hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
398a8aa8d2a685a8d41d5aacc5e7cf810d75073b
8,341
cpp
C++
jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp
mrRay/jit.gl.isf
81553e0c48f6030fcd67e0df2a48d38f0d98ee90
[ "MIT" ]
19
2019-04-28T11:53:46.000Z
2021-04-16T21:05:58.000Z
jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp
mrRay/jit.gl.isf
81553e0c48f6030fcd67e0df2a48d38f0d98ee90
[ "MIT" ]
6
2019-05-25T17:27:18.000Z
2020-09-01T01:11:25.000Z
jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp
mrRay/jit.gl.isf
81553e0c48f6030fcd67e0df2a48d38f0d98ee90
[ "MIT" ]
1
2020-08-14T15:39:10.000Z
2020-08-14T15:39:10.000Z
#include "ISFFileManager_Win.hpp" #include "VVISF.hpp" //#include <unistd.h> #include <sys/types.h> //#include <pwd.h> #include <algorithm> /* #include "jit.common.h" #include "jit.gl.h" //#include "ext_mess.h" */ #include <filesystem> using namespace std; using namespace VVGL; using namespace VVISF; void ISFFileManager_Win::populateEntries() { //post("%s",__func__); //cout << __PRETTY_FUNCTION__ << endl; lock_guard<recursive_mutex> lock(_lock); _fileEntries.clear(); GLContext::bootstrapGLEnvironmentIfNecessary(); // make a global buffer pool. we're going to destroy it before this method exits, we just need the pool so the ISFDocs we're about to create don't throw exceptions b/c they're unable to load image resources to disk (b/c there's no buffer pool) GLContextRef tmpCtx = CreateNewGLContextRef(NULL, AllocGL4ContextAttribs().get()); tmpCtx->makeCurrent(); CreateGlobalBufferPool(tmpCtx); // add the built-in 'color bars' ISF addBuiltInColorBarsISF(); // add the files in the global ISF library //insertFilesFromDirectory(string("/ProgramData/ISF"), true); // now add the files for the user-centric ISF library. this will overwrite any duplicate entries from the global lib. // under windows, the global ISF repository is /ProgramData/ISF on the boot drive const UINT maxPathLen = 300; UINT tmpPathLen = 0; TCHAR tmpPathBuf[maxPathLen]; // try to get the system directory tmpPathLen = GetSystemDirectory(tmpPathBuf, maxPathLen); std::filesystem::path rootPath; if (tmpPathLen > 0) { //wstring tmpWStr(tmpPathBuf); //string tmpStr(tmpPathBuf, tmpPathLen); //string tmpStr(tmpWStr.begin(), tmpWStr.end()); string tmpStr(tmpPathBuf); std::filesystem::path tmpPath(tmpStr); rootPath = tmpPath.root_path(); } // else we couldn't get the system directory for some reason... else { // get the root path for the current directory, assume that's the boot drive std::filesystem::path tmpPath = std::filesystem::current_path(); rootPath = tmpPath.root_path(); } //cout << "root path is " << rootPath << endl; std::filesystem::path isfDir = rootPath; isfDir /= "ProgramData"; isfDir /= "ISF"; if (std::filesystem::exists(isfDir)) { insertFilesFromDirectory(isfDir.string(), true); } /* cout << "exists() = " << std::filesystem::exists(isfDir) << endl; cout << "root_name() = " << isfDir.root_name() << endl; cout << "root_path() = " << isfDir.root_path() << endl; cout << "relative_path() = " << isfDir.relative_path() << endl; cout << "parent_path() = " << isfDir.parent_path() << endl; cout << "filename() = " << isfDir.filename() << endl; cout << "stem() = " << isfDir.stem() << endl; cout << "extension() = " << isfDir.extension() << endl; cout << "************************" << endl; // now add the default color bars ISF, so there's always at least one ISF loaded //string filename = string("Default ColorBars"); string tmpPathStr("c:/ProgramData/ISF"); std::filesystem::path tmpPath(tmpPathStr); cout << "exists() = " << std::filesystem::exists(tmpPath) << endl; cout << "root_name() = " << tmpPath.root_name() << endl; cout << "root_path() = " << tmpPath.root_path() << endl; cout << "relative_path() = " << tmpPath.relative_path() << endl; cout << "parent_path() = " << tmpPath.parent_path() << endl; cout << "filename() = " << tmpPath.filename() << endl; cout << "stem() = " << tmpPath.stem() << endl; cout << "extension() = " << tmpPath.extension() << endl; */ // DON'T FORGET TO DESTROY THIS GLOBAL BUFFER POOL SetGlobalBufferPool(); } ISFFile ISFFileManager_Win::fileEntryForName(const string & inName) { lock_guard<recursive_mutex> lock(_lock); ISFFile returnMe = ISFFile(string(""), string(""), ISFFileType_None, string(""), vector<string>()); try { returnMe = _fileEntries.at(inName); } catch (...) { } return returnMe; } vector<string> ISFFileManager_Win::fileNames() { lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; returnMe.reserve(_fileEntries.size()); for (const auto & fileIt : _fileEntries) { returnMe.push_back(fileIt.first); } return returnMe; } vector<string> ISFFileManager_Win::generatorNames() { lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; returnMe.reserve(_fileEntries.size()); for (const auto & fileIt : _fileEntries) { if ((fileIt.second.type() & ISFFileType_Source) == ISFFileType_Source) returnMe.push_back(fileIt.first); } return returnMe; } vector<string> ISFFileManager_Win::filterNames() { lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; returnMe.reserve(_fileEntries.size()); for (const auto & fileIt : _fileEntries) { if ((fileIt.second.type() & ISFFileType_Filter) == ISFFileType_Filter) returnMe.push_back(fileIt.first); } return returnMe; } vector<string> ISFFileManager_Win::transitionNames() { lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; returnMe.reserve(_fileEntries.size()); for (const auto & fileIt : _fileEntries) { if ((fileIt.second.type() & ISFFileType_Transition) == ISFFileType_Transition) returnMe.push_back(fileIt.first); } return returnMe; } vector<string> ISFFileManager_Win::categories() { //cout << __PRETTY_FUNCTION__ << endl; lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; // iterate through all the entries in the map for (const auto & fileIt : _fileEntries) { //cout << "\tchecking file " << fileIt.first << ", its cats are: "; // run through every cat in this entry's categories vector for (const auto & fileCat : fileIt.second.categories()) { //cout << fileCat << " "; // if the vector we're returning doesn't contain this category yet, add it if (find(returnMe.begin(), returnMe.end(), fileCat) == returnMe.end()) { returnMe.push_back(fileCat); } } //cout << endl; } return returnMe; } vector<string> ISFFileManager_Win::fileNamesForCategory(const string & inCategory) { lock_guard<recursive_mutex> lock(_lock); vector<string> returnMe; // iterate through all the entries in the map for (const auto & fileIt : _fileEntries) { // run through every cat in this entry's categories for (const auto & fileCat : fileIt.second.categories()) { // if this category is a match for the passed category, add it if (CaseInsensitiveCompare(fileCat, inCategory)) { returnMe.push_back(fileIt.first); break; } } } return returnMe; } void ISFFileManager_Win::insertFilesFromDirectory(const string & inDirRaw, const bool & inRecursive) { //post("%s ... %s, %d",__func__,inDirRaw.c_str(),inRecursive); //cout << __PRETTY_FUNCTION__ << "... " << inDirRaw << " : " << inRecursive << endl; // some static strings to avoid churn static string *_fsstr = nullptr; static string *_fragstr = nullptr; if (_fsstr == nullptr) { _fsstr = new string(".fs"); _fragstr = new string(".frag"); } filesystem::path inDir(inDirRaw); for (const auto & tmpDirEntry : std::filesystem::directory_iterator(inDir)) { string tmpExt = tmpDirEntry.path().extension().string(); //cout << "\ttmpDirEntry is " << tmpDirEntry.path() << ", ext is " << tmpExt << endl; bool isDir = tmpDirEntry.is_directory(); if (!isDir && (CaseInsensitiveCompare(tmpExt, *_fsstr) || CaseInsensitiveCompare(tmpExt, *_fragstr))) { ISFFile tmpFile = CreateISFFileFromPath(tmpDirEntry.path().string()); if (tmpFile.isValid()) { _fileEntries[tmpFile.filename()] = tmpFile; } } if (inRecursive && isDir) { insertFilesFromDirectory(tmpDirEntry.path().string(), inRecursive); } } } ISFFile CreateISFFileFromPath(const string & inPath) { //cout << __PRETTY_FUNCTION__ << "... " << inPath << endl; string filename = StringByDeletingExtension(LastPathComponent(inPath)); string filepath = inPath; //ISFFileType type; //string description; //vector<string> categories; ISFDocRef doc = CreateISFDocRef(filepath, nullptr, false); if (doc == nullptr) { return ISFFile(string(""), string(""), ISFFileType_None, string(""), vector<string>()); } //type = doc->type(); //description = doc->descripton(); //categories = doc->categories(); //return ISFFile(filename, filepath, type, description, categories); return ISFFile(filename, filepath, doc->type(), doc->description(), doc->categories()); }
32.582031
245
0.687927
mrRay
39906832e9940940eb1e4d81e5ad9fd0bd6da26f
172
hpp
C++
include/TextureManager.hpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
include/TextureManager.hpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
include/TextureManager.hpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
#ifndef TEXTURE_MANAGER_HPP_ #define TEXTURE_MANAGER_HPP_ #include <iostream> #include <vector> #include "stb/stb_image.h" class TextureManager { private: public: }; #endif
15.636364
28
0.796512
Frostie314159
39906b9a591240b78755180ee0087bdcebf54ed5
1,647
cpp
C++
018/4Sum.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
1
2018-06-24T13:58:07.000Z
2018-06-24T13:58:07.000Z
018/4Sum.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
null
null
null
018/4Sum.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> using namespace std; vector<vector<int>> fourSum(vector<int>&nums, int target){ vector<vector<int>> total; int n = nums.size(); if(n<4) return total; sort(nums.begin(),nums.end()); for (int i=0;i<n-3;i++){ if(i>0&&nums[i]==nums[i-1]) continue; if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break; if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue; for (int j = i+1;j<n-2;j++){ if(j>i+1&&nums[j]==nums[j-1]) continue; if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break; if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue; int left = j+1, right = n-1; while(left<right){ int sum = nums[i]+nums[j]+nums[left]+nums[right]; if(sum <target) left++; else if(sum>target) right--; else{ total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]}); do{left++;}while(left<right&&nums[left]==nums[left-1]); do{right--;}while(left<right&&nums[right]==nums[right+1]); } } } } return total; } int main(){ vector<int>nums = {1, 0, -1, 0, -2, 2}; vector<vector<int>>res = fourSum(nums, 0); for(int i = 0;i<res.size();i++){ for(int j = 0;j < res[0].size();j++) cout<<res[i][j]; cout<<endl; } return 0; }
35.804348
93
0.453552
Lixu518
39990e6a9d4dd6137bf85bcf89a84be908e31afd
5,553
cpp
C++
src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp
EECS-467-W20-RRRobot-Project/RRRobot
f5bfccab3b96e1908a81a987d5fed51ae3b9c738
[ "MIT" ]
1
2020-04-10T21:19:03.000Z
2020-04-10T21:19:03.000Z
src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp
EECS-467-W20-RRRobot-Project/RRRobot
f5bfccab3b96e1908a81a987d5fed51ae3b9c738
[ "MIT" ]
9
2020-04-10T18:47:54.000Z
2020-04-10T18:57:52.000Z
src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp
EECS-467-W20-RRRobot-Project/RRRobot
f5bfccab3b96e1908a81a987d5fed51ae3b9c738
[ "MIT" ]
null
null
null
// rrrobot_node.cpp #include <algorithm> #include <vector> #include <string> #include <stdlib.h> #include <time.h> #include <fstream> #include <iostream> #include <ros/ros.h> #include <osrf_gear/LogicalCameraImage.h> #include <osrf_gear/Order.h> #include <osrf_gear/Proximity.h> #include <osrf_gear/VacuumGripperState.h> #include <osrf_gear/ConveyorBeltControl.h> #include <sensor_msgs/JointState.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Range.h> #include <std_msgs/Float32.h> #include <std_msgs/String.h> #include <std_srvs/Trigger.h> #include <trajectory_msgs/JointTrajectory.h> #include "topic_names.h" #include "rrrobot/arm_command.h" using namespace std; class Position { public: float x, y, z; Position(float x, float y, float z) : x(x), y(y), z(z){}; Position() : x(0), y(0), z(0) {} }; class RRRobot { public: RRRobot(ros::NodeHandle &node) : current_robot_state(RobotState::WAITING_FOR_CLASSIFICATION | RobotState::WAITING_FOR_GRAB_LOCATION), nh(node) { cv_classification_sub = nh.subscribe(CV_CLASSIFICATION_CHANNEL, 1000, &RRRobot::cv_classification_callback, this); gripper_state_sub = nh.subscribe(GRIPPER_STATE_CHANNEL, 1000, &RRRobot::gripper_state_callback, this); depth_camera_sub = nh.subscribe(DESIRED_GRASP_POSE_CHANNEL, 1000, &RRRobot::grasp_pose_callback, this); conveyor_pub = nh.serviceClient<osrf_gear::ConveyorBeltControl>(CONVEYOR_POWER_CHANNEL); arm_destination_pub = nh.advertise<rrrobot::arm_command>(ARM_DESTINATION_CHANNEL, 1000); // start competition ros::ServiceClient comp_start = nh.serviceClient<std_srvs::Trigger>(START_COMPETITION_CHANNEL); std_srvs::Trigger trg; comp_start.call(trg); } void cv_classification_callback(const std_msgs::String &classification) { std::string type = classification.data.substr(classification.data.find(":") + 1); Position drop_point = destination(type); desired_drop_pose.position.x = drop_point.x; desired_drop_pose.position.y = drop_point.y; desired_drop_pose.position.z = drop_point.z; // update state if (current_robot_state & RobotState::WAITING_FOR_GRAB_LOCATION) { current_robot_state &= ~RobotState::WAITING_FOR_CLASSIFICATION; } else if ((current_robot_state & RobotState::MOVING_ARM) == 0x0) { current_robot_state = RobotState::MOVING_ARM; // tell the arm to move to grab the object publish_arm_command(); } // print_state(); } void gripper_state_callback(const osrf_gear::VacuumGripperState &state) { if (state.attached) { current_robot_state = RobotState::MOVING_ARM; if (!gripper_state.attached) { // start the conveyor belt again set_conveyor(100); } } // just dropped the object else if (gripper_state.attached /* && !state.attached */) { current_robot_state = RobotState::WAITING_FOR_CLASSIFICATION | RobotState::WAITING_FOR_GRAB_LOCATION; } // store current state gripper_state = state; // print_state(); } void grasp_pose_callback(const geometry_msgs::Pose &grasp_pose) { // stop conveyor belt set_conveyor(0); desired_grasp_pose = grasp_pose; // Add z offset so end effector doesn't hit object desired_grasp_pose.position.z += 0.01; if (current_robot_state & RobotState::WAITING_FOR_CLASSIFICATION) { current_robot_state &= ~RobotState::WAITING_FOR_GRAB_LOCATION; } else if ((current_robot_state & RobotState::MOVING_ARM) == 0x0) { current_robot_state = RobotState::MOVING_ARM; publish_arm_command(); } // print_state(); } private: enum RobotState { WAITING_FOR_CLASSIFICATION = 0x1, WAITING_FOR_GRAB_LOCATION = 0x1 << 1, MOVING_ARM = 0x1 << 2 }; int current_robot_state; osrf_gear::VacuumGripperState gripper_state; geometry_msgs::Pose desired_grasp_pose; geometry_msgs::Pose desired_drop_pose; ros::NodeHandle nh; ros::Subscriber cv_classification_sub; ros::Subscriber gripper_state_sub; // know when item has been grabbed, so conveyor can be started ros::Subscriber depth_camera_sub; // get desired grab location ros::ServiceClient conveyor_pub; ros::Publisher arm_destination_pub; Position trash_bin = Position(-0.3, 0.383, 1); Position recycle_bin = Position(-0.3, 1.15, 1); // Determine item destination bin based on classification Position destination(const std::string &type) const { Position pos; if (type == "trash") { pos = trash_bin; } else { pos = recycle_bin; } return pos; } // Publish message including grab and drop off location for arm controller void publish_arm_command() { rrrobot::arm_command cmd; cmd.grab_location = desired_grasp_pose; cmd.drop_location = desired_drop_pose; arm_destination_pub.publish(cmd); ros::spinOnce(); } // Set conveyor power (0 or 50-100) void set_conveyor(int power) { if (power != 0 && (power < 50 || power > 100)) { return; } osrf_gear::ConveyorBeltControl cmd; cmd.request.power = power; conveyor_pub.call(cmd); } // Print current state for debugging void print_state() { if (current_robot_state & RobotState::WAITING_FOR_CLASSIFICATION) { cout << "Waiting for classification\t"; } if (current_robot_state & RobotState::WAITING_FOR_GRAB_LOCATION) { cout << "Waiting for grab location\t"; } if (current_robot_state & RobotState::MOVING_ARM) { cout << "Moving Arm\t"; } cout << endl; } }; int main(int argc, char **argv) { ros::init(argc, argv, "rrrobot"); ros::NodeHandle node; RRRobot robot(node); ros::spin(); // This executes callbacks on new data until ctrl-c. return 0; }
24.355263
116
0.730956
EECS-467-W20-RRRobot-Project
399a2f37e219aff62ff05cca7e9dba3d15403c80
623
hh
C++
Tek2/Piscine-CPP/cpp_santa/Wrap.hh
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
30
2018-10-26T12:54:11.000Z
2022-02-04T18:18:57.000Z
Tek2/Piscine-CPP/cpp_santa/Wrap.hh
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
null
null
null
Tek2/Piscine-CPP/cpp_santa/Wrap.hh
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
26
2018-11-20T18:11:39.000Z
2022-01-28T21:05:30.000Z
// // Wrap.hh for in /home/guarni_l/cpp_santa // // Made by Luca GUARNIERI // Login <guarni_l@epitech.net> // // Started on Sat Jan 16 14:37:19 2016 Luca GUARNIERI // Last update Sun Jan 17 07:18:04 2016 Luca GUARNIERI // #ifndef WRAP_HH_ # define WRAP_HH_ # include "Object.hh" class Wrap : public Object { protected: Object *_gift; bool _open; public: Wrap(std::string const &title = "", std::string const &type = ""); ~Wrap(); void closeMe(); void openMe(); bool isOpen(); bool isWrapped(); Wrap &operator=(Wrap const &); virtual void wrapMeThat(Object *) = 0; }; #endif /* WRAP_HH_ */
18.878788
68
0.65008
Estayparadox
399a41d35d5666fda21d70dbb83dc61a8c6a0928
3,149
cc
C++
src/starkware/commitment_scheme/merkle/merkle_commitment_scheme.cc
ChihChengLiang/ethSTARK
032eda9f83d419eb2eaeef79d446fb77ecc3f019
[ "Apache-2.0" ]
null
null
null
src/starkware/commitment_scheme/merkle/merkle_commitment_scheme.cc
ChihChengLiang/ethSTARK
032eda9f83d419eb2eaeef79d446fb77ecc3f019
[ "Apache-2.0" ]
null
null
null
src/starkware/commitment_scheme/merkle/merkle_commitment_scheme.cc
ChihChengLiang/ethSTARK
032eda9f83d419eb2eaeef79d446fb77ecc3f019
[ "Apache-2.0" ]
null
null
null
#include "starkware/commitment_scheme/merkle/merkle_commitment_scheme.h" #include <algorithm> #include <string> #include "starkware/crypt_tools/blake2s_160.h" #include "starkware/error_handling/error_handling.h" #include "starkware/math/math.h" #include "starkware/stl_utils/containers.h" namespace starkware { MerkleCommitmentSchemeProver::MerkleCommitmentSchemeProver( size_t n_elements, size_t n_segments, ProverChannel* channel) : n_elements_(n_elements), n_segments_(n_segments), channel_(channel), // Initialize the tree with the number of elements, each element is the hash stored in a leaf. tree_(MerkleTree(n_elements_)) {} size_t MerkleCommitmentSchemeProver::NumSegments() const { return n_segments_; } uint64_t MerkleCommitmentSchemeProver::SegmentLengthInElements() const { return SafeDiv(n_elements_, n_segments_); } void MerkleCommitmentSchemeProver::AddSegmentForCommitment( gsl::span<const std::byte> segment_data, size_t segment_index) { ASSERT_RELEASE( segment_data.size() == SegmentLengthInElements() * kSizeOfElement, "Segment size is " + std::to_string(segment_data.size()) + " instead of the expected " + std::to_string(kSizeOfElement * SegmentLengthInElements()) + "."); tree_.AddData( segment_data.as_span<const Blake2s160>(), segment_index * SegmentLengthInElements()); } void MerkleCommitmentSchemeProver::Commit() { // After adding all segments, all inner tree nodes that are at least (tree_height - // log2(n_elements_in_segment_)) far from the root - were already computed. size_t tree_height = SafeLog2(tree_.GetDataLength()); const Blake2s160 commitment = tree_.GetRoot(tree_height - SafeLog2(SegmentLengthInElements())); channel_->SendCommitmentHash(commitment, "Commitment"); } std::vector<uint64_t> MerkleCommitmentSchemeProver::StartDecommitmentPhase( const std::set<uint64_t>& queries) { queries_ = queries; return {}; } void MerkleCommitmentSchemeProver::Decommit(gsl::span<const std::byte> elements_data) { ASSERT_RELEASE(elements_data.empty(), "element_data is expected to be empty."); tree_.GenerateDecommitment(queries_, channel_); } MerkleCommitmentSchemeVerifier::MerkleCommitmentSchemeVerifier( uint64_t n_elements, VerifierChannel* channel) : n_elements_(n_elements), channel_(channel) {} void MerkleCommitmentSchemeVerifier::ReadCommitment() { commitment_ = channel_->ReceiveCommitmentHash("Commitment"); } bool MerkleCommitmentSchemeVerifier::VerifyIntegrity( const std::map<uint64_t, std::vector<std::byte>>& elements_to_verify) { // Convert data to hashes. std::map<uint64_t, Blake2s160> hashes_to_verify; for (auto const& element : elements_to_verify) { ASSERT_RELEASE(element.first < n_elements_, "Query out of range."); ASSERT_RELEASE( element.second.size() == Blake2s160::kDigestNumBytes, "Element size mismatches."); hashes_to_verify[element.first] = Blake2s160::InitDigestTo(element.second); } // Verify decommitment. return MerkleTree::VerifyDecommitment(hashes_to_verify, n_elements_, *commitment_, channel_); } } // namespace starkware
39.3625
100
0.765005
ChihChengLiang
399c99bd2be8831407f02b878cc0f7c6deb5856b
4,738
cpp
C++
shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
5
2019-12-02T12:28:57.000Z
2021-04-07T21:21:13.000Z
shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
null
null
null
shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
1
2020-01-09T14:25:42.000Z
2020-01-09T14:25:42.000Z
// // Created by dottideveloper on 29.10.19. // #include <material/serialization.h> #include "vulkan_integration/resources/types/vulkanshadermoduleresource.h" #include "vulkan_integration/vulkandevicecapabilities.h" namespace engine::vulkan { //<----------------------------------------------------------------------------- // //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- // //<----------------------------------------------------------------------------- CEngineResult<> CVulkanShaderModuleResource::create( SShaderModuleDescriptor const &aDescription , SNoDependencies const &aDependencies , GpuApiResourceDependencies_t const &aResolvedDependencies) { SHIRABE_UNUSED(aResolvedDependencies); CVkApiResource<SShaderModule>::create(aDescription, aDependencies, aResolvedDependencies); Shared<IVkGlobalContext> vkContext = getVkContext(); VkDevice device = vkContext->getLogicalDevice(); std::unordered_map<VkShaderStageFlags, VkShaderModule> vkShaderModules {}; for(auto const &[stage, dataAccessor] : aDescription.shaderStages) { if(not dataAccessor) { // If we don't have any data to access, then don't create a shader module. continue; } ByteBuffer const data = dataAccessor(); // We need to convert from a regular 8-bit data buffer to uint32 words of SPIR-V. // TODO: Refactor the asset system to permit loading 32-bit buffers... std::vector<uint8_t> const &srcData = data.dataVector(); uint32_t const srcDataSize = srcData.size(); std::vector<uint32_t> convData {}; convData.resize( srcDataSize / 4 ); for(uint32_t k=0; k<srcDataSize; k += 4) { uint32_t const value = *reinterpret_cast<uint32_t const*>( srcData.data() + k ); convData[ k / 4 ] = value; } VkShaderModuleCreateInfo shaderModuleCreateInfo {}; shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; shaderModuleCreateInfo.pNext = nullptr; shaderModuleCreateInfo.flags = 0; shaderModuleCreateInfo.pCode = convData.data(); shaderModuleCreateInfo.codeSize = srcData.size(); VkShaderModule vkShaderModule = VK_NULL_HANDLE; VkResult const moduleCreationResult = vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, &vkShaderModule); if(VkResult::VK_SUCCESS != moduleCreationResult) { CLog::Error(logTag(), "Failed to create shader module for stage {}", stage); continue; } vkShaderModules.insert({ stage, vkShaderModule }); } this->handles = vkShaderModules; return { EEngineStatus::Ok }; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- // //<----------------------------------------------------------------------------- CEngineResult<> CVulkanShaderModuleResource::load() const { return { EEngineStatus::Ok }; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- // //<----------------------------------------------------------------------------- CEngineResult<> CVulkanShaderModuleResource::unload() const { return { EEngineStatus::Ok }; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- // //<----------------------------------------------------------------------------- CEngineResult<> CVulkanShaderModuleResource::destroy() { VkDevice device = getVkContext()->getLogicalDevice(); for(auto const &[stage, module] : this->handles) { vkDestroyShaderModule(device, module, nullptr); } this->handles.clear(); return EEngineStatus::Ok; } //<----------------------------------------------------------------------------- }
41.2
130
0.436471
BoneCrasher
399d5128af1add1705289fa1dbfa47b61822ea4c
5,855
cc
C++
gazebo/physics/Atmosphere_TEST.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
3
2018-07-17T00:17:13.000Z
2020-05-26T08:39:25.000Z
gazebo/physics/Atmosphere_TEST.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-04T10:26:04.000Z
2020-06-04T10:26:04.000Z
gazebo/physics/Atmosphere_TEST.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
2
2019-11-10T07:19:09.000Z
2019-11-21T19:11:11.000Z
/* * Copyright (C) 2016 Open Source Robotics Foundation * * 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 "gazebo/test/ServerFixture.hh" #include "gazebo/msgs/msgs.hh" using namespace gazebo; class AtmosphereTest : public ServerFixture, public testing::WithParamInterface<const char*> { /// \brief Callback for gztopic "~/response". /// \param[in] _msg Message received from topic. public: void OnAtmosphereMsgResponse(ConstResponsePtr &_msg); /// \brief Test getting/setting atmosphere model parameters. /// \param[in] _atmosphere Name of the atmosphere model. public: void AtmosphereParam(const std::string &_atmosphere); /// \brief Test default atmosphere model parameters /// \param[in] _atmosphere Name of the atmosphere model. public: void AtmosphereParamBool(const std::string &_atmosphere); /// \brief Incoming atmosphere message. public: static msgs::Atmosphere atmospherePubMsg; /// \brief Received atmosphere message. public: static msgs::Atmosphere atmosphereResponseMsg; }; msgs::Atmosphere AtmosphereTest::atmospherePubMsg; msgs::Atmosphere AtmosphereTest::atmosphereResponseMsg; ///////////////////////////////////////////////// void AtmosphereTest::OnAtmosphereMsgResponse(ConstResponsePtr &_msg) { if (_msg->type() == atmospherePubMsg.GetTypeName()) atmosphereResponseMsg.ParseFromString(_msg->serialized_data()); } ///////////////////////////////////////////////// void AtmosphereTest::AtmosphereParam(const std::string &_atmosphere) { atmospherePubMsg.Clear(); atmosphereResponseMsg.Clear(); this->Load("worlds/empty.world", false); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); transport::NodePtr atmosphereNode; atmosphereNode = transport::NodePtr(new transport::Node()); atmosphereNode->Init(); transport::PublisherPtr atmospherePub = atmosphereNode->Advertise<msgs::Atmosphere>("~/atmosphere"); transport::PublisherPtr requestPub = atmosphereNode->Advertise<msgs::Request>("~/request"); transport::SubscriberPtr responsePub = atmosphereNode->Subscribe("~/response", &AtmosphereTest::OnAtmosphereMsgResponse, this); ASSERT_EQ(_atmosphere, "adiabatic"); atmospherePubMsg.set_type(msgs::Atmosphere::ADIABATIC); atmospherePubMsg.set_temperature(0.01); atmospherePubMsg.set_pressure(500); atmospherePubMsg.set_mass_density(174.18084087484144); atmospherePub->Publish(atmospherePubMsg); msgs::Request *requestMsg = msgs::CreateRequest("atmosphere_info", ""); requestPub->Publish(*requestMsg); int waitCount = 0, maxWaitCount = 3000; while (atmosphereResponseMsg.ByteSize() == 0 && ++waitCount < maxWaitCount) common::Time::MSleep(10); ASSERT_LT(waitCount, maxWaitCount); EXPECT_DOUBLE_EQ(atmosphereResponseMsg.temperature(), atmospherePubMsg.temperature()); EXPECT_DOUBLE_EQ(atmosphereResponseMsg.pressure(), atmospherePubMsg.pressure()); EXPECT_DOUBLE_EQ(atmosphereResponseMsg.mass_density(), atmospherePubMsg.mass_density()); // Test Atmosphere::[GS]etParam() { physics::Atmosphere &atmosphere = world->Atmosphere(); double temperature = atmosphere.Temperature(); EXPECT_DOUBLE_EQ(temperature, atmospherePubMsg.temperature()); } // Test SetParam for non-implementation-specific parameters physics::Atmosphere &atmosphere = world->Atmosphere(); double temperature = 0.02; double pressure = 0.03; double temperatureGradient = 0.05; atmosphere.SetTemperature(temperature); EXPECT_NEAR(atmosphere.Temperature(), temperature, 1e-6); atmosphere.SetPressure(pressure); EXPECT_NEAR(atmosphere.Pressure(), pressure, 1e-6); atmosphere.SetTemperatureGradient(temperatureGradient); EXPECT_NEAR(atmosphere.TemperatureGradient(), temperatureGradient, 1e-6); atmosphereNode->Fini(); } ///////////////////////////////////////////////// TEST_P(AtmosphereTest, AtmosphereParam) { AtmosphereParam(this->GetParam()); } ///////////////////////////////////////////////// void AtmosphereTest::AtmosphereParamBool (const std::string &_atmosphere) { Load("worlds/empty.world", false); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); physics::Atmosphere &atmosphere = world->Atmosphere(); // Test shared atmosphere model parameter(s) EXPECT_NEAR(atmosphere.Temperature(), 288.15, 1e-6); EXPECT_NEAR(atmosphere.MassDensity(), 1.2249782197913108, 1e-6); EXPECT_NEAR(atmosphere.Pressure(), 101325, 1e-6); EXPECT_NEAR(atmosphere.TemperatureGradient(), -0.0065, 1e-6); EXPECT_EQ(atmosphere.Type(), _atmosphere); // Test atmosphere model parameters at a given altitude if (_atmosphere == "adiabatic") { double altitude = 1000; EXPECT_NEAR(atmosphere.Temperature(altitude), 281.64999999999998, 1e-6); EXPECT_NEAR(atmosphere.MassDensity(altitude), 1.1117154882870524, 1e-6); EXPECT_NEAR(atmosphere.Pressure(altitude), 89882.063292207444, 1e-6); } } ///////////////////////////////////////////////// TEST_P(AtmosphereTest, AtmosphereParamBool) { AtmosphereParamBool(this->GetParam()); } INSTANTIATE_TEST_CASE_P(Atmospheres, AtmosphereTest, ::testing::Values("adiabatic")); int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.64497
80
0.713749
SamFerwerda
399d894f9b444c6a9f8b02cd4559b64037312864
15,160
cpp
C++
test/hotspot/jtreg/vmTestbase/nsk/jvmti/IsMethodObsolete/isobsolete001/isobsolete001.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jvmti/IsMethodObsolete/isobsolete001/isobsolete001.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jvmti/IsMethodObsolete/isobsolete001/isobsolete001.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <string.h> #include "jvmti.h" #include "agent_common.h" #include "jni_tools.h" #include "jvmti_tools.h" extern "C" { /* ============================================================================= */ /* scaffold objects */ static jlong timeout = 0; /* constant names */ #define DEBUGEE_CLASS_NAME "nsk/jvmti/IsMethodObsolete/isobsolete001" #define TESTED_CLASS_NAME "nsk/jvmti/IsMethodObsolete/isobsolete001r" #define TESTED_CLASS_SIG "L" TESTED_CLASS_NAME ";" #define TESTED_THREAD_NAME "testedThread" #define CLASSFILE_FIELD_NAME "classfileBytes" #define CLASSFILE_FIELD_SIG "[B" #define STATIC_METHOD_NAME "testedStaticMethod" #define STATIC_METHOD_SIG "(I" TESTED_CLASS_SIG ")I" #define INSTANCE_METHOD_NAME "testedInstanceMethod" #define INSTANCE_METHOD_SIG "(I)I" /* constants */ #define MAX_STACK_DEPTH 64 /* ============================================================================= */ /** Check is method obsolete is as expected. */ static void checkMethodObsolete(jvmtiEnv* jvmti, jmethodID method, const char name[], const char kind[], jboolean expected) { jboolean obsolete = JNI_FALSE; NSK_DISPLAY3("Call IsObsolete() for %s method: %p (%s)\n", kind, (void*)method, name); if (!NSK_JVMTI_VERIFY( jvmti->IsMethodObsolete(method, &obsolete))) { nsk_jvmti_setFailStatus(); } NSK_DISPLAY1(" ... got obsolete: %d\n", (int)obsolete); if (obsolete != expected) { NSK_COMPLAIN4("IsObsolete() returns unexpected value for %s method: %s\n" "# return value: %d\n" "# expected: %d\n", kind, name, (int)obsolete, (int)expected); nsk_jvmti_setFailStatus(); } } /** Check is obsolete for methods on the stack are as expected. */ static void checkStackMethodsObsolete(jvmtiEnv* jvmti, jthread thread, const char kind[], jboolean expected) { jvmtiFrameInfo frameStack[MAX_STACK_DEPTH]; jint frameCount = 0; NSK_DISPLAY1("Get stack frames for thread: %p\n", (void*)thread); if (!NSK_JVMTI_VERIFY( jvmti->GetStackTrace(thread, 0, MAX_STACK_DEPTH, frameStack, &frameCount))) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... got frames: %d\n", (int)frameCount); NSK_DISPLAY1("Check methods of each frame: %d frames\n", (int)frameCount); { int found = 0; int i; for (i = 0; i < frameCount; i++) { char* name = NULL; char* signature = NULL; char* generic = NULL; char* kind = NULL; NSK_DISPLAY1(" frame #%i:\n", i); NSK_DISPLAY1(" methodID: %p\n", (void*)frameStack[i].method); if (!NSK_JVMTI_VERIFY( jvmti->GetMethodName(frameStack[i].method, &name, &signature, &generic))) { nsk_jvmti_setFailStatus(); continue; } NSK_DISPLAY1(" name: %s\n", nsk_null_string(name)); NSK_DISPLAY1(" signature: %s\n", nsk_null_string(signature)); NSK_DISPLAY1(" generic: %s\n", nsk_null_string(generic)); if (name != NULL && (strcmp(STATIC_METHOD_NAME, name) == 0 || strcmp(INSTANCE_METHOD_NAME, name) == 0)) { found++; NSK_DISPLAY1("SUCCESS: found redefined method on stack: %s\n", name); checkMethodObsolete(jvmti, frameStack[i].method, name, "obsolete redefined", expected); } if (!NSK_JVMTI_VERIFY( jvmti->Deallocate((unsigned char*)name))) { nsk_jvmti_setFailStatus(); } if (!NSK_JVMTI_VERIFY( jvmti->Deallocate((unsigned char*)signature))) { nsk_jvmti_setFailStatus(); } if (!NSK_JVMTI_VERIFY( jvmti->Deallocate((unsigned char*)generic))) { nsk_jvmti_setFailStatus(); } } if (found < 2) { NSK_COMPLAIN3("Not all %s methods found on stack:\n" "# found methods: %d\n" "# expected: %d\n", kind, found, 2); nsk_jvmti_setFailStatus(); } } } /** Redefine class with given bytecode. */ static int redefineClass(jvmtiEnv* jvmti, jclass klass, const char className[], jint size, unsigned char bytes[]) { jvmtiClassDefinition classDef; classDef.klass = klass; classDef.class_byte_count = size; classDef.class_bytes = bytes; NSK_DISPLAY1("Redefine class: %s\n", className); if (!NSK_JVMTI_VERIFY( jvmti->RedefineClasses(1, &classDef))) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... redefined with classfile: %d bytes\n", (int)size); return NSK_TRUE; } /** Get classfile bytes to redefine. */ static int getClassfileBytes(JNIEnv* jni, jvmtiEnv* jvmti, jint* size, unsigned char* *bytes) { jclass debugeeClass = NULL; jfieldID fieldID = NULL; jbyteArray array = NULL; jbyte* elements; int i; NSK_DISPLAY1("Find debugee class: %s\n", DEBUGEE_CLASS_NAME); if (!NSK_JNI_VERIFY(jni, (debugeeClass = jni->FindClass(DEBUGEE_CLASS_NAME)) != NULL)) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... found class: %p\n", (void*)debugeeClass); NSK_DISPLAY1("Find static field: %s\n", CLASSFILE_FIELD_NAME); if (!NSK_JNI_VERIFY(jni, (fieldID = jni->GetStaticFieldID(debugeeClass, CLASSFILE_FIELD_NAME, CLASSFILE_FIELD_SIG)) != NULL)) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... got fieldID: %p\n", (void*)fieldID); NSK_DISPLAY1("Get classfile bytes array from static field: %s\n", CLASSFILE_FIELD_NAME); if (!NSK_JNI_VERIFY(jni, (array = (jbyteArray) jni->GetStaticObjectField(debugeeClass, fieldID)) != NULL)) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... got array object: %p\n", (void*)array); if (!NSK_JNI_VERIFY(jni, (*size = jni->GetArrayLength(array)) > 0)) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... got array size: %d bytes\n", (int)*size); { jboolean isCopy; if (!NSK_JNI_VERIFY(jni, (elements = jni->GetByteArrayElements(array, &isCopy)) != NULL)) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } } NSK_DISPLAY1(" ... got elements list: %p\n", (void*)elements); if (!NSK_JVMTI_VERIFY( jvmti->Allocate(*size, bytes))) { nsk_jvmti_setFailStatus(); return NSK_FALSE; } NSK_DISPLAY1(" ... created bytes array: %p\n", (void*)*bytes); for (i = 0; i < *size; i++) { (*bytes)[i] = (unsigned char)elements[i]; } NSK_DISPLAY1(" ... copied bytecode: %d bytes\n", (int)*size); NSK_DISPLAY1("Release elements list: %p\n", (void*)elements); NSK_TRACE(jni->ReleaseByteArrayElements(array, elements, JNI_ABORT)); NSK_DISPLAY0(" ... released\n"); return NSK_TRUE; } /** Agent algorithm. */ static void JNICALL agentProc(jvmtiEnv* jvmti, JNIEnv* jni, void* arg) { NSK_DISPLAY0("Wait for tested methods to run\n"); if (!NSK_VERIFY(nsk_jvmti_waitForSync(timeout))) return; /* perform testing */ { jclass testedClass = NULL; jobject testedThread = NULL; jmethodID staticMethodID = NULL; jmethodID instanceMethodID = NULL; unsigned char* classfileBytes = NULL; jint classfileSize = 0; NSK_DISPLAY0(">>> Obtain bytes for class file redefinition\n"); { if (!NSK_VERIFY(getClassfileBytes(jni, jvmti, &classfileSize, &classfileBytes))) return; } NSK_DISPLAY0(">>> Find tested methods and running thread\n"); { NSK_DISPLAY1("Find tested class: %s\n", TESTED_CLASS_NAME); if (!NSK_JNI_VERIFY(jni, (testedClass = jni->FindClass(TESTED_CLASS_NAME)) != NULL)) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... found class: %p\n", (void*)testedClass); NSK_DISPLAY1("Make global reference for class object: %p\n", (void*)testedClass); if (!NSK_JNI_VERIFY(jni, (testedClass = (jclass) jni->NewGlobalRef(testedClass)) != NULL)) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... got reference: %p\n", (void*)testedClass); NSK_DISPLAY1("Get static methodID: %s\n", STATIC_METHOD_NAME); if (!NSK_JNI_VERIFY(jni, (staticMethodID = jni->GetStaticMethodID(testedClass, STATIC_METHOD_NAME, STATIC_METHOD_SIG)) != NULL)) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... got methodID: %p\n", (void*)staticMethodID); NSK_DISPLAY1("Get instance methodID: %s\n", INSTANCE_METHOD_NAME); if (!NSK_JNI_VERIFY(jni, (instanceMethodID = jni->GetMethodID(testedClass, INSTANCE_METHOD_NAME, INSTANCE_METHOD_SIG)) != NULL)) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... got methodID: %p\n", (void*)instanceMethodID); NSK_DISPLAY1("Find thread with running methods by name: %s\n", TESTED_THREAD_NAME); if (!NSK_VERIFY((testedThread = nsk_jvmti_threadByName(TESTED_THREAD_NAME)) != NULL)) { nsk_jvmti_setFailStatus(); return; } NSK_DISPLAY1(" ... got thread reference: %p\n", (void*)testedThread); } NSK_DISPLAY0(">>> Testcase #1: check IsObsolete() for methods before class redefinition\n"); { checkMethodObsolete(jvmti, staticMethodID, STATIC_METHOD_NAME, "not yet redefined", JNI_FALSE); checkMethodObsolete(jvmti, instanceMethodID, INSTANCE_METHOD_NAME, "not yet redefined", JNI_FALSE); } NSK_DISPLAY0(">>> Testcase #2: check IsObsolete() for methods on stack before class redefinition\n"); { checkStackMethodsObsolete(jvmti, testedThread, "not yet redefined", JNI_FALSE); } NSK_DISPLAY0(">>> Redefine class while methods are on the stack\n"); { if (!NSK_VERIFY(redefineClass(jvmti, testedClass, TESTED_CLASS_NAME, classfileSize, classfileBytes))) return; } NSK_DISPLAY0(">>> Testcase #3: check IsObsolete() for methods after class redefinition\n"); { checkMethodObsolete(jvmti, staticMethodID, STATIC_METHOD_NAME, "redefined", JNI_FALSE); checkMethodObsolete(jvmti, instanceMethodID, INSTANCE_METHOD_NAME, "redefined", JNI_FALSE); } NSK_DISPLAY0(">>> Testcase #4: check IsObsolete() for obsoleted methods on stack after class redefinition\n"); { checkStackMethodsObsolete(jvmti, testedThread, "obsolete redefined", JNI_TRUE); } NSK_DISPLAY0(">>> Clean used data\n"); { NSK_DISPLAY1("Deallocate classfile bytes array: %p\n", (void*)classfileBytes); if (!NSK_JVMTI_VERIFY( jvmti->Deallocate(classfileBytes))) { nsk_jvmti_setFailStatus(); } NSK_DISPLAY1("Delete global eference to thread: %p\n", (void*)testedThread); NSK_TRACE(jni->DeleteGlobalRef(testedThread)); NSK_DISPLAY1("Delete global reference to class: %p\n", (void*)testedClass); NSK_TRACE(jni->DeleteGlobalRef(testedClass)); } } NSK_DISPLAY0("Let debugee to finish\n"); if (!NSK_VERIFY(nsk_jvmti_resumeSync())) return; } /* ============================================================================= */ /** Agent library initialization. */ #ifdef STATIC_BUILD JNIEXPORT jint JNICALL Agent_OnLoad_isobsolete001(JavaVM *jvm, char *options, void *reserved) { return Agent_Initialize(jvm, options, reserved); } JNIEXPORT jint JNICALL Agent_OnAttach_isobsolete001(JavaVM *jvm, char *options, void *reserved) { return Agent_Initialize(jvm, options, reserved); } JNIEXPORT jint JNI_OnLoad_isobsolete001(JavaVM *jvm, char *options, void *reserved) { return JNI_VERSION_1_8; } #endif jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { jvmtiEnv* jvmti = NULL; /* init framework and parse options */ if (!NSK_VERIFY(nsk_jvmti_parseOptions(options))) return JNI_ERR; timeout = nsk_jvmti_getWaitTime() * 60 * 1000; /* create JVMTI environment */ if (!NSK_VERIFY((jvmti = nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL)) return JNI_ERR; /* add required capabilities */ { jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_redefine_classes = 1; if (!NSK_JVMTI_VERIFY( jvmti->AddCapabilities(&caps))) { return JNI_ERR; } } /* register agent proc and arg */ if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL))) return JNI_ERR; return JNI_OK; } /* ============================================================================= */ }
37.432099
118
0.577309
1690296356
399db7b9cb01f3cad58f6479f2145cf6826b3046
14,799
inl
C++
include/UDRefl/details/Object.inl
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
include/UDRefl/details/Object.inl
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
include/UDRefl/details/Object.inl
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
#pragma once #include <array> namespace Ubpa::UDRefl { // // ObjectPtrBase ////////////////// template<typename... Args> InvocableResult ObjectPtrBase::IsInvocable(StrID methodID) const noexcept { std::array argTypeIDs = { TypeID::of<Args>... }; return IsInvocable(ID, methodID, Span<const TypeID>{argTypeIDs}); } template<typename T> T ObjectPtrBase::InvokeRet(StrID methodID, Span<const TypeID> argTypeIDs, void* args_buffer) const { using U = std::conditional_t<std::is_reference_v<T>, std::add_pointer_t<T>, T>; std::uint8_t result_buffer[sizeof(U)]; auto result = Invoke(methodID, result_buffer, argTypeIDs, args_buffer); assert(result.resultID == TypeID::of<T>); return result.Move<T>(result_buffer); } template<typename... Args> InvokeResult ObjectPtrBase::InvokeArgs(StrID methodID, void* result_buffer, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return Invoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), result_buffer); } else return Invoke(methodID, {}, nullptr, result_buffer); } template<typename T, typename... Args> T ObjectPtrBase::Invoke(StrID methodID, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return InvokeRet<T>(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data())); } else return InvokeRet<T>(methodID); } template<typename... Args> SharedObject ObjectPtrBase::MInvoke( StrID methodID, std::pmr::memory_resource* rst_rsrc, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc); } else return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc); } template<typename... Args> SharedObject ObjectPtrBase::DMInvoke( StrID methodID, Args... args) const { return MInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...); } template<typename... Args> SharedObject ObjectPtrBase::AMInvoke( StrID methodID, std::pmr::memory_resource* rst_rsrc, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { ArgID<Args>(std::forward<Args>(args))... }; std::array args_buffer{ reinterpret_cast<std::size_t>(ArgPtr(args))... }; return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc); } else return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc); } template<typename... Args> SharedObject ObjectPtrBase::ADMInvoke( StrID methodID, Args... args) const { return AMInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...); } // // ObjectPtr ////////////// template<typename... Args> InvocableResult ObjectPtr::IsInvocable(StrID methodID) const noexcept { std::array argTypeIDs = { TypeID::of<Args>... }; return IsInvocable(ID, methodID, Span<const TypeID>{argTypeIDs}); } template<typename T> T ObjectPtr::InvokeRet(StrID methodID, Span<const TypeID> argTypeIDs, void* args_buffer) const {\ if constexpr (!std::is_void_v<T>) { using U = std::conditional_t<std::is_reference_v<T>, std::add_pointer_t<T>, T>; std::uint8_t result_buffer[sizeof(U)]; auto result = Invoke(methodID, result_buffer, argTypeIDs, args_buffer); assert(result.resultID == TypeID::of<T>); return result.Move<T>(result_buffer); } else Invoke(methodID, nullptr, argTypeIDs, args_buffer); } template<typename... Args> InvokeResult ObjectPtr::InvokeArgs(StrID methodID, void* result_buffer, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return Invoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), result_buffer); } else return Invoke(methodID, {}, nullptr, result_buffer); } template<typename T, typename... Args> T ObjectPtr::Invoke(StrID methodID, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return InvokeRet<T>(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data())); } else return InvokeRet<T>(methodID); } template<typename... Args> SharedObject ObjectPtr::MInvoke( StrID methodID, std::pmr::memory_resource* rst_rsrc, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { TypeID::of<Args>... }; std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... }; return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc); } else return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc); } template<typename... Args> SharedObject ObjectPtr::DMInvoke( StrID methodID, Args... args) const { return MInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...); } template<typename... Args> SharedObject ObjectPtr::AMInvoke( StrID methodID, std::pmr::memory_resource* rst_rsrc, Args... args) const { if constexpr (sizeof...(Args) > 0) { static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...)); std::array argTypeIDs = { ArgID<Args>(std::forward<Args>(args))... }; std::array args_buffer{ reinterpret_cast<std::size_t>(ArgPtr(args))... }; return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc); } else return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc); } template<typename... Args> SharedObject ObjectPtr::ADMInvoke( StrID methodID, Args... args) const { return AMInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...); } } template<> struct std::hash<Ubpa::UDRefl::ObjectPtr> { std::size_t operator()(const Ubpa::UDRefl::ObjectPtr& obj) const noexcept { return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr()); } }; template<> struct std::hash<Ubpa::UDRefl::ConstObjectPtr> { std::size_t operator()(const Ubpa::UDRefl::ConstObjectPtr& obj) const noexcept { return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr()); } }; template<> struct std::hash<Ubpa::UDRefl::SharedObject> { std::size_t operator()(const Ubpa::UDRefl::SharedObject& obj) const noexcept { return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr()); } }; template<> struct std::hash<Ubpa::UDRefl::SharedConstObject> { std::size_t operator()(const Ubpa::UDRefl::SharedConstObject& obj) const noexcept { return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr()); } }; namespace std { inline void swap(Ubpa::UDRefl::SharedObject& left, Ubpa::UDRefl::SharedObject& right) noexcept { left.Swap(right); } inline void swap(Ubpa::UDRefl::SharedConstObject& left, Ubpa::UDRefl::SharedConstObject& right) noexcept { left.Swap(right); } } template<typename T> struct Ubpa::UDRefl::IsObjectOrPtr { private: using U = std::remove_cv_t<T>; public: static constexpr bool value = std::is_same_v<T, ObjectPtr> || std::is_same_v<T, ConstObjectPtr> || std::is_same_v<T, SharedObject> || std::is_same_v<T, SharedConstObject>; }; template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator==(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) == Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator!=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) != Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) < Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) > Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) <= Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) >= Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> T& operator<<(T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { return ptr >> lhs; } //template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> //Ubpa::UDRefl::SharedObject operator>>(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) { // return ptr << lhs; //} template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator==(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) == ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator!=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) != ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) < ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) > ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) <= ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return Ubpa::UDRefl::Ptr(lhs) >= ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> T& operator<<(T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return ptr >> lhs; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> Ubpa::UDRefl::SharedObject operator>>(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) { return ptr << lhs; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator==(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) == Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator!=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) != Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) < Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) > Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) <= Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) >= Ubpa::UDRefl::ConstCast(ptr); } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> T& operator<<(T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { return ptr >> lhs; } //template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> //Ubpa::UDRefl::SharedObject operator>>(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) { // return ptr << lhs; //} template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator==(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) == ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator!=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) != ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) < ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) > ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator<=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) <= ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> bool operator>=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return Ubpa::UDRefl::Ptr(lhs) >= ptr; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> T& operator<<(T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return ptr >> lhs; } template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0> Ubpa::UDRefl::SharedObject operator>>(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) { return ptr << lhs; }
36.905237
116
0.693493
zerger
39a22d72475d40fe80590b67e8c7068a5926cedf
821
cpp
C++
HackerRank/Challenges/compare-the-triplets.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Challenges/compare-the-triplets.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Challenges/compare-the-triplets.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <vector> using namespace std; void addIf(vector<int> &results, int a, int b) { if (a > b) { results[0]++; } else if (a < b) { results[1]++; } } vector<int> solve(int a0, int a1, int a2, int b0, int b1, int b2) { vector<int> results = vector<int>(2, 0); addIf(results, a0, b0); addIf(results, a1, b1); addIf(results, a2, b2); return results; } int main() { int a0; int a1; int a2; cin >> a0 >> a1 >> a2; int b0; int b1; int b2; cin >> b0 >> b1 >> b2; vector<int> result = solve(a0, a1, a2, b0, b1, b2); for (ssize_t i = 0; i < result.size(); i++) { cout << result[i] << (i != result.size() - 1 ? " " : ""); } cout << endl; return EXIT_SUCCESS; }
17.847826
65
0.501827
Diggzinc
39a5cab860d715ba666ff4c97e096f82308098f1
5,307
cpp
C++
Bebop2cpp-master/SNAP/SNAP_rudi.cpp
jmenden1/SNAP
a253aa052e4568cdc35e7ff5789b3e716ccbb4da
[ "MIT" ]
null
null
null
Bebop2cpp-master/SNAP/SNAP_rudi.cpp
jmenden1/SNAP
a253aa052e4568cdc35e7ff5789b3e716ccbb4da
[ "MIT" ]
null
null
null
Bebop2cpp-master/SNAP/SNAP_rudi.cpp
jmenden1/SNAP
a253aa052e4568cdc35e7ff5789b3e716ccbb4da
[ "MIT" ]
null
null
null
#include <vector> #include "Drone.h" #include <math.h> #include <boost/asio/io_service.hpp> #include <Fullnavdata.h> #include <gnuplot_iostream.h> #include <deque> #include <fstream> #include <iostream> #include <sstream> /* * PRIVATE HEADER */ #define DRONE_IP "192.168.42.1" #define DRONE_MAX_ALTITUDE 1.0 #define DRONE_MAX_HORIZONTAL_SPEED 0.3 #define DRONE_MAX_VERTICAL_SPEED 0.3 #define LAND_AFTER_LAST_WAYPOINT true #define CALIBRATION_FILE "res/calib_bd2.xml" #define HULLPROTECTIONON true #define LOOK_FOR_CHESSBOARD false #define MAX_COORD 10000000 using namespace std; void ReadyToReadScan(); void ReadScanFile(string fn); double * CheckSmallestCoord(double x, double y, int check_x_or_y, double current_min[], int negative); /* TODO: Need to uncomment drone code if trying to use drone; currently just trying to make a droneless code */ //Drone bebop; /* Signal catches; if a process dies, we need drone to emergency stop */ /* void kill_handler (int junk) { signal(SIGINT, kill_handler); cout << endl << "AHHHHHHHHHHHH, WHAT ARE YOU DOING" << endl; bebop.emergency(); exit(1); } */ int main(int argc, char *argv[]) { cout << argc << endl; if( argc != 2 ) { //need to put the file name of where the scans will go; // this assumes all scans will go to the same file cout << "PUT IN A FILE NAME, FOOL!" << endl; exit(0); } /* SETUP FOR DONE */ /* signal(SIGINT, kill_handler); bebop.connect(); while(!bebop.isRunning()){ sleep(1); } bebop.setMaxAltitude(DRONE_MAX_ALTITUDE); bebop.setMaxHorizontalSpeed(DRONE_MAX_HORIZONTAL_SPEED); bebop.setMaxVerticalSpeed(DRONE_MAX_VERTICAL_SPEED); if(bebop.blockingFlatTrim()) { std::cout << "FLAT TRIM IS OK" << std::endl; } else { std::cerr << "FLAT TRIM NOT OK" << std::endl; return 1; } */ /*END SETUP*/ /* This is very rudimentary; the drone cannot currently fly with everything on it. */ string file_name = argv[1]; bool getting_info_loop = true; while(getting_info_loop) { ReadyToReadScan(); ReadScanFile(file_name); } exit(0); } /* This just makes sure the user is */ void ReadyToReadScan() { char scan_ready; cout << "Ready for next scan (y for yes; e for exit)" << endl; bool scan_ready_loop = true; while(scan_ready_loop) { cin >> scan_ready; switch(scan_ready) { case 'y': scan_ready_loop = false; break; case 'e': exit(0); break; default: cout << "FOOL, DO NOT TEST ME!" << endl; } } } void ReadScanFile(string fn) { ifstream fin; double x_info; double y_info; double z_info; /* double smallest_forward_x[2] = {MAX_COORD, MAX_COORD}; double smallest_backward_x[2] = {MAX_COORD, MAX_COORD}; double smallest_left_y[2] = {MAX_COORD, MAX_COORD}; double smallest_right_y[2] = {MAX_COORD, MAX_COORD}; */ double *smallest_forward_x = NULL; double *smallest_backward_x = NULL; double *smallest_left_y = NULL; double *smallest_right_y = NULL; string info_line; fin.open(fn); //the first line is the "NODE" line, which should be discarded here getline(fin, info_line); //getting each x and y pair of data while( getline(fin, info_line) ) { cout << info_line << endl; istringstream iss(info_line); iss >> x_info; iss >> y_info; iss >> z_info; if( x_info < 0) { smallest_backward_x = CheckSmallestCoord(x_info, y_info, 0, smallest_backward_x, 1); } if( x_info >= 0 ) { smallest_forward_x = CheckSmallestCoord(x_info, y_info, 0, smallest_forward_x, 0); } //TODO: THIS MIGHT BE BACKWARDS, need to check!!!!!!!!!!!!!!!!!!!! if( y_info < 0 ) { smallest_left_y = CheckSmallestCoord(x_info, y_info, 1, smallest_left_y, 1); } if( y_info >= 0 ) { smallest_right_y = CheckSmallestCoord(x_info, y_info, 1, smallest_right_y, 0); } } cout << "SBX: " << smallest_backward_x[0] << " " << smallest_backward_x[1] << endl; cout << "SFX: " << smallest_forward_x[0] << " " << smallest_forward_x[1] << endl; cout << "SLY: " << smallest_left_y[0] << " " << smallest_left_y[1] << endl; cout << "SRY: " << smallest_right_y[0] << " " << smallest_right_y[1] << endl; fin.close(); } /* check_x_or_y means which index it should be checking in the array: 0 for x, 1 for y */ double * CheckSmallestCoord(double x, double y, int check_x_or_y, double current_min[], int negative) { double * new_min_array = new double[2]; //if it is the first loop, need to set the min to current point if( current_min == NULL ) { new_min_array[0] = x; new_min_array[1] = y; return new_min_array; } double check_min = current_min[check_x_or_y]; new_min_array[0] = current_min[0]; new_min_array[1] = current_min[1]; //checking x if( check_x_or_y == 0 ) { if( check_min > x && negative == 0) { new_min_array[0] = x; new_min_array[1] = y; } else if( check_min < x && negative == 1) { new_min_array[0] = x; new_min_array[1] = y; } } //checking y if( check_x_or_y == 1 ) { if( check_min > y && negative == 0 ) { new_min_array[0] = x; new_min_array[1] = y; } else if( check_min < y && negative == 1) { new_min_array[0] = x; new_min_array[1] = y; } } delete[] current_min; return new_min_array; }
21.313253
102
0.655172
jmenden1
39b190ab03896db9404c35ee98c9abbbe5ec8e95
1,898
cpp
C++
od/audio/SampleSaver.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-06-29T19:26:35.000Z
2021-06-29T19:26:35.000Z
od/audio/SampleSaver.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-04-28T07:54:41.000Z
2021-04-28T07:54:41.000Z
od/audio/SampleSaver.cpp
bapch/er-301
e652eb9253009897747b0de7cfc57a27ac0cde1a
[ "MIT" ]
1
2021-03-02T21:32:52.000Z
2021-03-02T21:32:52.000Z
/* * SampleSaver.cpp * * Created on: 24 Oct 2016 * Author: clarkson */ #include <od/audio/SampleSaver.h> #include <od/audio/WavFileWriter.h> namespace od { SampleSaver::SampleSaver() { } SampleSaver::~SampleSaver() { } bool SampleSaver::set(Sample *sample, const char *filename) { if (mStatus == STATUS_WORKING || sample == 0 || filename == 0) return false; mpSample = sample; mpSample->attach(); mFilename = filename; mStatus = STATUS_WORKING; return true; } void SampleSaver::work() { if (mpSample) { mStatus = save(); mpSample->release(); mpSample = NULL; } } int SampleSaver::save() { WavFileWriter writer(mpSample->mSampleRate, mpSample->mChannelCount, wavFloat); uint32_t sw; float *buffer = mpSample->mpData; if (buffer == NULL) { return STATUS_SAMPLE_NOT_PREPARED; } mPercentDone = 0.0f; mSamplesWritten = 0; if (!writer.open(mFilename)) { return STATUS_ERROR_OPENING_FILE; } mSamplesRemaining = mpSample->mSampleCount; while (mSamplesRemaining) { if (mCancelRequested) { return STATUS_CANCELED; } if (mSamplesRemaining < mSamplesPerBlock) sw = mSamplesRemaining; else sw = mSamplesPerBlock; if (writer.writeSamples(buffer, sw) != sw) { return STATUS_ERROR_WRITING_FILE; } else { buffer += sw * mpSample->mChannelCount; mSamplesWritten += sw; mSamplesRemaining -= sw; if (mpSample->mSampleCount < mSamplesPerBlock) { mPercentDone = 100.0f; } else { mPercentDone = 100.0f * (float)(mSamplesWritten / mSamplesPerBlock) / (float)(mpSample->mSampleCount / mSamplesPerBlock); } } } mpSample->mDirty = false; writer.close(); return STATUS_FINISHED; } } /* namespace od */
18.427184
127
0.611697
bapch
39b3080d167cecd1cf34fe5bdca3aea61bbf180c
1,991
hpp
C++
ThreadPool.hpp
Linsexy/thread-pool
0e9667c8c95fefc65054d8022c1a736aebf330d5
[ "MIT" ]
null
null
null
ThreadPool.hpp
Linsexy/thread-pool
0e9667c8c95fefc65054d8022c1a736aebf330d5
[ "MIT" ]
1
2018-03-27T19:43:26.000Z
2018-03-28T14:04:40.000Z
ThreadPool.hpp
Linsexy/thread-pool
0e9667c8c95fefc65054d8022c1a736aebf330d5
[ "MIT" ]
null
null
null
// // Created by benito on 3/25/18. // #ifndef THREAD_POOL_THREADPOOL_HPP #define THREAD_POOL_THREADPOOL_HPP /* Written for the Arfang Engine * * https://github.com/Linsexy/arfang-engine * */ #include <array> #include <vector> #include <functional> #include <list> #include <future> #include <queue> #include <iostream> #include "Thread.hpp" namespace Af { class ThreadPool { public: ThreadPool(int, Thread::DestroyBehavior behavior=Thread::DestroyBehavior::DETACH); ~ThreadPool(); ThreadPool(ThreadPool&&) = default; ThreadPool(ThreadPool const&) = delete; template <typename Func, typename... Args> auto runAsyncTask(Func&& toCall, Args&&... args) { using RetType = typename std::result_of<Func(Args...)>::type; std::promise<RetType> promise; auto ret = promise.get_future(); auto task = std::make_unique<Thread::Task<RetType, Func, Args...>>(std::move(promise), std::forward<Func>(toCall), std::forward<Args>(args)...); // std::cout << "threadpool acquiring mutex" << std::endl; std::unique_lock lk(*_mut); _tasks.emplace(std::move(task)); lk.unlock(); _cond->notify_one(); return std::move(ret); } void finishTasks() noexcept; class Error : public std::runtime_error { public: Error(const std::string& err) : std::runtime_error(err) {} }; private: Thread::DestroyBehavior _behavior; std::shared_ptr<std::condition_variable> _cond; std::shared_ptr<std::mutex> _mut; std::queue<std::unique_ptr<Thread::ITask>> _tasks; std::vector<Thread> _threads; }; } #endif //THREAD_POOL_THREADPOOL_HPP
27.273973
108
0.549975
Linsexy
39ba6efd5d7a862e8522d5e90a3fc1a4f0959e9a
1,267
cpp
C++
lib/LanguageService.cpp
LibProtection/libprotection-cpp
4dc7860c8d9db15854764525e37c3f60cd2f9362
[ "MIT" ]
2
2018-11-24T13:29:35.000Z
2018-11-24T13:29:36.000Z
lib/LanguageService.cpp
LibProtection/libprotection-cpp
4dc7860c8d9db15854764525e37c3f60cd2f9362
[ "MIT" ]
1
2018-01-24T15:51:00.000Z
2018-02-08T13:11:01.000Z
lib/LanguageService.cpp
LibProtection/libprotection-cpp
4dc7860c8d9db15854764525e37c3f60cd2f9362
[ "MIT" ]
3
2017-11-28T09:42:07.000Z
2021-04-30T10:22:41.000Z
#include "protection/LanguageService.h" #include <algorithm> #include <unordered_map> namespace protection { namespace injections { SanitizeResult::SanitizeResult(bool sanitized, std::vector<Token> t, std::string sanitizedStr, Token token) : success{sanitized}, tokens{std::move(t)}, sanitizedString{sanitizedStr}, attackToken{token} {} bool LanguageService::TokenScope::isTrivial() const { return std::all_of(tokens.begin(), tokens.end(), [](const Token &t) { return t.isTrivial; }); } std::vector<LanguageService::TokenScope> LanguageService::getTokensScopes(const std::vector<Token> &tokens, const std::vector<Range> &ranges) { std::unordered_map<Range, TokenScope> scopesMap; for (const auto &token : tokens) { for (const auto &range : ranges) { if (range.overlaps(token.range)) { auto it = scopesMap.emplace(range, TokenScope{range}).first; it->second.tokens.push_back(token); } } } std::vector<TokenScope> scopes; for (const auto &r : ranges) { auto it = scopesMap.find(r); if (it != scopesMap.end()) { scopes.push_back(it->second); } } return scopes; } } // namespace injections } // namespace protection
31.675
109
0.651144
LibProtection
39c13e97f233560c6fdf20a9c88db6c3884accb5
758
cpp
C++
Win32/GroupBox.cpp
soncfe/Win32GUI
c7bf6f24f2d4a66456c701017005e58f75a57c3c
[ "Unlicense" ]
36
2020-03-29T19:23:00.000Z
2022-03-28T22:07:11.000Z
Win32/GroupBox.cpp
soncfe/Win32GUI
c7bf6f24f2d4a66456c701017005e58f75a57c3c
[ "Unlicense" ]
7
2020-08-01T13:35:16.000Z
2022-01-27T00:43:44.000Z
Win32/GroupBox.cpp
soncfe/Win32GUI
c7bf6f24f2d4a66456c701017005e58f75a57c3c
[ "Unlicense" ]
10
2020-04-07T15:55:44.000Z
2021-12-16T20:25:12.000Z
#include "GroupBox.h" GroupBox::GroupBox() { } GroupBox::GroupBox(Control* parent, std::string name, RECT rect) : Control(parent, name, rect.right, rect.bottom) { cmnControlInit(ICC_STANDARD_CLASSES); setLocation(rect.left, rect.top); mStyle = WS_CHILD | WS_VISIBLE | BS_GROUPBOX | BS_NOTIFY; mType = WC_BUTTON; create(); } GroupBox::GroupBox(Control* parent, std::string name, int width, int height) : Control(parent, name, width, height) { cmnControlInit(ICC_STANDARD_CLASSES); mStyle = WS_CHILD | WS_VISIBLE | BS_GROUPBOX | BS_NOTIFY; mType = WC_BUTTON; create(); } LRESULT GroupBox::drawctl(UINT uMsg, WPARAM wParam, LPARAM lParam) { SetBkMode((HDC)wParam, TRANSPARENT); SetTextColor((HDC)wParam, mFtColor); return (LRESULT)mBkBrush; }
23.6875
76
0.738786
soncfe
39c6bbf7bcac20ca09842384382a854c334d6afd
1,098
cpp
C++
doc/snippets/compile_JacobiSVD_basic.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
15
2021-02-27T11:00:51.000Z
2022-03-11T10:31:46.000Z
doc/snippets/compile_JacobiSVD_basic.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
1
2018-11-14T23:14:58.000Z
2018-11-14T23:14:58.000Z
doc/snippets/compile_JacobiSVD_basic.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
4
2021-03-13T13:28:55.000Z
2021-11-05T02:26:02.000Z
static bool eigen_did_assert = false; #define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << "### Assertion raised in " << __FILE__ << ":" << __LINE__ << ":\n" #X << "\n### The following would happen without assertions:\n"; eigen_did_assert = true;} #include <iostream> #include <Eigen/Eigen> #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif using namespace Eigen; using namespace std; int main(int, char**) { cout.precision(3); MatrixXf m = MatrixXf::Random(3,2); cout << "Here is the matrix m:" << endl << m << endl; JacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV); cout << "Its singular values are:" << endl << svd.singularValues() << endl; cout << "Its left singular vectors are the columns of the thin U matrix:" << endl << svd.matrixU() << endl; cout << "Its right singular vectors are the columns of the thin V matrix:" << endl << svd.matrixV() << endl; Vector3f rhs(1, 0, 0); cout << "Now consider this rhs vector:" << endl << rhs << endl; cout << "A least-squares solution of m*x = rhs is:" << endl << svd.solve(rhs) << endl; return 0; }
36.6
224
0.668488
mousepawmedia
39c7bed1fe699371925ee5a737b47ce59df42389
156
cpp
C++
chapter04/4.6_The_Member_Access_Operators .cpp
NorthFacing/step-by-c
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
[ "MIT" ]
9
2019-05-10T05:39:21.000Z
2022-02-22T08:04:52.000Z
chapter04/4.6_The_Member_Access_Operators .cpp
NorthFacing/step-by-c
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
[ "MIT" ]
null
null
null
chapter04/4.6_The_Member_Access_Operators .cpp
NorthFacing/step-by-c
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
[ "MIT" ]
6
2019-05-13T13:39:19.000Z
2022-02-22T08:05:01.000Z
/** * 4.6 成员访问运算符 * @Author Bob * @Eamil 0haizhu0@gmail.com * @Date 2017/7/28 */ int main(){ /** * p->size(); 等价于 (*p).size() */ return 0; }
12
31
0.49359
NorthFacing
39ca362c7922dde9d34d3c17724aa77e6c4c43ce
652
hpp
C++
Sources/Physics/Colliders/ColliderSphere.hpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Physics/Colliders/ColliderSphere.hpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Physics/Colliders/ColliderSphere.hpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
#pragma once #include "Collider.hpp" class btSphereShape; namespace acid { class ACID_EXPORT ColliderSphere : public Collider::Registrar<ColliderSphere> { public: explicit ColliderSphere(float radius = 0.5f, const Transform &localTransform = {}); ~ColliderSphere(); btCollisionShape *GetCollisionShape() const override; float GetRadius() const { return m_radius; } void SetRadius(float radius); friend const Node &operator>>(const Node &node, ColliderSphere &collider); friend Node &operator<<(Node &node, const ColliderSphere &collider); private: static bool registered; std::unique_ptr<btSphereShape> m_shape; float m_radius; }; }
22.482759
84
0.76227
dreadris
39ca7ec225ef050296a50f9a169889b1a73db298
3,314
hpp
C++
tests/data.hpp
ChrisAHolland/constexpr-sql
3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3
[ "MIT" ]
121
2020-04-21T13:21:55.000Z
2021-11-15T09:48:47.000Z
tests/data.hpp
ChrisAHolland/constexpr-sql
3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3
[ "MIT" ]
3
2020-04-23T05:29:54.000Z
2021-07-18T18:37:57.000Z
tests/data.hpp
ChrisAHolland/constexpr-sql
3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3
[ "MIT" ]
5
2020-04-23T05:01:02.000Z
2022-02-21T21:00:30.000Z
#pragma once #include <string> #include <type_traits> #include "sql.hpp" using books = sql::schema< "books", sql::index<>, #ifdef CROSS sql::column<"book", std::string>, #else sql::column<"title", std::string>, #endif sql::column<"genre", std::string>, sql::column<"year", unsigned>, sql::column<"pages", unsigned> >; using stories = sql::schema< "stories", sql::index<>, #ifdef CROSS sql::column<"story", std::string>, #else sql::column<"title", std::string>, #endif sql::column<"genre", std::string>, sql::column<"year", unsigned> >; using authored = sql::schema< "authored", sql::index<>, sql::column<"title", std::string>, sql::column<"name", std::string> >; using collected = sql::schema< "collected", sql::index<>, sql::column<"title", std::string>, sql::column<"collection", std::string>, sql::column<"pages", unsigned> >; const std::string data_folder{ "./data/" }; const std::string perf_folder{ "../data/" }; const std::string books_data{ "books.tsv" }; const std::string stories_data{ "stories.tsv" }; const std::string authored_data{ "authored.tsv" }; const std::string collected_data{ "collected.tsv" }; using books_row = std::tuple<std::string, std::string, int, int>; using books_type = std::vector<books_row>; using stories_row = std::tuple<std::string, std::string, int>; using stories_type = std::vector<stories_row>; using authored_row = std::tuple<std::string, std::string>; using authored_type = std::vector<authored_row>; using collected_row = std::tuple<std::string, std::string, int>; using collected_type = std::vector<collected_row>; constexpr std::size_t iters{ 65536 }; constexpr std::size_t offset{ 512 }; template <char Delim> books_type books_load() { auto file{ std::fstream(perf_folder + books_data) }; books_type table{}; while (file) { books_row row{}; std::getline(file, std::get<0>(row), Delim); std::getline(file, std::get<1>(row), Delim); file >> std::get<2>(row); file >> std::get<3>(row); table.push_back(std::move(row)); if (file.get() != '\n') { file.unget(); } } return table; } template <char Delim> stories_type stories_load() { auto file{ std::fstream(perf_folder + stories_data) }; stories_type table{}; while (file) { stories_row row{}; std::getline(file, std::get<0>(row), Delim); std::getline(file, std::get<1>(row), Delim); file >> std::get<2>(row); table.push_back(std::move(row)); if (file.get() != '\n') { file.unget(); } } return table; } template <char Delim> authored_type authored_load() { auto file{ std::fstream(perf_folder + authored_data) }; authored_type table{}; while (file) { authored_row row{}; std::getline(file, std::get<0>(row), Delim); std::getline(file, std::get<1>(row), Delim); table.push_back(std::move(row)); if (file.get() != '\n') { file.unget(); } } return table; } template <char Delim> collected_type collected_load() { auto file{ std::fstream(perf_folder + collected_data) }; collected_type table{}; while (file) { collected_row row{}; std::getline(file, std::get<0>(row), Delim); std::getline(file, std::get<1>(row), Delim); file >> std::get<2>(row); table.push_back(std::move(row)); if (file.get() != '\n') { file.unget(); } } return table; }
20.45679
65
0.646952
ChrisAHolland
39cadcd1cc8192bf943bc237abdaabb52e2fa9fe
1,578
hpp
C++
include/DREAM/ConvergenceChecker.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
include/DREAM/ConvergenceChecker.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
include/DREAM/ConvergenceChecker.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
#ifndef _DREAM_CONVERGENCE_CHECKER_HPP #define _DREAM_CONVERGENCE_CHECKER_HPP #include <string> #include <unordered_map> #include <vector> #include "FVM/NormEvaluator.hpp" #include "FVM/UnknownQuantityHandler.hpp" namespace DREAM { class ConvergenceChecker : public FVM::NormEvaluator { private: std::unordered_map<len_t, real_t> absTols; std::unordered_map<len_t, real_t> relTols; void DefineAbsoluteTolerances(); real_t GetDefaultAbsTol(const std::string&); len_t dx_size = 0; real_t *dx_buffer=nullptr; len_t nNontrivials; real_t *x_2norm=nullptr; real_t *dx_2norm=nullptr; public: ConvergenceChecker( FVM::UnknownQuantityHandler*, const std::vector<len_t>&, const real_t reltol=1e-6 ); virtual ~ConvergenceChecker(); void AllocateBuffer(const len_t); void DeallocateBuffer(); const std::string &GetNonTrivialName(const len_t i) { return this->unknowns->GetUnknown(nontrivials[i])->GetName(); } bool IsConverged(const real_t*, const real_t*, bool verbose=false); bool IsConverged(const real_t*, const real_t*, const real_t*, bool verbose=false); const real_t *GetErrorNorms() { return this->dx_2norm; } const real_t GetErrorScale(const len_t); void SetAbsoluteTolerance(const len_t, const real_t); void SetRelativeTolerance(const real_t); void SetRelativeTolerance(const len_t, const real_t); }; } #endif/*_DREAM_CONVERGENCE_CHECKER_HPP*/
30.346154
90
0.679975
chalmersplasmatheory
39cd665f158df7b7981492c8c02d51edefce8d11
1,872
cpp
C++
src/question34.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question34.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question34.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: // 法一: vector<int> searchRange1(vector<int>& nums, int target) { if(nums.size() == 0) return {-1, -1}; int l = 0, r = nums.size() - 1; int mid = 0; while(l <= r){ mid = l + (r - l) / 2; if(nums[mid] == target){ break; }else if(nums[mid] > target){ r = mid - 1; }else{ l = mid + 1; } } // cout << "mid = " << mid << endl; if(l > r) return {-1, -1}; int i = mid, j = mid; while(i >= 0 && nums[i] == target) i--; while(j < nums.size() && nums[j] == target) j++; return {i + 1, j - 1}; } // 法二: int binarySearch(vector<int>& nums, int target, bool lower){ int l = 0, r = nums.size() - 1, ans = nums.size(); while(l <= r){ int mid = (l + r) / 2; if(nums[mid] > target || (lower && nums[mid] >= target)){ r = mid - 1; ans = mid; }else{ l = mid + 1; } } return ans; } vector<int> searchRange(vector<int>& nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false); if(leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target){ return vector<int>{leftIdx, rightIdx}; } return {-1, -1}; } }; int main(){ // vector<int> nums{5,7,7,8,8,10}; // int target = 8; vector<int> nums{5,7,7,8,8,10}; int target = 6; Solution s; auto ans = s.searchRange(nums, target); for(auto num : ans){ cout << num << " "; } cout << endl; }
27.130435
113
0.444444
lxb1226
39d7c9e0998fda2cdc29ac309fb7e0712ae06c90
1,709
cc
C++
src/sheet_painter.cc
d0iasm/liumos
f9600bd26f15ebd194d35d5e76877650e25b9733
[ "MIT" ]
null
null
null
src/sheet_painter.cc
d0iasm/liumos
f9600bd26f15ebd194d35d5e76877650e25b9733
[ "MIT" ]
null
null
null
src/sheet_painter.cc
d0iasm/liumos
f9600bd26f15ebd194d35d5e76877650e25b9733
[ "MIT" ]
null
null
null
#include "sheet_painter.h" #include "asm.h" // @font.gen.c extern uint8_t font[0x100][16]; void SheetPainter::DrawCharacter(Sheet& s, char c, int px, int py, bool do_flush) { if (!s.buf_) return; uint32_t* b32 = reinterpret_cast<uint32_t*>(s.buf_); for (int dy = 0; dy < 16; dy++) { for (int dx = 0; dx < 8; dx++) { uint32_t col = ((font[(uint8_t)c][dy] >> (7 - dx)) & 1) ? 0xffffff : 0; int x = px + dx; int y = py + dy; b32[y * s.pixels_per_scan_line_ + x] = col; } } if (do_flush) s.Flush(px, py, 8, 16); } void SheetPainter::DrawRect(Sheet& s, int px, int py, int w, int h, uint32_t col, bool do_flush) { if (!s.buf_) return; uint32_t* b32 = reinterpret_cast<uint32_t*>(s.buf_); if (w & 1) { for (int y = py; y < py + h; y++) { RepeatStore4Bytes(w, &b32[y * s.pixels_per_scan_line_ + px], col); } } else { for (int y = py; y < py + h; y++) { RepeatStore8Bytes(w / 2, &b32[y * s.pixels_per_scan_line_ + px], ((uint64_t)col << 32) | col); } } if (do_flush) s.Flush(px, py, w, h); } void SheetPainter::DrawPoint(Sheet& s, int px, int py, uint32_t col, bool do_flush) { s.buf_[py * s.pixels_per_scan_line_ + px] = col; if (do_flush) s.Flush(px, py, 1, 1); }
28.016393
77
0.426565
d0iasm
39d8dafd5118ea5b48ded9852aee0f07e48802f6
813
hpp
C++
include/cues.hpp
stefanofortu/intoTheWild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
null
null
null
include/cues.hpp
stefanofortu/intoTheWild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
1
2015-12-23T16:26:12.000Z
2015-12-23T16:26:34.000Z
include/cues.hpp
stefanofortu/intothewild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
null
null
null
#ifndef _CUES_HPP_ #define _CUES_HPP_ #include "config.hpp" vector<double> ComputeEHOG(Mat source, vector<vector<Point> > regions); vector<double> ComputePD(Mat source, vector<vector<Point> > regions); vector<double> ComputeStrokeWidth(Mat source, vector<vector<Point> > regions); vector<int> regions_cue(vector<double> cue, double positive_dist[51], double negative_dist[51], Mat source, vector<vector<Point> > regions, int numero, Mat *risultato); Mat Bayes(double positive_dist_SW[51], double negative_dist_SW[51], double positive_dist_PD[51], double negative_dist_PD[51], double positive_dist_EHOG[51], double negative_dist_EHOG[51], vector<double> SW, vector<double> PD, vector<double> EHOG, Mat source, vector<vector<Point> > regions); #endif // _CUES_HPP_
42.789474
168
0.738007
stefanofortu
39d9cd2a51eb44da0fd11031f2d53dd4e72bed47
45
cpp
C++
src/NGFX/Private/Vulkan/vk_log.cpp
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/NGFX/Private/Vulkan/vk_log.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/NGFX/Private/Vulkan/vk_log.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include "vk_common.h" namespace vulkan { }
7.5
22
0.711111
PixPh
39de3ef7de48233da97491f31e295f3e2792d4b0
9,319
cpp
C++
programming/sampleProject/startScanner.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
2
2020-12-10T02:05:29.000Z
2021-05-30T15:23:56.000Z
programming/sampleProject/startScanner.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
null
null
null
programming/sampleProject/startScanner.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
1
2020-04-21T11:18:18.000Z
2020-04-21T11:18:18.000Z
#include "startScanner.h" void StartScanner::StartEntryPoint() { AllData a; a.initializeTraderParameters(); a.initializeOtherParameters(); a.initializeSymbolVectors_Prev(); a.m_backTest = false; //**** IMPORTANT! This must be false all the time for real trading. a.initializeSymbolVectors(); a.initializeBaseVector("EMPTY"); a.initializeCurrentDataVector(); a.initializeOtherVectors(); a.unhandledSymbols(); int err = _beginthread(AllData::MessageLimitationStatic, 0, &a); if (err < 0) { printf("Could not start new threads.\n"); } // This is for handling 50 message limitation. CommonFunctions cfs(a); cfs.initialization(); HistoricalDataL historicalDataL(cfs, a); historicalDataL.connectToTWS(); HistoricalDataNormal historicalDataS(cfs, a); historicalDataS.connectToTWS(); //Liquidity_EC->reqScannerSubscription(100, m_ScannerSubscription); if (time(0) > a.m_tradingEndTime){//Preparing data for tomorrow. When runing this, must make sure SPY dayBar for today is already available. The application will complain if this is not true. a.m_timeNow = time(0); a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataL.downloadHistoricalData_Single(); //****After this call, a.m_numDataOfSingleSymbolL will be set with a value. a.L_BarVectorDefaul(); a.update_manualsVector(); a.earningReportDate(); //**** This is actually not necessary here. Just for testing purpose. It only matters in trading process. a.m_numSymbolsToDownload = a.m_newtxtVector.size(); a.m_historicalDataDone = false; err = _beginthread(HistoricalDataL::HistoricalDataStaticEntryPoint, 0, &historicalDataL); if (err < 0) { printf("Could not start new threads.\n"); } while (1) { if (a.m_historicalDataDone) break; else Sleep(1000); } Sleep(10000); time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" exit(0); } else{ //time(0) <= tradingEndTime. During or before trading. a.m_timeNow = time(0) - 13 * 60 * 60; //****If I changed it into eastern time, I need modify this? a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataL.downloadHistoricalData_Single(); //****After this call, numDataOfSingleSymbolL will be set with a value. a.L_BarVectorDefaul(); a.update_manualsVector(); a.earningReportDate(); a.update_historyVector(); time_t startTime = time(0), timePassed, nextHeartBeat = time(0); a.m_numSymbolsToDownload = a.m_newtxtVector.size(); a.m_historicalDataDone = false; err = _beginthread(HistoricalDataL::HistoricalDataStaticEntryPoint, 0, &historicalDataL); if (err < 0) { printf("Could not start new threads.\n"); } while (1){ timePassed = time(0) - startTime; if (a.m_historicalDataDone) break; Sleep(100); if (time(0) > nextHeartBeat) { printf("I am waiting %d seconds for most historical data download done.\n", a.m_traderParameters.timeToContinue); nextHeartBeat = nextHeartBeat + 60; } } cfs.calculateBaseVector(); a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataS.downloadHistoricalData_Single(); //****After this call, numDataOfSingleSymbolL will be set with a value. a.S_BarVectorDefaul(); //**** Similarly I can download s bars if necessary } EClientL0 *EC_datafeed, *EC_Long, *EC_Short; //**** ECLientL0 is abstract class and cannot be instantiated. However, we can create pointers to an abstract class. DatafeedNormal datafeed(a); EC_datafeed = EClientL0::New(&datafeed); if (EC_datafeed == NULL) { printf("Creating EClient for dataFeed failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used. bool returnValue = false; std::chrono::high_resolution_clock::time_point now; while (1){ bool b = true; try { a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){ if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){ returnValue = EC_datafeed->eConnect("", a.m_port, a.m_clientId_MarketData); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours. now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); } a.m_csTimeDeque.LeaveCriticalSection(); } printf(" socket client is being created for datafeed in start.cpp.\n"); if (returnValue == true) break; else { Sleep(20000); } } //end of while(1) datafeed.set_EC(EC_datafeed); TraderEWrapperNormalLong traderEWrapperLong(a); EC_Long = EClientL0::New(&traderEWrapperLong); if (EC_Long == NULL) { printf("Creating EClient failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used. returnValue = false; while (1){ bool b = true; try { a.m_csTimeDeque.EnterCriticalSection(); }catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){ if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){ returnValue = EC_Long->eConnect("", a.m_port, a.m_clientIdLong); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours. now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); } a.m_csTimeDeque.LeaveCriticalSection(); } printf(" long socket client is being created in startNormal.cpp.\n"); if (returnValue == true) break; else { Sleep(20000); } } //end of while(1) TraderNormalLong trader1(cfs, a, EC_Long, traderEWrapperLong); traderEWrapperLong.set_EC(EC_Long); traderEWrapperLong.update_traderStructureVector_by_EWrappers(); TraderEWrapperNormalShort traderEWrapperShort(a); EC_Short = EClientL0::New(&traderEWrapperShort); if (EC_Short == NULL) { printf("Creating EClient failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used. returnValue = false; while (1){ bool b = true; try { a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){ if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){ returnValue = EC_Short->eConnect("", a.m_port, a.m_clientIdShort); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours. now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); } a.m_csTimeDeque.LeaveCriticalSection(); } printf(" short socket client is being created in startNormal.cpp.\n"); if (returnValue == true) break; else { Sleep(20000); } } //end of while(1) traderEWrapperShort.set_EC(EC_Short); traderEWrapperShort.update_traderStructureVector_by_EWrappers(); TraderNormalShort trader2(cfs, a, EC_Short, traderEWrapperShort); //Sleep(10000); //It seems here above does not have problems. if (time(0) <= a.m_tradingEndTime){ //Preparing data for tomorrow. When runing this, must make sure SPY dayBar for today is already available. The application will complain if this is not true. err = _beginthread(DatafeedNormal::DatafeedStaticEntryPoint, 0, &datafeed); if (err < 0) { printf("Could not start new threads.\n"); } err = _beginthread(TraderNormalLong::TraderNormalLongStaticEntryPoint, 0, &trader1); if (err < 0) { printf("Could not start new threads for normalLong.\n"); } err = _beginthread(TraderNormalShort::TraderNormalShortStaticEntryPoint, 0, &trader2); if (err < 0) { printf("Could not start new threads for normalShort.\n"); } //**** Note to keep the threads initiated here alive. I must keep the thead here alive. Otherwise all threads will be dead tother with weird errors. ///************** Don't comment this line //*************** Two IMPORTANT Points: [1] If without the Sleep(100000000) below, then once the main thread is gone, then all other threads will be done. [2] When starting a new thread I need make sure that the class instance //*************** used in the new thread will not be dead. The class instance should be alive all the time when the application is running, unless I really don't need the thread to be alive that long. In the main() above, //*************** I define several class instances but not define them in a new class member function. This is because when that member function is gone, then class instance will often be gone too. If that happens, I will get errors such as "pure virtual funtion call " or "invalid access" or "unhandled exception" etc. Sleep(100000000); // This is critically important for old C++ standard. Without it, the termination of main thread will terminate all other running threads. } }
65.167832
322
0.725722
ljyang100
39e02ac39c3e1f70da83cc9ff39059161777e515
38,695
cpp
C++
extensions/DRM/dream/DRMSignalIO.cpp
mfkiwl/FlyDog_SDR_GPS
d4870af35e960282a3c1b7e6b41444be4cb53fab
[ "MIT" ]
9
2020-09-22T17:26:17.000Z
2022-03-10T17:58:03.000Z
extensions/DRM/dream/DRMSignalIO.cpp
hikijun/FlyDog_SDR_GPS
d4870af35e960282a3c1b7e6b41444be4cb53fab
[ "MIT" ]
null
null
null
extensions/DRM/dream/DRMSignalIO.cpp
hikijun/FlyDog_SDR_GPS
d4870af35e960282a3c1b7e6b41444be4cb53fab
[ "MIT" ]
4
2021-02-10T16:13:19.000Z
2021-09-21T08:04:25.000Z
/******************************************************************************\ * Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik * Copyright (c) 2001 * * Author(s): * Volker Fischer, Cesco (HB9TLK) * * Description: * Transmit and receive data * ****************************************************************************** * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * \******************************************************************************/ #include "DRMSignalIO.h" #include "UpsampleFilter.h" #include <iostream> #include "sound/sound.h" #include "sound/audiofilein.h" #include "util/FileTyper.h" #include "matlib/MatlibSigProToolbox.h" const static int SineTable[] = { 0, 1, 0, -1, 0 }; /* Implementation *************************************************************/ /******************************************************************************\ * Transmitter * \******************************************************************************/ CTransmitData::CTransmitData() : pFileTransmitter(nullptr), pSound(nullptr), eOutputFormat(OF_REAL_VAL), rDefCarOffset((_REAL) VIRTUAL_INTERMED_FREQ), strOutFileName("test/TransmittedData.txt"), bUseSoundcard(true), bAmplified(false), bHighQualityIQ(false) { } void CTransmitData::Stop() { if(pSound!=nullptr) pSound->Close(); } void CTransmitData::Enumerate(std::vector<std::string>& names, std::vector<std::string>& descriptions) { if(pSound==nullptr) pSound = new CSoundOut; pSound->Enumerate(names, descriptions); } void CTransmitData::SetSoundInterface(string device) { soundDevice = device; if(pSound != nullptr) { delete pSound; pSound = nullptr; } pSound = new CSoundOut(); pSound->SetDev(device); } void CTransmitData::ProcessDataInternal(CParameter&) { int i; /* Apply bandpass filter */ BPFilter.Process(*pvecInputData); /* Convert vector type. Fill vector with symbols (collect them) */ const int iNs2 = iInputBlockSize * 2; for (i = 0; i < iNs2; i += 2) { const int iCurIndex = iBlockCnt * iNs2 + i; _COMPLEX cInputData = (*pvecInputData)[i / 2]; if (bHighQualityIQ && eOutputFormat != OF_REAL_VAL) HilbertFilt(cInputData); /* Imaginary, real */ const _SAMPLE sCurOutReal = Real2Sample(cInputData.real() * rNormFactor); const _SAMPLE sCurOutImag = Real2Sample(cInputData.imag() * rNormFactor); /* Envelope, phase */ const _SAMPLE sCurOutEnv = Real2Sample(Abs(cInputData) * (_REAL) 256.0); const _SAMPLE sCurOutPhase = /* 2^15 / pi / 2 -> approx. 5000 */ Real2Sample(Angle(cInputData) * (_REAL) 5000.0); switch (eOutputFormat) { case OF_REAL_VAL: /* Use real valued signal as output for both sound card channels */ vecsDataOut[iCurIndex] = vecsDataOut[iCurIndex + 1] = sCurOutReal; break; case OF_IQ_POS: /* Send inphase and quadrature (I / Q) signal to stereo sound card output. I: left channel, Q: right channel */ vecsDataOut[iCurIndex] = sCurOutReal; vecsDataOut[iCurIndex + 1] = sCurOutImag; break; case OF_IQ_NEG: /* Send inphase and quadrature (I / Q) signal to stereo sound card output. I: right channel, Q: left channel */ vecsDataOut[iCurIndex] = sCurOutImag; vecsDataOut[iCurIndex + 1] = sCurOutReal; break; case OF_EP: /* Send envelope and phase signal to stereo sound card output. Envelope: left channel, Phase: right channel */ vecsDataOut[iCurIndex] = sCurOutEnv; vecsDataOut[iCurIndex + 1] = sCurOutPhase; break; } } iBlockCnt++; if (iBlockCnt == iNumBlocks) FlushData(); } void CTransmitData::FlushData() { int i; /* Zero the remain of the buffer, if incomplete */ if (iBlockCnt != iNumBlocks) { const int iSize = vecsDataOut.Size(); const int iStart = iSize * iBlockCnt / iNumBlocks; for (i = iStart; i < iSize; i++) vecsDataOut[i] = 0; } iBlockCnt = 0; if (bUseSoundcard) { /* Write data to sound card. Must be a blocking function */ pSound->Write(vecsDataOut); } else { /* Write data to file */ for (i = 0; i < iBigBlockSize; i++) { #ifdef FILE_DRM_USING_RAW_DATA const short sOut = vecsDataOut[i]; /* Write 2 bytes, 1 piece */ fwrite((const void*) &sOut, size_t(2), size_t(1), pFileTransmitter); #else /* This can be read with Matlab "load" command */ fprintf(pFileTransmitter, "%d\n", vecsDataOut[i]); #endif } /* Flush the file buffer */ fflush(pFileTransmitter); } } void CTransmitData::InitInternal(CParameter& Parameters) { /* float* pCurFilt; int iNumTapsTransmFilt; CReal rNormCurFreqOffset; */ /* Get signal sample rate */ iSampleRate = Parameters.GetSigSampleRate(); /* Define symbol block-size */ const int iSymbolBlockSize = Parameters.CellMappingTable.iSymbolBlockSize; /* Init vector for storing a complete DRM frame number of OFDM symbols */ iBlockCnt = 0; Parameters.Lock(); iNumBlocks = Parameters.CellMappingTable.iNumSymPerFrame; ESpecOcc eSpecOcc = Parameters.GetSpectrumOccup(); Parameters.Unlock(); iBigBlockSize = iSymbolBlockSize * 2 /* Stereo */ * iNumBlocks; /* Init I/Q history */ vecrReHist.Init(NUM_TAPS_IQ_INPUT_FILT_HQ, (_REAL) 0.0); vecsDataOut.Init(iBigBlockSize); if (pFileTransmitter != nullptr) { fclose(pFileTransmitter); } if (bUseSoundcard) { /* Init sound interface */ if(pSound!=nullptr) pSound->Init(iSampleRate, iBigBlockSize, true); } else { /* Open file for writing data for transmitting */ #ifdef FILE_DRM_USING_RAW_DATA pFileTransmitter = fopen(strOutFileName.c_str(), "wb"); #else pFileTransmitter = fopen(strOutFileName.c_str(), "w"); #endif /* Check for error */ if (pFileTransmitter == nullptr) throw CGenErr("The file " + strOutFileName + " cannot be created."); } /* Init bandpass filter object */ BPFilter.Init(iSampleRate, iSymbolBlockSize, rDefCarOffset, eSpecOcc, CDRMBandpassFilt::FT_TRANSMITTER); /* All robustness modes and spectrum occupancies should have the same output power. Calculate the normalization factor based on the average power of symbol (the number 3000 was obtained through output tests) */ rNormFactor = (CReal) 3000.0 / Sqrt(Parameters.CellMappingTable.rAvPowPerSymbol); /* Apply amplification factor, 4.0 = +12dB (the maximum without clipping, obtained through output tests) */ rNormFactor *= bAmplified ? 4.0 : 1.0; /* Define block-size for input */ iInputBlockSize = iSymbolBlockSize; } CTransmitData::~CTransmitData() { /* Close file */ if (pFileTransmitter != nullptr) fclose(pFileTransmitter); } void CTransmitData::HilbertFilt(_COMPLEX& vecData) { int i; /* Move old data */ for (i = 0; i < NUM_TAPS_IQ_INPUT_FILT_HQ - 1; i++) vecrReHist[i] = vecrReHist[i + 1]; vecrReHist[NUM_TAPS_IQ_INPUT_FILT_HQ - 1] = vecData.real(); /* Filter */ _REAL rSum = (_REAL) 0.0; for (i = 1; i < NUM_TAPS_IQ_INPUT_FILT_HQ; i += 2) rSum += fHilFiltIQ_HQ[i] * vecrReHist[i]; vecData = _COMPLEX(vecrReHist[IQ_INP_HIL_FILT_DELAY_HQ], -rSum); } /******************************************************************************\ * Receive data from the sound card * \******************************************************************************/ //inline _REAL sample2real(_SAMPLE s) { return _REAL(s)/32768.0; } inline _REAL sample2real(_SAMPLE s) { return _REAL(s); } void CReceiveData::Stop() { if(pSound!=nullptr) pSound->Close(); } void CReceiveData::Enumerate(std::vector<std::string>& names, std::vector<std::string>& descriptions) { if(pSound==nullptr) pSound = new CSoundIn; pSound->Enumerate(names, descriptions); } void CReceiveData::SetSoundInterface(string device) { soundDevice = device; if(pSound != nullptr) { pSound->Close(); delete pSound; pSound = nullptr; } FileTyper::type t = FileTyper::resolve(device); if(t != FileTyper::unrecognised) { CAudioFileIn* pAudioFileIn = new CAudioFileIn(); pAudioFileIn->SetFileName(device, t); int sr = pAudioFileIn->GetSampleRate(); if(iSampleRate!=sr) { // TODO //cerr << "file sample rate is " << sr << endl; iSampleRate = sr; } pSound = pAudioFileIn; } else { pSound = new CSoundIn(); pSound->SetDev(device); } } void CReceiveData::ProcessDataInternal(CParameter& Parameters) { int i; /* OPH: update free-running symbol counter */ Parameters.Lock(); iFreeSymbolCounter++; if (iFreeSymbolCounter >= Parameters.CellMappingTable.iNumSymPerFrame * 2) /* x2 because iOutputBlockSize=iSymbolBlockSize/2 */ { iFreeSymbolCounter = 0; /* calculate the PSD once per frame for the RSI output */ if (Parameters.bMeasurePSD) PutPSD(Parameters); } Parameters.Unlock(); /* Get data from sound interface. The read function must be a blocking function! */ bool bBad = true; if (pSound != nullptr) { bBad = pSound->Read(vecsSoundBuffer); } Parameters.Lock(); Parameters.ReceiveStatus.InterfaceI.SetStatus(bBad ? CRC_ERROR : RX_OK); /* Red light */ Parameters.Unlock(); if(bBad) return; /* Upscale if ratio greater than one */ if (iUpscaleRatio > 1) { /* The actual upscaling, currently only 2X is supported */ InterpFIR_2X(2, &vecsSoundBuffer[0], vecf_ZL, vecf_YL, vecf_B); InterpFIR_2X(2, &vecsSoundBuffer[1], vecf_ZR, vecf_YR, vecf_B); /* Write data to output buffer. Do not set the switch command inside the for-loop for efficiency reasons */ switch (eInChanSelection) { case CS_LEFT_CHAN: for (i = 0; i < iOutputBlockSize; i++) (*pvecOutputData)[i] = _REAL(vecf_YL[unsigned(i)]); break; case CS_RIGHT_CHAN: for (i = 0; i < iOutputBlockSize; i++) (*pvecOutputData)[i] = _REAL(vecf_YR[unsigned(i)]); break; case CS_MIX_CHAN: for (i = 0; i < iOutputBlockSize; i++) { /* Mix left and right channel together */ (*pvecOutputData)[i] = _REAL(vecf_YL[unsigned(i)] + vecf_YR[unsigned(i)]) / 2.0; } break; case CS_SUB_CHAN: for (i = 0; i < iOutputBlockSize; i++) { /* Subtract right channel from left */ (*pvecOutputData)[i] = (vecf_YL[unsigned(i)] - vecf_YR[unsigned(i)]) / 2; } break; /* I / Q input */ case CS_IQ_POS: for (i = 0; i < iOutputBlockSize; i++) { (*pvecOutputData)[i] = HilbertFilt(vecf_YL[unsigned(i)], vecf_YR[unsigned(i)]); } break; case CS_IQ_NEG: for (i = 0; i < iOutputBlockSize; i++) { (*pvecOutputData)[i] = HilbertFilt(vecf_YR[unsigned(i)], vecf_YL[unsigned(i)]); } break; case CS_IQ_POS_ZERO: for (i = 0; i < iOutputBlockSize; i++) { /* Shift signal to vitual intermediate frequency before applying the Hilbert filtering */ _COMPLEX cCurSig = _COMPLEX(vecf_YL[unsigned(i)], vecf_YR[unsigned(i)]); cCurSig *= cCurExp; /* Rotate exp-pointer on step further by complex multiplication with precalculated rotation vector cExpStep */ cCurExp *= cExpStep; (*pvecOutputData)[i] = HilbertFilt(cCurSig.real(), cCurSig.imag()); } break; case CS_IQ_NEG_ZERO: for (i = 0; i < iOutputBlockSize; i++) { /* Shift signal to vitual intermediate frequency before applying the Hilbert filtering */ _COMPLEX cCurSig = _COMPLEX(vecf_YR[unsigned(i)], vecf_YL[unsigned(i)]); cCurSig *= cCurExp; /* Rotate exp-pointer on step further by complex multiplication with precalculated rotation vector cExpStep */ cCurExp *= cExpStep; (*pvecOutputData)[i] = HilbertFilt(cCurSig.real(), cCurSig.imag()); } break; case CS_IQ_POS_SPLIT: for (i = 0; i < iOutputBlockSize; i += 4) { (*pvecOutputData)[i + 0] = vecf_YL[i + 0]; (*pvecOutputData)[i + 1] = -vecf_YR[i + 1]; (*pvecOutputData)[i + 2] = -vecf_YL[i + 2]; (*pvecOutputData)[i + 3] = vecf_YR[i + 3]; } break; case CS_IQ_NEG_SPLIT: for (i = 0; i < iOutputBlockSize; i += 4) { (*pvecOutputData)[i + 0] = vecf_YR[i + 0]; (*pvecOutputData)[i + 1] = -vecf_YL[i + 1]; (*pvecOutputData)[i + 2] = -vecf_YR[i + 2]; (*pvecOutputData)[i + 3] = vecf_YL[i + 3]; } break; } } /* Upscale ratio equal to one */ else { /* Write data to output buffer. Do not set the switch command inside the for-loop for efficiency reasons */ switch (eInChanSelection) { case CS_LEFT_CHAN: for (i = 0; i < iOutputBlockSize; i++) (*pvecOutputData)[i] = sample2real(vecsSoundBuffer[2 * i]); break; case CS_RIGHT_CHAN: for (i = 0; i < iOutputBlockSize; i++) (*pvecOutputData)[i] = sample2real(vecsSoundBuffer[2 * i + 1]); break; case CS_MIX_CHAN: for (i = 0; i < iOutputBlockSize; i++) { /* Mix left and right channel together */ const _REAL rLeftChan = sample2real(vecsSoundBuffer[2 * i]); const _REAL rRightChan = sample2real(vecsSoundBuffer[2 * i + 1]); (*pvecOutputData)[i] = (rLeftChan + rRightChan) / 2; } break; case CS_SUB_CHAN: for (i = 0; i < iOutputBlockSize; i++) { /* Subtract right channel from left */ const _REAL rLeftChan = sample2real(vecsSoundBuffer[2 * i]); const _REAL rRightChan = sample2real(vecsSoundBuffer[2 * i + 1]); (*pvecOutputData)[i] = (rLeftChan - rRightChan) / 2; } break; /* I / Q input */ case CS_IQ_POS: for (i = 0; i < iOutputBlockSize; i++) { (*pvecOutputData)[i] = HilbertFilt(sample2real(vecsSoundBuffer[2 * i]), sample2real(vecsSoundBuffer[2 * i + 1])); } break; case CS_IQ_NEG: for (i = 0; i < iOutputBlockSize; i++) { (*pvecOutputData)[i] = HilbertFilt(sample2real(vecsSoundBuffer[2 * i + 1]), sample2real(vecsSoundBuffer[2 * i])); } break; case CS_IQ_POS_ZERO: for (i = 0; i < iOutputBlockSize; i++) { /* Shift signal to vitual intermediate frequency before applying the Hilbert filtering */ _COMPLEX cCurSig = _COMPLEX(sample2real(vecsSoundBuffer[2 * i]), sample2real(vecsSoundBuffer[2 * i + 1])); cCurSig *= cCurExp; /* Rotate exp-pointer on step further by complex multiplication with precalculated rotation vector cExpStep */ cCurExp *= cExpStep; (*pvecOutputData)[i] = HilbertFilt(cCurSig.real(), cCurSig.imag()); } break; case CS_IQ_NEG_ZERO: for (i = 0; i < iOutputBlockSize; i++) { /* Shift signal to vitual intermediate frequency before applying the Hilbert filtering */ _COMPLEX cCurSig = _COMPLEX(sample2real(vecsSoundBuffer[2 * i + 1]), sample2real(vecsSoundBuffer[2 * i])); cCurSig *= cCurExp; /* Rotate exp-pointer on step further by complex multiplication with precalculated rotation vector cExpStep */ cCurExp *= cExpStep; (*pvecOutputData)[i] = HilbertFilt(cCurSig.real(), cCurSig.imag()); } break; case CS_IQ_POS_SPLIT: /* Require twice the bandwidth */ for (i = 0; i < iOutputBlockSize; i++) { iPhase = (iPhase + 1) & 3; _REAL rValue = vecsSoundBuffer[2 * i] * /*COS*/SineTable[iPhase + 1] - vecsSoundBuffer[2 * i + 1] * /*SIN*/SineTable[iPhase]; (*pvecOutputData)[i] = rValue; } break; case CS_IQ_NEG_SPLIT: /* Require twice the bandwidth */ for (i = 0; i < iOutputBlockSize; i++) { iPhase = (iPhase + 1) & 3; _REAL rValue = vecsSoundBuffer[2 * i + 1] * /*COS*/SineTable[iPhase + 1] - vecsSoundBuffer[2 * i] * /*SIN*/SineTable[iPhase]; (*pvecOutputData)[i] = rValue; } break; } } /* Flip spectrum if necessary ------------------------------------------- */ if (bFippedSpectrum) { /* Since iOutputBlockSize is always even we can do some opt. here */ for (i = 0; i < iOutputBlockSize; i+=2) { /* We flip the spectrum by using the mirror spectrum at the negative frequencys. If we shift by half of the sample frequency, we can do the shift without the need of a Hilbert transformation */ (*pvecOutputData)[i] = -(*pvecOutputData)[i]; } } /* Copy data in buffer for spectrum calculation */ mutexInpData.Lock(); vecrInpData.AddEnd((*pvecOutputData), iOutputBlockSize); mutexInpData.Unlock(); /* Update level meter */ SignalLevelMeter.Update((*pvecOutputData)); Parameters.Lock(); Parameters.SetIFSignalLevel(SignalLevelMeter.Level()); Parameters.Unlock(); } void CReceiveData::InitInternal(CParameter& Parameters) { /* Init sound interface. Set it to one symbol. The sound card interface has to taken care about the buffering data of a whole MSC block. Use stereo input (* 2) */ if (pSound == nullptr) return; Parameters.Lock(); /* We define iOutputBlockSize as half the iSymbolBlockSize because if a positive frequency offset is present in drm signal, after some time a buffer overflow occur in the output buffer of InputResample.ProcessData() */ /* Define output block-size */ iOutputBlockSize = Parameters.CellMappingTable.iSymbolBlockSize / 2; iMaxOutputBlockSize = iOutputBlockSize * 2; /* Get signal sample rate */ iSampleRate = Parameters.GetSigSampleRate(); iUpscaleRatio = Parameters.GetSigUpscaleRatio(); Parameters.Unlock(); const int iOutputBlockAlignment = iOutputBlockSize & 3; if (iOutputBlockAlignment) { fprintf(stderr, "CReceiveData::InitInternal(): iOutputBlockAlignment = %i\n", iOutputBlockAlignment); } try { const bool bChanged = (pSound == nullptr)? true : pSound->Init(iSampleRate / iUpscaleRatio, iOutputBlockSize * 2 / iUpscaleRatio, true); /* Clear input data buffer on change samplerate change */ if (bChanged) ClearInputData(); /* Init 2X upscaler if enabled */ if (iUpscaleRatio > 1) { const int taps = (NUM_TAPS_UPSAMPLE_FILT + 3) & ~3; vecf_B.resize(taps, 0.0f); for (unsigned i = 0; i < NUM_TAPS_UPSAMPLE_FILT; i++) vecf_B[i] = float(dUpsampleFilt[i] * iUpscaleRatio); if (bChanged) { vecf_ZL.resize(0); vecf_ZR.resize(0); } vecf_ZL.resize(unsigned(iOutputBlockSize + taps) / 2, 0.0f); vecf_ZR.resize(unsigned(iOutputBlockSize + taps) / 2, 0.0f); vecf_YL.resize(unsigned(iOutputBlockSize)); vecf_YR.resize(unsigned(iOutputBlockSize)); } else { vecf_B.resize(0); vecf_YL.resize(0); vecf_YR.resize(0); vecf_ZL.resize(0); vecf_ZR.resize(0); } /* Init buffer size for taking stereo input */ vecsSoundBuffer.Init(iOutputBlockSize * 2 / iUpscaleRatio); /* Init signal meter */ SignalLevelMeter.Init(0); /* Inits for I / Q input, only if it is not already to keep the history intact */ if (vecrReHist.Size() != NUM_TAPS_IQ_INPUT_FILT || bChanged) { vecrReHist.Init(NUM_TAPS_IQ_INPUT_FILT, 0.0); vecrImHist.Init(NUM_TAPS_IQ_INPUT_FILT, 0.0); } /* Start with phase null (can be arbitrarily chosen) */ cCurExp = 1.0; /* Set rotation vector to mix signal from zero frequency to virtual intermediate frequency */ const _REAL rNormCurFreqOffsetIQ = 2.0 * crPi * _REAL(VIRTUAL_INTERMED_FREQ / iSampleRate); cExpStep = _COMPLEX(cos(rNormCurFreqOffsetIQ), sin(rNormCurFreqOffsetIQ)); /* OPH: init free-running symbol counter */ iFreeSymbolCounter = 0; } catch (CGenErr GenErr) { pSound = nullptr; } catch (string strError) { pSound = nullptr; } } _REAL CReceiveData::HilbertFilt(const _REAL rRe, const _REAL rIm) { /* Hilbert filter for I / Q input data. This code is based on code written by Cesco (HB9TLK) */ /* Move old data */ for (int i = 0; i < NUM_TAPS_IQ_INPUT_FILT - 1; i++) { vecrReHist[i] = vecrReHist[i + 1]; vecrImHist[i] = vecrImHist[i + 1]; } vecrReHist[NUM_TAPS_IQ_INPUT_FILT - 1] = rRe; vecrImHist[NUM_TAPS_IQ_INPUT_FILT - 1] = rIm; /* Filter */ _REAL rSum = 0.0; for (unsigned i = 1; i < NUM_TAPS_IQ_INPUT_FILT; i += 2) rSum += _REAL(fHilFiltIQ[i]) * vecrImHist[int(i)]; return (rSum + vecrReHist[IQ_INP_HIL_FILT_DELAY]) / 2; } void CReceiveData::InterpFIR_2X(const int channels, _SAMPLE* X, vector<float>& Z, vector<float>& Y, vector<float>& B) { /* 2X interpolating filter. When combined with CS_IQ_POS_SPLIT or CS_IQ_NEG_SPLIT input data mode, convert I/Q input to full bandwidth, code by David Flamand */ int i, j; const int B_len = int(B.size()); const int Z_len = int(Z.size()); const int Y_len = int(Y.size()); const int Y_len_2 = Y_len / 2; float *B_beg_ptr = &B[0]; float *Z_beg_ptr = &Z[0]; float *Y_ptr = &Y[0]; float *B_end_ptr, *B_ptr, *Z_ptr; float y0, y1, y2, y3; /* Check for size and alignment requirement */ if ((B_len & 3) || (Z_len != (B_len/2 + Y_len_2)) || (Y_len & 1)) return; /* Copy the old history at the end */ for (i = B_len/2-1; i >= 0; i--) Z_beg_ptr[Y_len_2 + i] = Z_beg_ptr[i]; /* Copy the new sample at the beginning of the history */ for (i = 0, j = 0; i < Y_len_2; i++, j+=channels) Z_beg_ptr[Y_len_2 - i - 1] = X[j]; /* The actual lowpass filtering using FIR */ for (i = Y_len_2-1; i >= 0; i--) { B_end_ptr = B_beg_ptr + B_len; B_ptr = B_beg_ptr; Z_ptr = Z_beg_ptr + i; y0 = y1 = y2 = y3 = 0.0f; while (B_ptr != B_end_ptr) { y0 = y0 + B_ptr[0] * Z_ptr[0]; y1 = y1 + B_ptr[1] * Z_ptr[0]; y2 = y2 + B_ptr[2] * Z_ptr[1]; y3 = y3 + B_ptr[3] * Z_ptr[1]; B_ptr += 4; Z_ptr += 2; } *Y_ptr++ = y0 + y2; *Y_ptr++ = y1 + y3; } } CReceiveData::~CReceiveData() { } /* Convert Real to I/Q frequency when bInvert is false Convert I/Q to Real frequency when bInvert is true */ _REAL CReceiveData::ConvertFrequency(_REAL rFrequency, bool bInvert) const { const int iInvert = bInvert ? -1 : 1; if (eInChanSelection == CS_IQ_POS_SPLIT || eInChanSelection == CS_IQ_NEG_SPLIT) rFrequency -= iSampleRate / 4 * iInvert; else if (eInChanSelection == CS_IQ_POS_ZERO || eInChanSelection == CS_IQ_NEG_ZERO) rFrequency -= VIRTUAL_INTERMED_FREQ * iInvert; return rFrequency; } void CReceiveData::GetInputSpec(CVector<_REAL>& vecrData, CVector<_REAL>& vecrScale) { int i; /* Length of spectrum vector including Nyquist frequency */ const int iLenSpecWithNyFreq = NUM_SMPLS_4_INPUT_SPECTRUM / 2 + 1; /* Init input and output vectors */ vecrData.Init(iLenSpecWithNyFreq, 0.0); vecrScale.Init(iLenSpecWithNyFreq, 0.0); /* Init the constants for scale and normalization */ const bool bNegativeFreq = eInChanSelection == CS_IQ_POS_SPLIT || eInChanSelection == CS_IQ_NEG_SPLIT; const bool bOffsetFreq = eInChanSelection == CS_IQ_POS_ZERO || eInChanSelection == CS_IQ_NEG_ZERO; const int iOffsetScale = bNegativeFreq ? iLenSpecWithNyFreq / 2 : (bOffsetFreq ? iLenSpecWithNyFreq * VIRTUAL_INTERMED_FREQ / (iSampleRate / 2) : 0); const _REAL rFactorScale = _REAL(iSampleRate / iLenSpecWithNyFreq / 2000); /* The calibration factor was determined experimentaly, give 0 dB for a full scale sine wave input (0 dBFS) */ const _REAL rDataCalibrationFactor = 18.49; const _REAL rNormData = rDataCalibrationFactor / (_REAL(_MAXSHORT * _MAXSHORT) * NUM_SMPLS_4_INPUT_SPECTRUM * NUM_SMPLS_4_INPUT_SPECTRUM); /* Copy data from shift register in Matlib vector */ CRealVector vecrFFTInput(NUM_SMPLS_4_INPUT_SPECTRUM); mutexInpData.Lock(); for (i = 0; i < NUM_SMPLS_4_INPUT_SPECTRUM; i++) vecrFFTInput[i] = vecrInpData[i]; mutexInpData.Unlock(); /* Get squared magnitude of spectrum */ CRealVector vecrSqMagSpect(iLenSpecWithNyFreq); CFftPlans FftPlans; vecrSqMagSpect = SqMag(rfft(vecrFFTInput * Hann(NUM_SMPLS_4_INPUT_SPECTRUM), FftPlans)); /* Log power spectrum data */ for (i = 0; i < iLenSpecWithNyFreq; i++) { const _REAL rNormSqMag = vecrSqMagSpect[i] * rNormData; if (rNormSqMag > 0) vecrData[i] = 10.0 * log10(rNormSqMag); else vecrData[i] = RET_VAL_LOG_0; vecrScale[i] = _REAL(i - iOffsetScale) * rFactorScale; } } void CReceiveData::GetInputPSD(CVector<_REAL>& vecrData, CVector<_REAL>& vecrScale, const int iLenPSDAvEachBlock, const int iNumAvBlocksPSD, const int iPSDOverlap) { CalculatePSD(vecrData, vecrScale, iLenPSDAvEachBlock,iNumAvBlocksPSD,iPSDOverlap); } void CReceiveData::CalculatePSD(CVector<_REAL>& vecrData, CVector<_REAL>& vecrScale, const int iLenPSDAvEachBlock, const int iNumAvBlocksPSD, const int iPSDOverlap) { /* Length of spectrum vector including Nyquist frequency */ const int iLenSpecWithNyFreq = iLenPSDAvEachBlock / 2 + 1; /* Init input and output vectors */ vecrData.Init(iLenSpecWithNyFreq, 0.0); vecrScale.Init(iLenSpecWithNyFreq, 0.0); /* Init the constants for scale and normalization */ const bool bNegativeFreq = eInChanSelection == CS_IQ_POS_SPLIT || eInChanSelection == CS_IQ_NEG_SPLIT; const bool bOffsetFreq = eInChanSelection == CS_IQ_POS_ZERO || eInChanSelection == CS_IQ_NEG_ZERO; const int iOffsetScale = bNegativeFreq ? iLenSpecWithNyFreq / 2 : (bOffsetFreq ? iLenSpecWithNyFreq * VIRTUAL_INTERMED_FREQ / (iSampleRate / 2) : 0); const _REAL rFactorScale = _REAL(iSampleRate / iLenSpecWithNyFreq / 2000); const _REAL rNormData = _REAL( _MAXSHORT * _MAXSHORT * iLenPSDAvEachBlock * iLenPSDAvEachBlock * iNumAvBlocksPSD * _REAL(PSD_WINDOW_GAIN)); /* Init intermediate vectors */ CRealVector vecrAvSqMagSpect(iLenSpecWithNyFreq, 0.0); CRealVector vecrFFTInput(iLenPSDAvEachBlock); /* Init Hamming window */ CRealVector vecrHammWin(Hamming(iLenPSDAvEachBlock)); /* Calculate FFT of each small block and average results (estimation of PSD of input signal) */ CFftPlans FftPlans; int i; mutexInpData.Lock(); for (i = 0; i < iNumAvBlocksPSD; i++) { /* Copy data from shift register in Matlib vector */ for (int j = 0; j < iLenPSDAvEachBlock; j++) vecrFFTInput[j] = vecrInpData[j + i * (iLenPSDAvEachBlock - iPSDOverlap)]; /* Apply Hamming window */ vecrFFTInput *= vecrHammWin; /* Calculate squared magnitude of spectrum and average results */ vecrAvSqMagSpect += SqMag(rfft(vecrFFTInput, FftPlans)); } mutexInpData.Unlock(); /* Log power spectrum data */ for (i = 0; i <iLenSpecWithNyFreq; i++) { const _REAL rNormSqMag = vecrAvSqMagSpect[i] / rNormData; if (rNormSqMag > 0) vecrData[i] = 10.0 * log10(rNormSqMag); else vecrData[i] = RET_VAL_LOG_0; vecrScale[i] = _REAL(i - iOffsetScale) * rFactorScale; } } /* Calculate PSD and put it into the CParameter class. * The data will be used by the rsi output. * This function is called in a context where the Parameters structure is Locked. */ void CReceiveData::PutPSD(CParameter &Parameters) { int i, j; CVector<_REAL> vecrData; CVector<_REAL> vecrScale; CalculatePSD(vecrData, vecrScale, LEN_PSD_AV_EACH_BLOCK_RSI, NUM_AV_BLOCKS_PSD_RSI, PSD_OVERLAP_RSI); /* Data required for rpsd tag */ /* extract the values from -8kHz to +8kHz/18kHz relative to 12kHz, i.e. 4kHz to 20kHz */ /*const int startBin = 4000.0 * LEN_PSD_AV_EACH_BLOCK_RSI /iSampleRate; const int endBin = 20000.0 * LEN_PSD_AV_EACH_BLOCK_RSI /iSampleRate;*/ /* The above calculation doesn't round in the way FhG expect. Probably better to specify directly */ /* For 20k mode, we need -8/+18, which is more than the Nyquist rate of 24kHz. */ /* Assume nominal freq = 7kHz (i.e. 2k to 22k) and pad with zeroes (roughly 1kHz each side) */ int iStartBin = 22; int iEndBin = 106; int iVecSize = iEndBin - iStartBin + 1; //85 //_REAL rIFCentreFrequency = Parameters.FrontEndParameters.rIFCentreFreq; ESpecOcc eSpecOcc = Parameters.GetSpectrumOccup(); if (eSpecOcc == SO_4 || eSpecOcc == SO_5) { iStartBin = 0; iEndBin = 127; iVecSize = 139; } /* Line up the the middle of the vector with the quarter-Nyquist bin of FFT */ int iStartIndex = iStartBin - (LEN_PSD_AV_EACH_BLOCK_RSI/4) + (iVecSize-1)/2; /* Fill with zeros to start with */ Parameters.vecrPSD.Init(iVecSize, 0.0); for (i=iStartIndex, j=iStartBin; j<=iEndBin; i++,j++) Parameters.vecrPSD[i] = vecrData[j]; CalculateSigStrengthCorrection(Parameters, vecrData); CalculatePSDInterferenceTag(Parameters, vecrData); } /* * This function is called in a context where the Parameters structure is Locked. */ void CReceiveData::CalculateSigStrengthCorrection(CParameter &Parameters, CVector<_REAL> &vecrPSD) { _REAL rCorrection = _REAL(0.0); /* Calculate signal power in measurement bandwidth */ _REAL rFreqKmin, rFreqKmax; _REAL rIFCentreFrequency = Parameters.FrontEndParameters.rIFCentreFreq; if (Parameters.GetAcquiState() == AS_WITH_SIGNAL && Parameters.FrontEndParameters.bAutoMeasurementBandwidth) { // Receiver is locked, so measure in the current DRM signal bandwidth Kmin to Kmax _REAL rDCFrequency = Parameters.GetDCFrequency(); rFreqKmin = rDCFrequency + _REAL(Parameters.CellMappingTable.iCarrierKmin)/Parameters.CellMappingTable.iFFTSizeN * iSampleRate; rFreqKmax = rDCFrequency + _REAL(Parameters.CellMappingTable.iCarrierKmax)/Parameters.CellMappingTable.iFFTSizeN * iSampleRate; } else { // Receiver unlocked, or measurement is requested in fixed bandwidth _REAL rMeasBandwidth = Parameters.FrontEndParameters.rDefaultMeasurementBandwidth; rFreqKmin = rIFCentreFrequency - rMeasBandwidth/_REAL(2.0); rFreqKmax = rIFCentreFrequency + rMeasBandwidth/_REAL(2.0); } _REAL rSigPower = CalcTotalPower(vecrPSD, FreqToBin(rFreqKmin), FreqToBin(rFreqKmax)); if (Parameters.FrontEndParameters.eSMeterCorrectionType == CFrontEndParameters::S_METER_CORRECTION_TYPE_AGC_ONLY) { /* Write it to the receiver params to help with calculating the signal strength */ rCorrection += _REAL(10.0) * log10(rSigPower); } else if (Parameters.FrontEndParameters.eSMeterCorrectionType == CFrontEndParameters::S_METER_CORRECTION_TYPE_AGC_RSSI) { _REAL rSMeterBandwidth = Parameters.FrontEndParameters.rSMeterBandwidth; _REAL rFreqSMeterMin = _REAL(rIFCentreFrequency - rSMeterBandwidth / _REAL(2.0)); _REAL rFreqSMeterMax = _REAL(rIFCentreFrequency + rSMeterBandwidth / _REAL(2.0)); _REAL rPowerInSMeterBW = CalcTotalPower(vecrPSD, FreqToBin(rFreqSMeterMin), FreqToBin(rFreqSMeterMax)); /* Write it to the receiver params to help with calculating the signal strength */ rCorrection += _REAL(10.0) * log10(rSigPower/rPowerInSMeterBW); } /* Add on the calibration factor for the current mode */ if (Parameters.GetReceiverMode() == RM_DRM) rCorrection += Parameters.FrontEndParameters.rCalFactorDRM; else if (Parameters.GetReceiverMode() == RM_AM) rCorrection += Parameters.FrontEndParameters.rCalFactorAM; Parameters.rSigStrengthCorrection = rCorrection; return; } /* * This function is called in a context where the Parameters structure is Locked. */ void CReceiveData::CalculatePSDInterferenceTag(CParameter &Parameters, CVector<_REAL> &vecrPSD) { /* Interference tag (rnip) */ // Calculate search range: defined as +/-5.1kHz except if locked and in 20k _REAL rIFCentreFrequency = Parameters.FrontEndParameters.rIFCentreFreq; _REAL rFreqSearchMin = rIFCentreFrequency - _REAL(RNIP_SEARCH_RANGE_NARROW); _REAL rFreqSearchMax = rIFCentreFrequency + _REAL(RNIP_SEARCH_RANGE_NARROW); ESpecOcc eSpecOcc = Parameters.GetSpectrumOccup(); if (Parameters.GetAcquiState() == AS_WITH_SIGNAL && (eSpecOcc == SO_4 || eSpecOcc == SO_5) ) { rFreqSearchMax = rIFCentreFrequency + _REAL(RNIP_SEARCH_RANGE_WIDE); } int iSearchStartBin = FreqToBin(rFreqSearchMin); int iSearchEndBin = FreqToBin(rFreqSearchMax); if (iSearchStartBin < 0) iSearchStartBin = 0; if (iSearchEndBin > LEN_PSD_AV_EACH_BLOCK_RSI/2) iSearchEndBin = LEN_PSD_AV_EACH_BLOCK_RSI/2; _REAL rMaxPSD = _REAL(-1000.0); int iMaxPSDBin = 0; for (int i=iSearchStartBin; i<=iSearchEndBin; i++) { _REAL rPSD = _REAL(2.0) * pow(_REAL(10.0), vecrPSD[i]/_REAL(10.0)); if (rPSD > rMaxPSD) { rMaxPSD = rPSD; iMaxPSDBin = i; } } // For total signal power, exclude the biggest one and e.g. 2 either side int iExcludeStartBin = iMaxPSDBin - RNIP_EXCLUDE_BINS; int iExcludeEndBin = iMaxPSDBin + RNIP_EXCLUDE_BINS; // Calculate power. TotalPower() function will deal with start>end correctly _REAL rSigPowerExcludingInterferer = CalcTotalPower(vecrPSD, iSearchStartBin, iExcludeStartBin-1) + CalcTotalPower(vecrPSD, iExcludeEndBin+1, iSearchEndBin); /* interferer level wrt signal power */ Parameters.rMaxPSDwrtSig = _REAL(10.0) * log10(rMaxPSD / rSigPowerExcludingInterferer); /* interferer frequency */ Parameters.rMaxPSDFreq = _REAL(iMaxPSDBin) * _REAL(iSampleRate) / _REAL(LEN_PSD_AV_EACH_BLOCK_RSI) - rIFCentreFrequency; } int CReceiveData::FreqToBin(_REAL rFreq) { return int(rFreq/iSampleRate * LEN_PSD_AV_EACH_BLOCK_RSI); } _REAL CReceiveData::CalcTotalPower(CVector<_REAL> &vecrData, int iStartBin, int iEndBin) { if (iStartBin < 0) iStartBin = 0; if (iEndBin > LEN_PSD_AV_EACH_BLOCK_RSI/2) iEndBin = LEN_PSD_AV_EACH_BLOCK_RSI/2; _REAL rSigPower = _REAL(0.0); for (int i=iStartBin; i<=iEndBin; i++) { _REAL rPSD = pow(_REAL(10.0), vecrData[i]/_REAL(10.0)); // The factor of 2 below is needed because half of the power is in the negative frequencies rSigPower += rPSD * _REAL(2.0); } return rSigPower; }
33.79476
144
0.592816
mfkiwl
39e2e124b0dbd8950a1a7d138a1b5ee8464995d5
656
cpp
C++
src/gui/widget/BodyWidget/BodyController.cpp
bartkessels/GetIt
8adde91005d00d83a73227a91b08706657513f41
[ "MIT" ]
16
2020-09-07T18:53:39.000Z
2022-03-21T08:15:55.000Z
src/gui/widget/BodyWidget/BodyController.cpp
bartkessels/GetIt
8adde91005d00d83a73227a91b08706657513f41
[ "MIT" ]
23
2017-03-29T21:21:43.000Z
2022-03-23T07:27:55.000Z
src/gui/widget/BodyWidget/BodyController.cpp
bartkessels/GetIt
8adde91005d00d83a73227a91b08706657513f41
[ "MIT" ]
4
2020-06-15T12:51:10.000Z
2021-09-05T20:50:46.000Z
#include "gui/widget/BodyWidget/BodyController.hpp" using namespace getit::gui::widget; BodyController::BodyController(std::shared_ptr<IBodyView> view): view(view) { } void BodyController::registerTab(std::shared_ptr<getit::domain::BeforeRequestPipeline> controller, std::shared_ptr<QWidget> tab, std::string name) { this->tabControllers.push_back(controller); view->addBodyTab(tab.get(), name); } void BodyController::executeBeforeRequest(std::shared_ptr<getit::domain::RequestData> data) { int currentTabIndex = view->getSelectedTabIndex(); auto body = tabControllers.at(currentTabIndex); body->executeBeforeRequest(data); }
28.521739
146
0.760671
bartkessels
39e2e6f4d2351b8444b28edacee97376057ee6d6
665
hpp
C++
core/impl/memory/free_first_fit.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
core/impl/memory/free_first_fit.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
core/impl/memory/free_first_fit.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
#ifndef E2_FREE_FIRST_FIT_HPP #define E2_FREE_FIRST_FIT_HPP #include "i_free.hpp" #include "memory_common.hpp" namespace e2 { namespace memory { class free_first_fit_impl { public: template< class T > bool deleting( void * p_mem_start, size_t p_mem_len, std::list< memory_block_info > * mem_blocks, std::list< memory_block_info > * mem_lent, T * p ); bool freeing( void * p_mem_start, size_t p_mem_len, std::list< memory_block_info > * mem_blocks, std::list< memory_block_info > * mem_lent, void * p ); }; #include "free_first_fit.tpp" class free_first_fit : public ::e2::interface::i_free< free_first_fit_impl > {}; } } #endif
28.913043
161
0.714286
auyunli
39e3b63b95788224b22bcbcfb41c9ecca1964d06
457
cpp
C++
ExampleTemplate/ExampleTemplate.cpp
siretty/BrotBoxEngine
e1eb95152ffb8a7051e96a8937aa62f568b90a27
[ "MIT" ]
37
2020-06-14T18:14:08.000Z
2022-03-29T18:39:34.000Z
ExampleTemplate/ExampleTemplate.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
2
2021-04-05T15:34:18.000Z
2021-05-28T00:04:56.000Z
ExampleTemplate/ExampleTemplate.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
10
2020-06-25T17:07:03.000Z
2022-03-08T20:31:17.000Z
#include "BBE/BrotBoxEngine.h" #include <iostream> class MyGame : public bbe::Game { virtual void onStart() override { } virtual void update(float timeSinceLastFrame) override { } virtual void draw3D(bbe::PrimitiveBrush3D & brush) override { } virtual void draw2D(bbe::PrimitiveBrush2D & brush) override { } virtual void onEnd() override { } }; int main() { MyGame *mg = new MyGame(); mg->start(1280, 720, "Template!"); return 0; }
14.741935
60
0.682713
siretty
39e64f1ecc077a97d5a64894fa9edc174bd0f1cd
120,568
cc
C++
lib/ArgParseConvert/test/argument_map_test.cc
JasperBraun/PasteAlignments
5186f674e51571319af3f328c661aaa62dbd0ca9
[ "MIT" ]
null
null
null
lib/ArgParseConvert/test/argument_map_test.cc
JasperBraun/PasteAlignments
5186f674e51571319af3f328c661aaa62dbd0ca9
[ "MIT" ]
null
null
null
lib/ArgParseConvert/test/argument_map_test.cc
JasperBraun/PasteAlignments
5186f674e51571319af3f328c661aaa62dbd0ca9
[ "MIT" ]
null
null
null
// Copyright (c) 2020 Jasper Braun // // 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 "argument_map.h" #define CATCH_CONFIG_MAIN #define CATCH_CONFIG_COLOUR_NONE #include "catch.h" #include "string_conversions.h" // include after catch.h // Test correctness for: // * ArgumentMap(ParameterMap) // * SetDefaultArguments // * AddArgument // * GetUnfilledParameters // * HasArgument // * ArgumentsOf // * GetValue // * GetAllValues // * IsSet // // Test invariants for: // * ArgumentMap(ParameterMap) // // Test exceptions for: // * AddArgument // * HasArgument // * ArgumentsOf // * GetValue // * GetAllValues // * IsSet namespace arg_parse_convert { namespace test { struct TestType { int data; TestType() = default; TestType(int d) : data{d} {} inline bool operator==(const TestType& other) const { return (data == other.data); } }; inline TestType StringToTestType(const std::string& s) { TestType result; result.data = std::stoi(s); return result; } namespace { // NoMin, YesMin, NoMax, YesMax indicate whether minimum and maximum arguments // are set. // * NoArgs: no arguments // * UnderfullArgs: some arguments, but less than its minimum // * MinArgs: exactly as many arguments as its minimum // * ManyArgs: more arguments than its minimum but less than its maximum // * FullArgs: as many arguments as its maximum // Parameter<std::string> kNoMinNoMaxNoArgs{Parameter<std::string>::Positional( converters::StringIdentity, "kNoMinNoMaxNoArgs", 0)}; Parameter<std::string> kNoMinYesMaxNoArgs{Parameter<std::string>::Keyword( converters::StringIdentity, {"kNoMinYesMaxNoArgs", "alt_kNoMinYesMaxNoArgs"}) .MaxArgs(8)}; Parameter<int> kNoMinYesMaxManyArgs{Parameter<int>::Positional( converters::stoi, "kNoMinYesMaxManyArgs", 1) .MaxArgs(8)}; Parameter<int> kNoMinYesMaxFullArgs{Parameter<int>::Keyword( converters::stoi, {"kNoMinYesMaxFullArgs", "alt_kNoMinYesMaxFullArgs"}) .MaxArgs(8)}; Parameter<TestType> kYesMinNoMaxNoArgs{Parameter<TestType>::Positional( StringToTestType, "kYesMinNoMaxNoArgs", 2) .MinArgs(4)}; Parameter<TestType> kYesMinNoMaxUnderfullArgs{Parameter<TestType>::Keyword( StringToTestType, {"kYesMinNoMaxUnderfullArgs", "alt_kYesMinNoMaxUnderfullArgs"}) .MinArgs(4)}; Parameter<long> kYesMinNoMaxMinArgs{Parameter<long>::Positional( converters::stol, "kYesMinNoMaxMinArgs", 3) .MinArgs(4)}; Parameter<long> kYesMinYesMaxNoArgs{Parameter<long>::Keyword( converters::stol, {"kYesMinYesMaxNoArgs", "alt_kYesMinYesMaxNoArgs"}) .MaxArgs(8).MinArgs(4)}; Parameter<float> kYesMinYesMaxUnderfullArgs{Parameter<float>::Positional( converters::stof, "kYesMinYesMaxUnderfullArgs", 4) .MaxArgs(8).MinArgs(4)}; Parameter<float> kYesMinYesMaxMinArgs{Parameter<float>::Keyword( converters::stof, {"kYesMinYesMaxMinArgs", "alt_kYesMinYesMaxMinArgs"}) .MaxArgs(8).MinArgs(4)}; Parameter<double> kYesMinYesMaxManyArgs{Parameter<double>::Positional( converters::stod, "kYesMinYesMaxManyArgs", 5) .MaxArgs(8).MinArgs(4)}; Parameter<double> kYesMinYesMaxFullArgs{Parameter<double>::Keyword( converters::stod, {"kYesMinYesMaxFullArgs", "alt_kYesMinYesMaxFullArgs"}) .MaxArgs(8).MinArgs(4)}; std::vector<std::string> kArgs{"1.0", "2.0", "2.0", "4.0", "5.0", "6.0", "7.0", "8.0", "9.0", "10.0"}; std::vector<std::string> kDefaultArgs{"10.0", "20.0", "20.0", "40.0", "50.0", "60.0", "70.0", "80.0", "90.0", "100.0"}; Parameter<bool> kSetFlag{Parameter<bool>::Flag({"kSetFlag", "alt_kSetFlag"})}; Parameter<bool> kUnsetFlag{Parameter<bool>::Flag({"kUnsetFlag", "alt_kUnsetFlag"})}; Parameter<bool> kMultipleSetFlag{Parameter<bool>::Flag( {"kMultipleSetFlag", "alt_kMultipleSetFlag"})}; Parameter<TestType> kNoConverterPositional{Parameter<TestType>::Positional( nullptr, "kNoConverterPositional", 6)}; Parameter<TestType> kNoConverterKeyword{Parameter<TestType>::Keyword( nullptr, {"kNoConverterKeyword", "alt_kNoConverterKeyword"})}; std::vector<std::string> kNames{ "kNoMinNoMaxNoArgs", "kNoMinYesMaxNoArgs", "alt_kNoMinYesMaxNoArgs", "kNoMinYesMaxManyArgs", "kNoMinYesMaxFullArgs", "alt_kNoMinYesMaxFullArgs", "kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs", "alt_kYesMinNoMaxUnderfullArgs", "kYesMinNoMaxMinArgs", "kYesMinYesMaxNoArgs", "alt_kYesMinYesMaxNoArgs", "kYesMinYesMaxUnderfullArgs", "kYesMinYesMaxMinArgs", "alt_kYesMinYesMaxMinArgs", "kYesMinYesMaxManyArgs", "kYesMinYesMaxFullArgs", "alt_kYesMinYesMaxFullArgs", "kSetFlag", "alt_kSetFlag", "kUnsetFlag", "alt_kUnsetFlag", "kMultipleSetFlag", "alt_kMultipleSetFlag", "kNoConverterPositional", "kNoConverterKeyword", "alt_kNoConverterKeyword"}; SCENARIO("Test correctness of ArgumentMap::ArgumentMap(ParameterMap).", "[ArgumentMap][ArgumentMap(ParameterMap)][correctness]") { GIVEN("A `ParameterMap` object containing various parameters.") { ParameterMap parameter_map, reference; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); reference = parameter_map; WHEN("Constructed from the parameters.") { ArgumentMap argument_map(std::move(parameter_map)); THEN("The `ParameterMap` becomes a member of the `ArgumentMap`.") { for (const std::string& name : kNames) { CHECK(argument_map.Parameters().GetConfiguration(name) == reference.GetConfiguration(name)); CHECK(argument_map.Parameters().required_parameters() == reference.required_parameters()); CHECK(argument_map.Parameters().positional_parameters() == reference.positional_parameters()); CHECK(argument_map.Parameters().keyword_parameters() == reference.keyword_parameters()); CHECK(argument_map.Parameters().flags() == reference.flags()); } } THEN("All argument lists begin empty.") { for (const std::string& name : kNames) { CHECK(argument_map.ArgumentsOf(name).empty()); } } } } } SCENARIO("Test invariant preservation by" " ArgumentMap::ArgumentMap(ParameterMap).", "[ArgumentMap][ArgumentMap(ParameterMap)][invariants]") { GIVEN("A `ParameterMap` object containing various parameters.") { int size = GENERATE(range(0, 21, 4)); ParameterMap parameter_map, reference; for (int i = 0; i < size; i += 4) { parameter_map(Parameter<bool>::Flag({kNames.at(i)})) (Parameter<int>::Keyword( converters::stoi, {kNames.at(i+1), kNames.at(i+2)})) (Parameter<std::string>::Positional( converters::StringIdentity, kNames.at(i+3), i)); } reference = parameter_map; WHEN("Constructed from the parameters.") { ArgumentMap argument_map(std::move(parameter_map)); THEN("The object's size is the same as the number of parameters.") { CHECK(argument_map.size() == reference.size()); CHECK(argument_map.Arguments().size() == reference.size()); CHECK(argument_map.Values().size() == reference.size()); } } } } SCENARIO("Test correctness of ArgumentMap::SetDefaultArguments.", "[ArgumentMap][SetDefaultArguments][correctness]") { GIVEN("Parameters without default arguments.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); WHEN("Argument lists are empty.") { ArgumentMap argument_map(std::move(parameter_map)); ArgumentMap reference{argument_map}; argument_map.SetDefaultArguments(); THEN("Argument lists remain unchanged.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == reference.ArgumentsOf("kNoMinNoMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == reference.ArgumentsOf("kNoMinYesMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == reference.ArgumentsOf("kNoMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == reference.ArgumentsOf("kNoMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == reference.ArgumentsOf("kYesMinNoMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == reference.ArgumentsOf("kYesMinNoMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == reference.ArgumentsOf("kYesMinYesMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == reference.ArgumentsOf("kYesMinYesMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == reference.ArgumentsOf("kYesMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == reference.ArgumentsOf("kYesMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kSetFlag") == reference.ArgumentsOf("kSetFlag")); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == reference.ArgumentsOf("kUnsetFlag")); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == reference.ArgumentsOf("kMultipleSetFlag")); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == reference.ArgumentsOf("kNoConverterPositional")); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == reference.ArgumentsOf("kNoConverterKeyword")); } } WHEN("Argument lists already contain some arguments.") { ArgumentMap argument_map(std::move(parameter_map)); for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } ArgumentMap reference{argument_map}; argument_map.SetDefaultArguments(); THEN("Argument lists remain unchanged.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == reference.ArgumentsOf("kNoMinNoMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == reference.ArgumentsOf("kNoMinYesMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == reference.ArgumentsOf("kNoMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == reference.ArgumentsOf("kNoMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == reference.ArgumentsOf("kYesMinNoMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == reference.ArgumentsOf("kYesMinNoMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == reference.ArgumentsOf("kYesMinYesMaxNoArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == reference.ArgumentsOf("kYesMinYesMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == reference.ArgumentsOf("kYesMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == reference.ArgumentsOf("kYesMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kSetFlag") == reference.ArgumentsOf("kSetFlag")); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == reference.ArgumentsOf("kUnsetFlag")); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == reference.ArgumentsOf("kMultipleSetFlag")); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == reference.ArgumentsOf("kNoConverterPositional")); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == reference.ArgumentsOf("kNoConverterKeyword")); } } } GIVEN("Parameters with default arguments.") { int count = GENERATE(range(1, 10)); ParameterMap parameter_map; std::vector<std::string> default_args{kDefaultArgs.begin(), kDefaultArgs.begin() + count}; parameter_map(kNoMinNoMaxNoArgs.SetDefault(default_args)) (kNoMinYesMaxNoArgs.SetDefault(default_args)) (kNoMinYesMaxManyArgs.SetDefault(default_args)) (kNoMinYesMaxFullArgs.SetDefault(default_args)) (kYesMinNoMaxNoArgs.SetDefault(default_args)) (kYesMinNoMaxUnderfullArgs.SetDefault(default_args)) (kYesMinNoMaxMinArgs.SetDefault(default_args)) (kYesMinYesMaxNoArgs.SetDefault(default_args)) (kYesMinYesMaxUnderfullArgs.SetDefault(default_args)) (kYesMinYesMaxMinArgs.SetDefault(default_args)) (kYesMinYesMaxManyArgs.SetDefault(default_args)) (kYesMinYesMaxFullArgs.SetDefault(default_args)) (kSetFlag.SetDefault(default_args)) (kUnsetFlag.SetDefault(default_args)) (kMultipleSetFlag.SetDefault(default_args)) (kNoConverterPositional.SetDefault(default_args)) (kNoConverterKeyword.SetDefault(default_args)); WHEN("Argument lists are empty.") { ArgumentMap argument_map(std::move(parameter_map)); ArgumentMap reference{argument_map}; argument_map.SetDefaultArguments(); THEN("Argument lists are added to where appropriate up to maximum.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == default_args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == default_args); CHECK(argument_map.ArgumentsOf("kSetFlag") == reference.ArgumentsOf("kSetFlag")); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == reference.ArgumentsOf("kUnsetFlag")); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == reference.ArgumentsOf("kMultipleSetFlag")); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == default_args); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == default_args); } } WHEN("Argument lists already contain some arguments.") { ArgumentMap argument_map(std::move(parameter_map)); for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } ArgumentMap reference{argument_map}; argument_map.SetDefaultArguments(); THEN("Arguments are assigned only to non-empty, non-flag parameters.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == reference.ArgumentsOf("kNoMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == reference.ArgumentsOf("kNoMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == reference.ArgumentsOf("kYesMinNoMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == default_args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == reference.ArgumentsOf("kYesMinYesMaxMinArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == reference.ArgumentsOf("kYesMinYesMaxManyArgs")); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == reference.ArgumentsOf("kYesMinYesMaxFullArgs")); CHECK(argument_map.ArgumentsOf("kSetFlag") == reference.ArgumentsOf("kSetFlag")); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == reference.ArgumentsOf("kUnsetFlag")); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == reference.ArgumentsOf("kMultipleSetFlag")); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == reference.ArgumentsOf("kNoConverterPositional")); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == reference.ArgumentsOf("kNoConverterKeyword")); } } } } SCENARIO("Test correctness of ArgumentMap::AddArgument.", "[ArgumentMap][AddArgument][correctness]") { GIVEN("Parameters without default arguments.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); WHEN("Argument lists are empty.") { ArgumentMap argument_map(std::move(parameter_map)); std::vector<std::string> args{kArgs.begin(), kArgs.begin() + 8}; for (const std::string& arg : args) { argument_map.AddArgument("kNoMinNoMaxNoArgs", arg); argument_map.AddArgument("kNoMinYesMaxNoArgs", arg); argument_map.AddArgument("kNoMinYesMaxManyArgs", arg); argument_map.AddArgument("kNoMinYesMaxFullArgs", arg); argument_map.AddArgument("kYesMinNoMaxNoArgs", arg); argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", arg); argument_map.AddArgument("kYesMinNoMaxMinArgs", arg); argument_map.AddArgument("kYesMinYesMaxNoArgs", arg); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", arg); argument_map.AddArgument("kYesMinYesMaxMinArgs", arg); argument_map.AddArgument("kYesMinYesMaxManyArgs", arg); argument_map.AddArgument("kYesMinYesMaxFullArgs", arg); argument_map.AddArgument("kSetFlag", arg); argument_map.AddArgument("kUnsetFlag", arg); argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("They are appended to the existing list of arguments.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args); CHECK(argument_map.ArgumentsOf("kSetFlag") == args); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == args); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == args); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == args); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == args); } THEN("More arguments are ignored by parameters with argument limits.") { for (auto it = kArgs.begin() + 8; it != kArgs.end(); ++it) { argument_map.AddArgument("kNoMinYesMaxNoArgs", *it); argument_map.AddArgument("kNoMinYesMaxManyArgs", *it); argument_map.AddArgument("kNoMinYesMaxFullArgs", *it); argument_map.AddArgument("kYesMinYesMaxNoArgs", *it); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", *it); argument_map.AddArgument("kYesMinYesMaxMinArgs", *it); argument_map.AddArgument("kYesMinYesMaxManyArgs", *it); argument_map.AddArgument("kYesMinYesMaxFullArgs", *it); } CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args); } THEN("More arguments are added for parameters without argument limits.") { for (auto it = kArgs.begin() + 8; it != kArgs.end(); ++it) { argument_map.AddArgument("kNoMinNoMaxNoArgs", *it); argument_map.AddArgument("kYesMinNoMaxNoArgs", *it); argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", *it); argument_map.AddArgument("kYesMinNoMaxMinArgs", *it); argument_map.AddArgument("kSetFlag", *it); argument_map.AddArgument("kUnsetFlag", *it); argument_map.AddArgument("kMultipleSetFlag", *it); argument_map.AddArgument("kNoConverterPositional", *it); argument_map.AddArgument("kNoConverterKeyword", *it); } CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kSetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs); } } WHEN("Argument lists already contain some arguments.") { ArgumentMap argument_map(std::move(parameter_map)); for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } std::vector<std::string> args{kArgs.begin(), kArgs.begin() + 8}; for (int i = 0; i < 10; ++i) { argument_map.AddArgument("kNoMinNoMaxNoArgs", kArgs.at(i)); argument_map.AddArgument("kNoMinYesMaxNoArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinNoMaxNoArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxNoArgs", kArgs.at(i)); argument_map.AddArgument("kUnsetFlag", kArgs.at(i)); if (i >= 1) { argument_map.AddArgument("kSetFlag", kArgs.at(i)); } if (i >= 2) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } if (i >= 4) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } if (i >= 6) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } if (i >= 8) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } } THEN("Arguments are added until argument limit is reached, if any.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args); CHECK(argument_map.ArgumentsOf("kSetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs); } } } } SCENARIO("Test exceptions thrown by ArgumentMap::AddArgument.", "[ArgumentMap][AddArgument][exceptions]") { GIVEN("Parameters without default arguments.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); ArgumentMap argument_map(std::move(parameter_map)); THEN("Adding arguments to parameters of unknown names causes exception.") { CHECK_THROWS_AS(argument_map.AddArgument("unknown_name", "arg"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.AddArgument("foo", "arg"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.AddArgument("b", "ARG"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.AddArgument("", "arg"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.AddArgument("bazinga", ""), exceptions::ParameterAccessError); } THEN("Adding arguments to recognized parameters doesn't cause exception.") { std::string name = GENERATE(from_range(kNames)); CHECK_NOTHROW(argument_map.AddArgument(name, "arg")); } } } SCENARIO("Test correctness of ArgumentMap::GetUnfilledParameters.", "[ArgumentMap][GetUnfilledParameters][correctness]") { GIVEN("Various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); WHEN("Argument lists are empty.") { ArgumentMap argument_map(std::move(parameter_map)); std::vector<std::string> unfilled_parameters{ argument_map.GetUnfilledParameters()}; THEN("Parameters with minimum argument numbers are unfilled.") { CHECK(unfilled_parameters == std::vector<std::string>{ "kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs", "kYesMinNoMaxMinArgs", "kYesMinYesMaxNoArgs", "kYesMinYesMaxUnderfullArgs", "kYesMinYesMaxMinArgs", "kYesMinYesMaxManyArgs", "kYesMinYesMaxFullArgs"}); } } WHEN("Argument lists already contain some arguments.") { ArgumentMap argument_map(std::move(parameter_map)); for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } std::vector<std::string> unfilled_parameters{ argument_map.GetUnfilledParameters()}; THEN("Parameters with too few arguments are unfilled.") { CHECK(unfilled_parameters == std::vector<std::string>{ "kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs", "kYesMinYesMaxNoArgs", "kYesMinYesMaxUnderfullArgs"}); } } } } SCENARIO("Test correctness of ArgumentMap::HasArgument.", "[ArgumentMap][HasArgument][correctness]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("None of them has arguments.") { CHECK_FALSE(argument_map.HasArgument("kNoMinNoMaxNoArgs")); CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxNoArgs")); CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxManyArgs")); CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxFullArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxNoArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxMinArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxNoArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxMinArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxManyArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxFullArgs")); CHECK_FALSE(argument_map.HasArgument("kSetFlag")); CHECK_FALSE(argument_map.HasArgument("kUnsetFlag")); CHECK_FALSE(argument_map.HasArgument("kMultipleSetFlag")); CHECK_FALSE(argument_map.HasArgument("kNoConverterPositional")); CHECK_FALSE(argument_map.HasArgument("kNoConverterKeyword")); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("All arguments with non-empty lists have arguments.") { CHECK_FALSE(argument_map.HasArgument("kNoMinNoMaxNoArgs")); CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxNoArgs")); CHECK(argument_map.HasArgument("kNoMinYesMaxManyArgs")); CHECK(argument_map.HasArgument("kNoMinYesMaxFullArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxNoArgs")); CHECK(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs")); CHECK(argument_map.HasArgument("kYesMinNoMaxMinArgs")); CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxNoArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxMinArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxManyArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxFullArgs")); CHECK(argument_map.HasArgument("kSetFlag")); CHECK_FALSE(argument_map.HasArgument("kUnsetFlag")); CHECK(argument_map.HasArgument("kMultipleSetFlag")); CHECK(argument_map.HasArgument("kNoConverterPositional")); CHECK(argument_map.HasArgument("kNoConverterKeyword")); } } WHEN("Default arguments are set for all arguments.") { argument_map.SetDefaultArguments(); THEN("All non-flag parameters have arguments.") { CHECK(argument_map.HasArgument("kNoMinNoMaxNoArgs")); CHECK(argument_map.HasArgument("kNoMinYesMaxNoArgs")); CHECK(argument_map.HasArgument("kNoMinYesMaxManyArgs")); CHECK(argument_map.HasArgument("kNoMinYesMaxFullArgs")); CHECK(argument_map.HasArgument("kYesMinNoMaxNoArgs")); CHECK(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs")); CHECK(argument_map.HasArgument("kYesMinNoMaxMinArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxNoArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxMinArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxManyArgs")); CHECK(argument_map.HasArgument("kYesMinYesMaxFullArgs")); CHECK_FALSE(argument_map.HasArgument("kSetFlag")); CHECK_FALSE(argument_map.HasArgument("kUnsetFlag")); CHECK_FALSE(argument_map.HasArgument("kMultipleSetFlag")); CHECK(argument_map.HasArgument("kNoConverterPositional")); CHECK(argument_map.HasArgument("kNoConverterKeyword")); } } } } SCENARIO("Test exceptions thrown by ArgumentMap::HasArgument.", "[ArgumentMap][HasArgument][exceptions]") { GIVEN("Parameters without default arguments.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Testing arguments of parameters of unknown names causes exception.") { CHECK_THROWS_AS(argument_map.HasArgument("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("bazinga"), exceptions::ParameterAccessError); } THEN("Testing arguments of recognized names doesn't cause exception.") { std::string name = GENERATE(from_range(kNames)); CHECK_NOTHROW(argument_map.HasArgument(name)); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Testing arguments of parameters of unknown names causes exception.") { CHECK_THROWS_AS(argument_map.HasArgument("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.HasArgument("bazinga"), exceptions::ParameterAccessError); } THEN("Testing arguments of recognized names doesn't cause exception.") { std::string name = GENERATE(from_range(kNames)); CHECK_NOTHROW(argument_map.HasArgument(name)); } } } } SCENARIO("Test correctness of ArgumentMap::ArgumentsOf.", "[ArgumentMap][ArgumentsOf][correctness]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("None of them has arguments.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kSetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == std::vector<std::string>{}); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Partial argument lists are returned.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 6}); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 8}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 2}); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 4}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 2}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 4}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 6}); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 8}); CHECK(argument_map.ArgumentsOf("kSetFlag") == std::vector<std::string>{kArgs.begin(), kArgs.begin() + 1}); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs); } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("All default arguments are returned for non-flag parameters.") { CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kSetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kUnsetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == std::vector<std::string>{}); CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kDefaultArgs); CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kDefaultArgs); } } } } SCENARIO("Test exceptions thrown by ArgumentMap::ArgumentsOf.", "[ArgumentMap][ArgumentsOf][exceptions]") { GIVEN("Parameters without default arguments.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs) (kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs) (kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs) (kYesMinNoMaxMinArgs) (kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs) (kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs) (kYesMinYesMaxFullArgs) (kSetFlag)(kUnsetFlag)(kMultipleSetFlag) (kNoConverterPositional)(kNoConverterKeyword); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.ArgumentsOf("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("bazinga"), exceptions::ParameterAccessError); } THEN("Getting arguments of recognized names doesn't cause exception.") { std::string name = GENERATE(from_range(kNames)); CHECK_NOTHROW(argument_map.ArgumentsOf(name)); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Testing arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.ArgumentsOf("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.ArgumentsOf("bazinga"), exceptions::ParameterAccessError); } THEN("Testing arguments of recognized names doesn't cause exception.") { std::string name = GENERATE(from_range(kNames)); CHECK_NOTHROW(argument_map.ArgumentsOf(name)); } } } } SCENARIO("Test correctness of ArgumentMap::GetValue.", "[ArgumentMap][GetValue][correctness]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Calling function without specifying position gets first value.") { CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs") == 1); CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs") == 1); CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs") == TestType{1}); CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs") == 1l); CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs") == Approx(1.0f)); CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs") == Approx(1.0f)); CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs") == Approx(1.0)); CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs") == Approx(1.0)); } THEN("Specifying valid position will return the requested value.") { int i = GENERATE(range(0, 7)); if (i < 2) { CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs", i) == TestType{std::stoi(kArgs.at(i))}); CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs", i) == Approx(std::stof(kArgs.at(i)))); } if (i < 4) { CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", i) == std::stol(kArgs.at(i))); CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs", i) == Approx(std::stof(kArgs.at(i)))); } if (i < 6) { CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", i) == std::stoi(kArgs.at(i))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs", i) == Approx(std::stod(kArgs.at(i)))); } if (i < 8) { CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", i) == std::stoi(kArgs.at(i))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs", i) == Approx(std::stod(kArgs.at(i)))); } } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("Calling function without specifying position gets first value.") { CHECK(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs") == converters::StringIdentity(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<std::string>("kNoMinYesMaxNoArgs") == converters::StringIdentity(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs") == std::stoi(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs") == std::stoi(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxNoArgs") == StringToTestType(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs") == StringToTestType(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs") == std::stol(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<long>("kYesMinYesMaxNoArgs") == std::stol(kDefaultArgs.at(0))); CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs") == Approx(std::stof(kDefaultArgs.at(0)))); CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs") == Approx(std::stof(kDefaultArgs.at(0)))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs") == Approx(std::stod(kDefaultArgs.at(0)))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs") == Approx(std::stod(kDefaultArgs.at(0)))); } THEN("Specifying valid position will return the requested value.") { int i = GENERATE(range(0, 8)); if (i < 2) { CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs", i) == TestType{std::stoi(kDefaultArgs.at(i))}); CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs", i) == Approx(std::stof(kDefaultArgs.at(i)))); } if (i < 4) { CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", i) == std::stol(kDefaultArgs.at(i))); CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs", i) == Approx(std::stof(kDefaultArgs.at(i)))); } if (i < 6) { CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", i) == std::stoi(kDefaultArgs.at(i))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs", i) == Approx(std::stod(kDefaultArgs.at(i)))); } if (i < 8) { CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", i) == std::stoi(kDefaultArgs.at(i))); CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs", i) == Approx(std::stod(kDefaultArgs.at(i)))); } } } } } SCENARIO("Test exceptions thrown by ArgumentMap::GetValue.", "[ArgumentMap][GetValue][exceptions]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Accessing value beyond argument list's range causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>( "kYesMinNoMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinNoMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>( "kYesMinYesMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>("kYesMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>("kYesMinYesMaxFullArgs"), exceptions::ValueAccessError); } THEN("Flags cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Accessing value beyond argument list's range causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxNoArgs", 0), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", 6), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", 8), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>( "kYesMinNoMaxNoArgs", kArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>( "kYesMinNoMaxUnderfullArgs", 2), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", 4), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinYesMaxNoArgs", 1), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>( "kYesMinYesMaxUnderfullArgs", kArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>( "kYesMinYesMaxMinArgs", kArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>( "kYesMinYesMaxManyArgs", kArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>( "kYesMinYesMaxFullArgs", kArgs.size()), exceptions::ValueAccessError); } THEN("Flags cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Accessing value beyond argument list's range causes exception.") { CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinNoMaxNoArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<std::string>( "kNoMinYesMaxNoArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>( "kNoMinYesMaxManyArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<int>( "kNoMinYesMaxFullArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>( "kYesMinNoMaxNoArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<TestType>( "kYesMinNoMaxUnderfullArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinNoMaxMinArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<long>( "kYesMinYesMaxNoArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>( "kYesMinYesMaxUnderfullArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<float>( "kYesMinYesMaxMinArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>( "kYesMinYesMaxManyArgs", kDefaultArgs.size()), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<double>( "kYesMinYesMaxFullArgs", kDefaultArgs.size()), exceptions::ValueAccessError); } THEN("Flags cause exception.") { CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } } } SCENARIO("Test correctness of ArgumentMap::GetAllValues.", "[ArgumentMap][GetAllValues][correctness]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Empty value lists are returned.") { CHECK(argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs") == std::vector<std::string>{}); CHECK(argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs") == std::vector<int>{}); CHECK(argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs") == std::vector<int>{}); CHECK(argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs") == std::vector<TestType>{}); CHECK(argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs") == std::vector<TestType>{}); CHECK(argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs") == std::vector<long>{}); CHECK(argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs") == std::vector<long>{}); CHECK(argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs") == std::vector<float>{}); CHECK(argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs") == std::vector<float>{}); CHECK(argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs") == std::vector<double>{}); CHECK(argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs") == std::vector<double>{}); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } std::vector<std::string> kNoMinNoMaxNoArgs_vals{ argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs")}; std::vector<std::string> kNoMinYesMaxNoArgs_vals{ argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs")}; std::vector<int> kNoMinYesMaxManyArgs_vals{ argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs")}; std::vector<int> kNoMinYesMaxFullArgs_vals{ argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs")}; std::vector<TestType> kYesMinNoMaxNoArgs_vals{ argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs")}; std::vector<TestType> kYesMinNoMaxUnderfullArgs_vals{ argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs")}; std::vector<long> kYesMinNoMaxMinArgs_vals{ argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs")}; std::vector<long> kYesMinYesMaxNoArgs_vals{ argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs")}; std::vector<float> kYesMinYesMaxUnderfullArgs_vals{ argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs")}; std::vector<float> kYesMinYesMaxMinArgs_vals{ argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs")}; std::vector<double> kYesMinYesMaxManyArgs_vals{ argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs")}; std::vector<double> kYesMinYesMaxFullArgs_vals{ argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs")}; THEN("Values for all arguments are returned.") { CHECK(kNoMinNoMaxNoArgs_vals == std::vector<std::string>{}); CHECK(kNoMinYesMaxNoArgs_vals == std::vector<std::string>{}); CHECK(kYesMinNoMaxNoArgs_vals == std::vector<TestType>{}); CHECK(kYesMinYesMaxNoArgs_vals == std::vector<long>{}); for (int i = 0; i < 2; ++i) { CHECK(kYesMinNoMaxUnderfullArgs_vals.at(i) == StringToTestType( argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs").at(i))); CHECK(kYesMinYesMaxUnderfullArgs_vals.at(i) == std::stof(argument_map.ArgumentsOf( "kYesMinYesMaxUnderfullArgs").at(i))); } for (int i = 0; i < 4; ++i) { CHECK(kYesMinNoMaxMinArgs_vals.at(i) == std::stol(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") .at(i))); CHECK(kYesMinYesMaxMinArgs_vals.at(i) == std::stof(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") .at(i))); } for (int i = 0; i < 6; ++i) { CHECK(kNoMinYesMaxManyArgs_vals.at(i) == std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") .at(i))); CHECK(kYesMinYesMaxManyArgs_vals.at(i) == std::stod(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") .at(i))); } for (int i = 0; i < 8; ++i) { CHECK(kNoMinYesMaxFullArgs_vals.at(i) == std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") .at(i))); CHECK(kYesMinYesMaxFullArgs_vals.at(i) == std::stod(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") .at(i))); } } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); std::vector<std::string> kNoMinNoMaxNoArgs_vals{ argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs")}; std::vector<std::string> kNoMinYesMaxNoArgs_vals{ argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs")}; std::vector<int> kNoMinYesMaxManyArgs_vals{ argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs")}; std::vector<int> kNoMinYesMaxFullArgs_vals{ argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs")}; std::vector<TestType> kYesMinNoMaxNoArgs_vals{ argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs")}; std::vector<TestType> kYesMinNoMaxUnderfullArgs_vals{ argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs")}; std::vector<long> kYesMinNoMaxMinArgs_vals{ argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs")}; std::vector<long> kYesMinYesMaxNoArgs_vals{ argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs")}; std::vector<float> kYesMinYesMaxUnderfullArgs_vals{ argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs")}; std::vector<float> kYesMinYesMaxMinArgs_vals{ argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs")}; std::vector<double> kYesMinYesMaxManyArgs_vals{ argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs")}; std::vector<double> kYesMinYesMaxFullArgs_vals{ argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs")}; THEN("Values for all arguments are returned.") { for (int i = 0; i < static_cast<int>(kDefaultArgs.size()); ++i) { CHECK(kNoMinNoMaxNoArgs_vals.at(i) == converters::StringIdentity( argument_map.ArgumentsOf("kNoMinNoMaxNoArgs").at(i))); CHECK(kNoMinYesMaxNoArgs_vals.at(i) == converters::StringIdentity( argument_map.ArgumentsOf("kNoMinYesMaxNoArgs").at(i))); CHECK(kNoMinYesMaxManyArgs_vals.at(i) == std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") .at(i))); CHECK(kNoMinYesMaxFullArgs_vals.at(i) == std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") .at(i))); CHECK(kYesMinNoMaxNoArgs_vals.at(i) == StringToTestType( argument_map.ArgumentsOf("kYesMinNoMaxNoArgs").at(i))); CHECK(kYesMinNoMaxUnderfullArgs_vals.at(i) == StringToTestType( argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs").at(i))); CHECK(kYesMinNoMaxMinArgs_vals.at(i) == std::stol(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") .at(i))); CHECK(kYesMinYesMaxNoArgs_vals.at(i) == std::stol(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") .at(i))); CHECK(kYesMinYesMaxUnderfullArgs_vals.at(i) == std::stof(argument_map.ArgumentsOf( "kYesMinYesMaxUnderfullArgs").at(i))); CHECK(kYesMinYesMaxMinArgs_vals.at(i) == std::stof(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") .at(i))); CHECK(kYesMinYesMaxManyArgs_vals.at(i) == std::stod(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") .at(i))); CHECK(kYesMinYesMaxFullArgs_vals.at(i) == std::stod(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") .at(i))); } } } } } SCENARIO("Test exceptions thrown by ArgumentMap::GetAllValues.", "[ArgumentMap][GetAllValues][exceptions]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>( "kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Flags cause exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>( "kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Flags cause exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<std::string>( "kNoMinYesMaxFullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<int>( "kYesMinNoMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinNoMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kYesMinYesMaxNoArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxUnderfullArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<long>( "kYesMinYesMaxMinArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxManyArgs"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<float>( "kYesMinYesMaxFullArgs"), exceptions::ParameterAccessError); } THEN("Parameters without conversion functions cause exception.") { CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<TestType>( "kNoConverterKeyword"), exceptions::ValueAccessError); } THEN("Flags cause exception if arguments are assigned.") { CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"), exceptions::ValueAccessError); } } } } SCENARIO("Test correctness of ArgumentMap::IsSet.", "[ArgumentMap][IsSet][correctness]") { GIVEN("An ArgumentMap containing various flags.") { ParameterMap parameter_map; parameter_map(kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Flags are not set.") { CHECK_FALSE(argument_map.IsSet("kSetFlag")); CHECK_FALSE(argument_map.IsSet("kUnsetFlag")); CHECK_FALSE(argument_map.IsSet("kMultipleSetFlag")); } } WHEN("Argument lists are partially filled.") { argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); } THEN("Non-empty argument lists mean that flag is set.") { CHECK(argument_map.IsSet("kSetFlag")); CHECK_FALSE(argument_map.IsSet("kUnsetFlag")); CHECK(argument_map.IsSet("kMultipleSetFlag")); } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("Default arguments are never set for flags, so flags are not set.") { CHECK_FALSE(argument_map.IsSet("kSetFlag")); CHECK_FALSE(argument_map.IsSet("kUnsetFlag")); CHECK_FALSE(argument_map.IsSet("kMultipleSetFlag")); } } } } SCENARIO("Test exceptions thrown by ArgumentMap::IsSet.", "[ArgumentMap][IsSet][exceptions]") { GIVEN("An ArgumentMap containing various parameters.") { ParameterMap parameter_map; parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs)) (kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs)) (kSetFlag.SetDefault(kDefaultArgs)) (kUnsetFlag.SetDefault(kDefaultArgs)) (kMultipleSetFlag.SetDefault(kDefaultArgs)) (kNoConverterPositional.SetDefault(kDefaultArgs)) (kNoConverterKeyword.SetDefault(kDefaultArgs)); ArgumentMap argument_map(std::move(parameter_map)); WHEN("Argument lists are empty.") { THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"), exceptions::ValueAccessError); } } WHEN("Argument lists are partially filled.") { for (int i = 0; i < 2; ++i) { argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i)); } for (int i = 0; i < 4; ++i) { argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i)); } for (int i = 0; i < 6; ++i) { argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i)); } for (int i = 0; i < 8; ++i) { argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i)); argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i)); } argument_map.AddArgument("kSetFlag", kArgs.at(0)); for (const std::string& arg : kArgs) { argument_map.AddArgument("kMultipleSetFlag", arg); argument_map.AddArgument("kNoConverterPositional", arg); argument_map.AddArgument("kNoConverterKeyword", arg); } THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"), exceptions::ValueAccessError); } } WHEN("Default arguments are set for all parameters.") { argument_map.SetDefaultArguments(); THEN("Getting arguments of unknown parameters causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("unknown_name"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("foo"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("b"), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet(""), exceptions::ParameterAccessError); CHECK_THROWS_AS(argument_map.IsSet("bazinga"), exceptions::ParameterAccessError); } THEN("Mismatching types causes exception.") { CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"), exceptions::ValueAccessError); CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"), exceptions::ValueAccessError); } } } } } // namespace } // namespace test } // namespace arg_parse_convert
50.069767
82
0.639332
JasperBraun
39ee83e54d46b60df4100a62c6ceedca042acc2d
5,627
cpp
C++
poker/src/DecisionMaker.cpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
1
2021-12-10T06:27:47.000Z
2021-12-10T06:27:47.000Z
poker/src/DecisionMaker.cpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
poker/src/DecisionMaker.cpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
#include "DecisionMaker.hpp" #include <iostream> namespace poker{ void DecisionMaker::decideBetsize() { int bet = 0; double winning_probability = this->data_.probability.first + this->data_.probability.second; if(this->data_.players.at(0).current_decision == CALL) { bet = this->data_.highest_bet <= this->data_.players.at(0).money ? (this->data_.highest_bet - this->data_.players.at(0).money_bet_in_phase) : this->data_.players.at(0).money; } else if(this->data_.players.at(0).current_decision == RAISE) { if(winning_probability <= 80) { bet = (static_cast<double>(this->data_.pot_size)/3.0 > 3 * this->big_blind_) ? static_cast<int>(static_cast<double>(this->data_.pot_size)/3.0) : 3 * this->big_blind_; } else if(winning_probability > 80) { bet = (2 * this->data_.highest_bet > 2 * this->data_.pot_size) ? 2 * this->data_.highest_bet : 2 * this->data_.pot_size; } else { //do nothing } // Check if robot went all in bet = bet <= this->data_.players.at(0).money ? bet : this->data_.players.at(0).money; this->data_.players.at(0).current_decision = HAS_RAISED; } else { //do nothing } // Other player went all in if( this->data_.players.at(1).is_all_in && (this->data_.players.at(0).current_decision == CALL || this->data_.players.at(0).current_decision == RAISE || this->data_.players.at(0).current_decision == HAS_RAISED) ) { // Check if robot has more money than player who went all in if( this->data_.players.at(0).money >= this->data_.players.at(1).current_bet) { bet = this->data_.players.at(1).money_bet_in_phase - this->data_.players.at(0).money_bet_in_phase; } else { this->data_.players.at(0).money; } // set robot player decision to call this->data_.players.at(0).current_decision = CALL; } this->data_.players.at(0).current_bet = bet; if( bet + this->data_.players.at(0).money_bet_in_phase > this->data_.highest_bet) { this->data_.highest_bet = bet + this->data_.players.at(0).money_bet_in_phase; } this->data_.players.at(0).money -= this->data_.players.at(0).current_bet; this->data_.players.at(0).money_bet_in_phase += this->data_.players.at(0).current_bet; } void DecisionMaker::decideMove() { double winning_probability = this->data_.probability.first + this->data_.probability.second; if(winning_probability <= 40) { if(this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase) { // Oponent has raised this->data_.players.at(0).current_decision = FOLD; } else { // Nobody has raised this->data_.players.at(0).current_decision = CHECK; } } else if(winning_probability > 40 && winning_probability <= 60) { if (this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase && this->data_.highest_bet >= static_cast<double>(this->data_.pot_size)/3.0 && this->data_.highest_bet >= 3*this->big_blind_ ) { // Oponent has raised for too much money this->data_.players.at(0).current_decision = FOLD; } else if(this->data_.highest_bet == this->data_.players.at(0).money_bet_in_phase) { // Nobody has raised this->data_.players.at(0).current_decision = CHECK; } else { // Oponent has raised but not too much this->data_.players.at(0).current_decision = CALL; } } else if(winning_probability > 60 && winning_probability <= 80) { if (this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase && this->data_.highest_bet >= 1/3 * this->data_.pot_size && this->data_.highest_bet >= 3*this->big_blind_ ) { // Only call if oponent raised for a high amount this->data_.players.at(0).current_decision = CALL; } else { // raise this->data_.players.at(0).current_decision = RAISE; } } else if(winning_probability > 80) { this->data_.players.at(0).current_decision = RAISE; } else { } //set decision to call if robot has to go all in an decided to raise if(this->data_.highest_bet >= this->data_.players.at(0).money && this->data_.players.at(0).current_decision == RAISE) { this->data_.players.at(0).current_decision = CALL; } } void DecisionMaker::makeDecision() { this->decideMove(); this->decideBetsize(); } }// end namespace poker
36.538961
182
0.513773
JMassing
39f0c4371e2a6bf05e595d225be791b4b51cac0a
1,018
cpp
C++
Leetcode2/207.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
Leetcode2/207.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
Leetcode2/207.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
class Solution { public: bool hasCircle(vector<vector<int>>& graph, vector<bool>& inGraph, vector<bool>& visited, int current){ visited[current] = true; inGraph[current] = true; for(auto adj : graph[current]){ if(!visited[adj]){ if(hasCircle(graph, inGraph, visited, adj)) return true; }else if(inGraph[adj]){ return true; } } inGraph[current] = false; return false; } bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<vector<int>> graph(numCourses, vector<int>()); vector<bool> visited(numCourses, false); vector<bool> inGraph(numCourses, false); for(auto p : prerequisites){ graph[p.first].push_back(p.second); } for(int i=0;i<numCourses;i++){ if(!visited[i]){ if(hasCircle(graph, inGraph, visited, i)) return false; } } return true; } };
32.83871
106
0.543222
nolink
39f60abaee0d398121d6905751915372ae22d6dc
11,163
cpp
C++
CReader_bin.cpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
CReader_bin.cpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
CReader_bin.cpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
/* * CReader.cpp * save laser data to binary file * * Created on: 22.12.2014 * Author: Markus */ #include <iostream> #include <string> #include "CReader.h" #include <sstream> #include <fstream> #include <stdint.h> #include <unistd.h> #include <sys/types.h> #include <math.h> #include <list> #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap/Pointcloud.h> #include "time.h" #include "ip_connection.h" #include "brick_imu.h" #include <boost/chrono/thread_clock.hpp> using namespace boost::chrono; // #define PI 3.14159265 #define CONFIG "/media/usb0/config.cfg" #define HOST "localhost" #define PORT 4223 #define CB_AV_PERIOD 10 #define DEBUG 1 std::fstream logfile; std::stringstream tmpstr; boost::mutex mtx_da; std::stringstream ss; int data_av = 0; bool is_cb_angular = false; bool is_imu_connected; using std::string; using namespace octomap; IPConnection ipcon; IMU imu; // trim a string const std::string trim( const std::string& s) { std::string::size_type first = s.find_first_not_of( ' '); if( first == std::string::npos) { return std::string(); } else { std::string::size_type last = s.find_last_not_of( ' '); /// must succeed return s.substr( first, last - first + 1); } } void debugMessage(int level, string message) { if (level >= DEBUG) std::cerr << message << std::endl; return; } // constructor CReader::CReader() { scancycles = 0; is_imu_connected = false; ip_adress = "192.168.0.1"; port = 12002; convergence = 0; laserscanner = NULL; // set angle filter angle_max = 0*PI/180; // scanner max 50 angle_min = -60*PI/180; // scanner min -60 maxmin = false; duration = false; writebt = false; writecsv = false; is_indoor = false; if (readConfig()) debugMessage(2,"config successfully readed!"); else debugMessage(2, "no config file!"); return; } // read config file int CReader::readConfig() { std::ifstream fh; std::string line; size_t pos = 0; std::string key, val; fh.open(CONFIG, std::ios::in); if (!fh.is_open()) { fh.open("config.cfg", std::ios::in); if (!fh.is_open()) { return FALSE; } } debugMessage(2, "read config..."); while (getline(fh,line)) { pos = line.find("="); key = trim(line.substr(0,pos)); val = trim(line.substr(pos+1)); try { if (key.compare("ip") == 0) { ip_adress = val; } else if (key.compare("port") == 0) { port = atoi(val.c_str()); } else if (key.compare("maxmin") == 0) { if (val.compare("true") == 0) maxmin = true; else maxmin = false; } else if (key.compare("writebt") == 0) { if (val.compare("true") == 0) writebt = true; } else if (key.compare("btpath") == 0) { bt_path = val; } else if (key.compare("convergence") == 0) { convergence = atoi(val.c_str()); } else if (key.compare("location") == 0) { if (val.compare("indoor") == 0) { is_indoor = true; } } else if (key.compare("writecsv") == 0) { if (val.compare("true") == 0) { writecsv = true; } } else if (key.compare("minangle") == 0) { angle_min = atoi(val.c_str())*PI/180.0; } else if (key.compare("maxangle") == 0) { angle_max = atoi(val.c_str())*PI/180.0; } } catch (...) { tmpstr << "unknown parameter:" << key; debugMessage(4, tmpstr.str()); } } fh.close(); return TRUE; } CReader::~CReader() { // release sensor //if (laserscanner != NULL) { // mtx_da.lock(); releaseSensor(); // mtx_da.unlock(); //} usleep(200); logfile.close(); //std::stringstream path; //path << "/home/pi/SICKRPi-Scanner/" << ss.str(); pid_t pid; if((pid = fork()) < 0) { fprintf(stderr, "Fehler... %s\n", strerror(errno)); } else if(pid == 0) { //Kindprozess "/media/usb0/" //execl("/usr/bin/sudo", "cp", "/bin/cp", path.str().c_str(), bt_path.c_str(), NULL); execl("/usr/bin/sudo", "sh", "/bin/sh", "/home/pi/SICKRPi-Scanner/tools/cpy_bin.sh", ss.str().c_str(), bt_path.c_str(), NULL); } else { // Elternprozess if (is_imu_connected) { // turn off imu leds imu_leds_off(&imu); // release ipcon imu_set_quaternion_period(&imu, 0); imu_set_angular_velocity_period(&imu, 0); imu_destroy(&imu); } ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally } //ret = execl("/usr/bin/sudo", "rm", "/bin/rm", path.str().c_str(), NULL); } // TINKERFORGE void cb_connected(uint8_t connect_reason, void *user_data) { // ...then trigger enumerate if (is_imu_connected == false) ipcon_enumerate(&ipcon); } void cb_angular_velocity(int16_t x, int16_t y, int16_t z, void *user_data) { mtx_da.lock(); is_cb_angular = true; //std::cout << y << std::endl; if (abs(x) > 50 || abs(y) > 50 || abs(z) > 50) { //std::cout << "adjust" << std::endl; //is_imu_adjustment = true; imu_set_convergence_speed(&imu, 300); usleep(1000000); imu_set_convergence_speed(&imu, 0); //is_imu_adjustment = false; //std::cout << "adjust finished" << std::endl; } else { //std::cout << "b" << std::endl; imu_set_convergence_speed(&imu, 0); //is_imu_adjustment = false; } is_cb_angular = false; mtx_da.unlock(); return; } // print incoming enumeration information void cb_enumerate(const char *uid, const char *connected_uid, char position, uint8_t hardware_version[3], uint8_t firmware_version[3], uint16_t device_identifier, uint8_t enumeration_type, void *user_data) { int is_indoor = *(int*)user_data; if(enumeration_type == IPCON_ENUMERATION_TYPE_DISCONNECTED) { printf("\n"); return; } // check if device is an imu if(device_identifier == IMU_DEVICE_IDENTIFIER) { tmpstr << "found IMU with UID:" << uid; debugMessage(2, tmpstr.str()); if (is_imu_connected) { debugMessage(2, "IMU already connected!"); return; } imu_create(&imu, uid, &ipcon); imu_set_convergence_speed(&imu,60); if (!is_indoor) { imu_set_angular_velocity_period(&imu, CB_AV_PERIOD); imu_register_callback(&imu, IMU_CALLBACK_ANGULAR_VELOCITY, (void *)cb_angular_velocity, NULL); } imu_leds_off(&imu); is_imu_connected = true; } } int CReader::init() { // set bounding box filter bb_x_max = 70.0; bb_x_min = 0.0; bb_y_max = 200.0; bb_y_min = -200.0; // activate both filter filter_angle = true; filter_bbox = true; // init tinkerforge ------------------------------------------------ // create IP connection ipcon_create(&ipcon); // Connect to brickd if(ipcon_connect(&ipcon, HOST, PORT) < 0) { debugMessage(4, "could not connect to brickd!"); return false; } // Register connected callback to "cb_connected" ipcon_register_callback(&ipcon, IPCON_CALLBACK_CONNECTED, (void *)cb_connected, &ipcon); // Register enumeration callback to "cb_enumerate" ipcon_register_callback(&ipcon, IPCON_CALLBACK_ENUMERATE, (void*)cb_enumerate, &is_indoor); ipcon_enumerate(&ipcon); // sleep usleep(7000000); // check if imu is connected if (!is_imu_connected) { debugMessage(4,"no IMU connected!"); return false; } // set convergence after initial stage imu_set_convergence_speed(&imu,convergence); usleep(50000); // raw data file time_t t; struct tm *ts; char buff[128]; // build filename t = time(NULL); ts = localtime(&t); strftime(buff, 80, "rawdata_%Y_%m_%d-%H_%M_%S.bin", ts); ss << "/home/pi/SICKRPi-Scanner/scans/" << buff; logfile.open(ss.str().c_str(), std::ios::out | std::ios::trunc); logfile.close(); logfile.open(ss.str().c_str(), std::ios::app | std::ios::binary | std::ios::out); // init sensor if(!initSensor()) { debugMessage(4, "couldn't connect to laserscanner!"); return false; } imu_leds_on(&imu); return true; } int CReader::initSensor() { if (!ibeo::ibeoLUX::IbeoLUX::getInstance()) { ibeo::ibeoLUX::IbeoLUX::initInstance(this->ip_adress, this->port, 1); debugMessage(4, "laserscanner searching...!"); laserscanner = ibeo::ibeoLUX::IbeoLUX::getInstance(); try { laserscanner->connect(); laserscanner->startMeasuring(); } catch (...) { debugMessage(4, "laserscanner not found!"); return false; } } if (laserscanner->getConnectionStatus()) { debugMessage(4, "laserscanner connected!"); } else { return false; } if (!laserscanner->getMeasuringStatus()) return false; laserscanner->ibeoLaserDataAvailable.connect(boost::bind(&CReader::newLaserData, this, _1)); return true; } float xAngle, yAngle, zAngle; void CReader::storeImuData() { float x, y, z, w; imu_get_quaternion(&imu, &x, &y, &z, &w); // use octomath to calc quaternion // y, z, x octomath::Quaternion q(w,x,y,z); octomath::Vector3 v(0.0,0.0,0.0); octomath::Pose6D pp(v, q); xAngle = pp.roll(); yAngle = pp.yaw(); zAngle = pp.pitch(); //xAngle = pp.roll(); //yAngle = pp.pitch(); //zAngle = pp.yaw()*-1; // invert to correct mirroring return; } void CReader::newLaserData(ibeo::ibeoLaserDataAbstractSmartPtr dat) { if (is_cb_angular) return; mtx_da.lock(); unsigned int scanpoints = dat->getNumberOfScanpoints(); short int angleTicksPerRotation = dat->getAngleTicksPerRotation(); //thread_clock::time_point start = thread_clock::now(); // get IMU data storeImuData(); logfile.write(reinterpret_cast<const char*>(&scanpoints), sizeof(scanpoints)); logfile.write(reinterpret_cast<const char*>(&xAngle), sizeof(xAngle)); logfile.write(reinterpret_cast<const char*>(&yAngle), sizeof(yAngle)); logfile.write(reinterpret_cast<const char*>(&zAngle), sizeof(zAngle)); logfile.write(reinterpret_cast<const char*>(&angleTicksPerRotation), sizeof(angleTicksPerRotation)); dat->writeAllScanPointsToBinFile(&logfile); data_av = 1; // calc delay //thread_clock::time_point stop = thread_clock::now(); //printf("| Time elapsed: %ld ms \n", duration_cast<milliseconds>(stop - start).count()); mtx_da.unlock(); return; } // get octomap data for lds server int CReader::getOctomap(char* buff) { return 0; } int CReader::writeDataBT() { return 0; } void CReader::releaseSensor() { // stop laserscanner laserscanner->stopMeasuring(); usleep(50000); laserscanner->releaseInstance(); return; } // get cpu load int CReader::getCPULoad() { int fd = 0; char buff[1024]; float load; fd = open("/proc/loadavg", O_RDONLY); if (fd < 0) return -1; read(fd,buff,sizeof(buff)-1); sscanf(buff, "%f", &load); close(fd); return (int)(load*100); } // get ram load int CReader::getRAMLoad(int* total, int* free) { FILE* fp = NULL; char buff[256]; char name[100], unit[16]; if ((fp = fopen("/proc/meminfo","r")) == NULL) { perror("no file meminfo!"); return 0; } fgets(buff, sizeof(buff), fp); sscanf(buff, "%s %d %s\n", name, total, unit); fgets(buff, sizeof(buff), fp); sscanf(buff, "%s %d %s\n", name, free, unit); //std::cout << "Total:" << *total << " Kb" << std::endl; //std::cout << "Free:" << *free << " Kb" << std::endl; //std::cout << "InUse:" << ((*total-*free)/1024) << " Mb" << std::endl; fclose(fp); return 1; }
21.717899
128
0.636746
MechLabEngineering
39faac70104bdf4137ca1f7d167af3c961ccf7d0
10,540
cpp
C++
tools/alive-worker.cpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
1
2021-11-03T02:26:36.000Z
2021-11-03T02:26:36.000Z
tools/alive-worker.cpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
3
2021-10-22T03:48:11.000Z
2021-11-03T03:39:48.000Z
tools/alive-worker.cpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
null
null
null
// Copyright (c) 2021-present The Alive2 Authors. // Distributed under the MIT license that can be found in the LICENSE file. // This program connects to a memodb-server server, gets alive.tv and // alive.interpret jobs, evaluates them, and sends the results back to the // server. You need a separate program to submit jobs to the server, or else // this program will have nothing to do. // // When a crash or timeout happens, it's important to send an error message // back to the server, so it knows not to retry the job. Alive2 doesn't have a // good way to detect or recover from crashes, so we set up some extra threads // and signal handlers to send an error result to the server when a crash or // timeout happens. We still can't recover from the crash, and we still can't // interrupt the main Alive2 thread if there's a timeout, so this program will // exit after sending the error result. // // Here's a suggested way to run this program: // // yes | parallel -n0 alive-worker http://127.0.0.1:1234 // // This command will run one alive-worker process per core. Whenever a process // exits, it will start a new one to replace it. #include "util/version.h" #include "util/worker.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include <condition_variable> #include <iostream> #include <mutex> #include <optional> #include <string> #include <thread> #include <utility> #include <vector> #include <semaphore.h> #include <signal.h> #include <unistd.h> // The server may wait 60 seconds to respond if there are no jobs available yet. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 120 #include <httplib.h> #include <jsoncons/byte_string.hpp> #include <jsoncons/json.hpp> #include <jsoncons_ext/cbor/decode_cbor.hpp> #include <jsoncons_ext/cbor/encode_cbor.hpp> using namespace util; using namespace std; using jsoncons::byte_string_arg; using jsoncons::decode_base64url; using jsoncons::encode_base64url; using jsoncons::json_array_arg; using jsoncons::json_object_arg; using jsoncons::ojson; using jsoncons::cbor::decode_cbor; using jsoncons::cbor::encode_cbor; static llvm::cl::OptionCategory alive_cmdargs("Alive2 worker options"); static llvm::cl::opt<string> opt_url(llvm::cl::Positional, llvm::cl::Required, llvm::cl::desc("<memodb server URL>"), llvm::cl::value_desc("url"), llvm::cl::cat(alive_cmdargs)); // Used by signal handler to communicate with crash handler thread. static sem_t crash_sem; static volatile sig_atomic_t crash_handler_done = 0; static std::mutex timeout_mutex; static std::condition_variable timeout_cv; static size_t timeout_millis = 0; static size_t timeout_index = 0; static bool timeout_cancelled = false; static std::mutex result_mutex; // May be empty if no result is in progress. static std::string result_uri; static std::optional<httplib::Client> session; static const httplib::Headers cbor_headers{{"Accept", "application/cbor"}}; static ojson textCIDToBinary(const llvm::StringRef &text) { if (!text.startswith("u")) { llvm::errs() << "unsupported CID: " << text << "\n"; std::exit(1); } std::vector<uint8_t> bytes{0x00}; auto result = decode_base64url(text.begin() + 1, text.end(), bytes); if (result.ec != jsoncons::conv_errc::success) { llvm::errs() << "invalid CID: " << text << "\n"; std::exit(1); } return ojson(byte_string_arg, bytes, 42); } static std::string binaryCIDToText(const ojson &cid) { std::string text = "u"; auto bytes = cid.as_byte_string_view(); if (bytes.size() == 0) { llvm::errs() << "invalid CID\n"; std::exit(1); } encode_base64url(bytes.begin() + 1, bytes.end(), text); return text; } static void checkResult(const httplib::Result &result) { if (!result) { std::cerr << "HTTP connection error: " << result.error() << '\n'; std::exit(1); } if (result->status < 200 || result->status > 299) { std::cerr << "HTTP response error: " << result->body << "\n"; std::exit(1); } }; static ojson getNodeFromCID(const ojson &cid) { std::string uri = "/cid/" + binaryCIDToText(cid); auto result = session->Get(uri.c_str(), cbor_headers); checkResult(result); if (result->get_header_value("Content-Type") != "application/cbor") { std::cerr << "unexpected Content-Type!\n"; std::exit(1); } return decode_cbor<ojson>(result->body); }; static ojson putNode(const ojson &node) { std::string buffer; encode_cbor(node, buffer); auto result = session->Post("/cid", cbor_headers, buffer, "application/cbor"); checkResult(result); string cid_str = result->get_header_value("Location"); if (!llvm::StringRef(cid_str).startswith("/cid/")) { llvm::errs() << "invalid CID URI!\n"; std::exit(1); } return textCIDToBinary(llvm::StringRef(cid_str).drop_front(5)); } static void sendResult(const ojson &node) { std::lock_guard lock(result_mutex); if (result_uri.empty()) return; auto cid = putNode(node); std::string buffer; encode_cbor(cid, buffer); auto result = session->Put(result_uri.c_str(), cbor_headers, buffer, "application/cbor"); checkResult(result); result_uri.clear(); } // Must be signal-safe. static void signalHandler(void *) { // Resume the signal handler thread. sem_post(&crash_sem); // Wait up to 10 seconds for the thread to send a result. for (int i = 0; i < 10; ++i) { if (crash_handler_done) break; sleep(1); } // Return and let LLVM's normal signal handlers run. } static void crashHandlerThread() { // Don't handle any signals in this thread. sigset_t sig_set; sigfillset(&sig_set); pthread_sigmask(SIG_BLOCK, &sig_set, nullptr); // Wait for signalHandler() to tell us a signal has been raised. while (sem_wait(&crash_sem)) ; std::cerr << "crashed\n"; sendResult(ojson(json_object_arg, {{"status", "crashed"}})); // Tell signalHandler() we're done. crash_handler_done = 1; } static void timeoutThread() { std::unique_lock<std::mutex> lock(timeout_mutex); while (true) { auto expected_millis = timeout_millis; auto expected_index = timeout_index; if (!expected_millis) { timeout_cv.wait(lock); } else { // If timeout_millis or timeout_index changes while we're waiting, the // job completed before the timeout. But if they don't change for // duration, the job hasn't completed yet. auto duration = std::chrono::milliseconds(expected_millis); auto predicate = [&] { return timeout_millis != expected_millis || timeout_index != expected_index || timeout_cancelled; }; if (!timeout_cv.wait_for(lock, duration, predicate)) break; // Timeout occurred! (or cancelled) } if (timeout_cancelled) return; } sendResult(ojson(json_object_arg, {{"status", "timeout"}})); // We can't call exit() because that would destroy the global SMT context // while another thread might be using it. _exit(2); } static void exitHandler() { // We need to cancel the timeout mutex so it stops waiting on timeout_cv. The // timeout_cv variable will be destroyed when the program exits, and it's // illegal to destroy a condition variable that has threads waiting on it. std::lock_guard lock(timeout_mutex); timeout_cancelled = true; timeout_cv.notify_all(); } int main(int argc, char **argv) { // Register our signal handler before LLVM's stack trace printer, so our // handler will run first. sem_init(&crash_sem, 0, 0); llvm::sys::AddSignalHandler(signalHandler, nullptr); // Start our threads before calling anything else from LLVM, in case LLVM's // functions crash. atexit(exitHandler); std::thread(crashHandlerThread).detach(); std::thread(timeoutThread).detach(); llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); llvm::PrettyStackTraceProgram X(argc, argv); llvm::EnableDebugBuffering = true; llvm::llvm_shutdown_obj llvm_shutdown; // Call llvm_shutdown() on exit. std::string Usage = R"EOF(Alive2 stand-alone distributed worker: version )EOF"; Usage += alive_version; Usage += R"EOF( see alive-worker --version for LLVM version info, This program connects to a memodb-server server and evaluates Alive2-related calls that are submitted to the server by other programs. )EOF"; llvm::cl::HideUnrelatedOptions(alive_cmdargs); llvm::cl::ParseCommandLineOptions(argc, argv, Usage); std::string server_url = opt_url; // httplib doesn't like the ending slash in http://127.0.0.1:1234/ if (!server_url.empty() && server_url.back() == '/') server_url.pop_back(); session.emplace(server_url); // Upload the list of funcs we can evaluate using POST /cid. ojson worker_info( json_object_arg, { {"funcs", ojson(json_array_arg, {"alive.tv_v2", "alive.interpret"})}, }); auto worker_info_cid = putNode(worker_info); while (true) { std::string buffer; encode_cbor(worker_info_cid, buffer); auto response = session->Post("/worker", cbor_headers, buffer, "application/cbor"); checkResult(response); if (response->get_header_value("Content-Type") != "application/cbor") { std::cerr << "unexpected Content-Type!\n"; return 1; } ojson job = decode_cbor<ojson>(response->body); if (job.is_null()) { // No jobs available, try again. sleep(1); // TODO: exponential backoff continue; } string func = job["func"].as<string>(); std::string call_uri = "/call/" + func + "/"; for (ojson &arg : job["args"].array_range()) { call_uri += binaryCIDToText(arg) + ","; arg = getNodeFromCID(arg); } call_uri.pop_back(); // remove last comma llvm::errs() << "evaluating " << call_uri << "\n"; std::unique_lock lock(result_mutex); result_uri = call_uri; lock.unlock(); uint64_t timeout = job["args"][0].get_with_default<uint64_t>("timeout", 60000); lock = unique_lock(timeout_mutex); timeout_millis = timeout; timeout_index++; lock.unlock(); timeout_cv.notify_one(); ojson result = evaluateAliveFunc(job); if (result.contains("test_input")) result["test_input"] = putNode(result["test_input"]); lock.lock(); timeout_millis = 0; lock.unlock(); timeout_cv.notify_one(); sendResult(result); } return 0; }
31.8429
80
0.681879
yotann
39fb491fd6f308f2fc4e92febae3038da1953a38
11,209
cpp
C++
src/engine/job_system.cpp
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
src/engine/job_system.cpp
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
src/engine/job_system.cpp
nemerle/LumixEngine
6cfee07c4268c15994c7171cb5625179b1f369e2
[ "MIT" ]
null
null
null
#include "engine/atomic.h" #include "engine/array.h" #include "engine/engine.h" #include "engine/fibers.h" #include "engine/allocator.h" #include "engine/log.h" #include "engine/math.h" #include "engine/os.h" #include "engine/sync.h" #include "engine/thread.h" #include "engine/profiler.h" #include "job_system.h" namespace Lumix::jobs { struct Job { void (*task)(void*) = nullptr; void* data = nullptr; Signal* dec_on_finish; u8 worker_index; }; struct WorkerTask; struct FiberDecl { int idx; Fiber::Handle fiber = Fiber::INVALID_FIBER; Job current_job; }; #ifdef _WIN32 static void __stdcall manage(void* data); #else static void manage(void* data); #endif struct System { System(IAllocator& allocator) : m_allocator(allocator) , m_workers(allocator) , m_job_queue(allocator) , m_ready_fibers(allocator) , m_free_fibers(allocator) , m_backup_workers(allocator) {} Lumix::Mutex m_sync; Lumix::Mutex m_job_queue_sync; Array<WorkerTask*> m_workers; Array<WorkerTask*> m_backup_workers; Array<Job> m_job_queue; FiberDecl m_fiber_pool[512]; Array<FiberDecl*> m_free_fibers; Array<FiberDecl*> m_ready_fibers; IAllocator& m_allocator; }; static Local<System> g_system; static volatile i32 g_generation = 0; static thread_local WorkerTask* g_worker = nullptr; #pragma optimize( "", off ) WorkerTask* getWorker() { return g_worker; } #pragma optimize( "", on ) struct WorkerTask : Thread { WorkerTask(System& system, u8 worker_index) : Thread(system.m_allocator) , m_system(system) , m_worker_index(worker_index) , m_job_queue(system.m_allocator) , m_ready_fibers(system.m_allocator) { } int task() override { profiler::showInProfiler(true); g_worker = this; Fiber::initThread(start, &m_primary_fiber); return 0; } #ifdef _WIN32 static void __stdcall start(void* data) #else static void start(void* data) #endif { g_system->m_sync.enter(); FiberDecl* fiber = g_system->m_free_fibers.back(); g_system->m_free_fibers.pop(); if (!Fiber::isValid(fiber->fiber)) { fiber->fiber = Fiber::create(64 * 1024, manage, fiber); } getWorker()->m_current_fiber = fiber; Fiber::switchTo(&getWorker()->m_primary_fiber, fiber->fiber); } bool m_finished = false; FiberDecl* m_current_fiber = nullptr; Fiber::Handle m_primary_fiber; System& m_system; Array<Job> m_job_queue; Array<FiberDecl*> m_ready_fibers; u8 m_worker_index; bool m_is_enabled = false; bool m_is_backup = false; }; struct Waitor { Waitor* next; FiberDecl* fiber; }; template <bool ZERO> LUMIX_FORCE_INLINE static bool trigger(Signal* signal) { Waitor* waitor; { Lumix::MutexGuard lock(g_system->m_sync); if constexpr (ZERO) { signal->counter = 0; } else { --signal->counter; ASSERT(signal->counter >= 0); if (signal->counter > 0) return false; } waitor = signal->waitor; signal->waitor = nullptr; } if (!waitor) return false; bool wake_all = false; { Lumix::MutexGuard queue_lock(g_system->m_job_queue_sync); while (waitor) { Waitor* next = waitor->next; const u8 worker = waitor->fiber->current_job.worker_index; if (worker == ANY_WORKER) { g_system->m_ready_fibers.push(waitor->fiber); wake_all = true; } else { WorkerTask* worker = g_system->m_workers[waitor->fiber->current_job.worker_index % g_system->m_workers.size()]; worker->m_ready_fibers.push(waitor->fiber); if(!wake_all) worker->wakeup(); } waitor = next; } } if (wake_all) { for (WorkerTask* worker : g_system->m_backup_workers) { if (worker->m_is_enabled) worker->wakeup(); } for (WorkerTask* worker : g_system->m_workers) { worker->wakeup(); } } return true; } void enableBackupWorker(bool enable) { Lumix::MutexGuard lock(g_system->m_sync); for (WorkerTask* task : g_system->m_backup_workers) { if (task->m_is_enabled != enable) { task->m_is_enabled = enable; return; } } ASSERT(enable); WorkerTask* task = LUMIX_NEW(g_system->m_allocator, WorkerTask)(*g_system, 0xff); if (task->create("Backup worker", false)) { g_system->m_backup_workers.push(task); task->m_is_enabled = true; task->m_is_backup = true; } else { logError("Job system backup worker failed to initialize."); LUMIX_DELETE(g_system->m_allocator, task); } } LUMIX_FORCE_INLINE static bool setRedEx(Signal* signal) { ASSERT(signal); ASSERT(signal->counter <= 1); bool res = compareAndExchange(&signal->counter, 1, 0); if (res) { signal->generation = atomicIncrement(&g_generation); } return res; } void setRed(Signal* signal) { setRedEx(signal); } void setGreen(Signal* signal) { ASSERT(signal); ASSERT(signal->counter <= 1); const u32 gen = signal->generation; if (trigger<true>(signal)){ profiler::signalTriggered(gen); } } void run(void* data, void(*task)(void*), Signal* on_finished) { runEx(data, task, on_finished, ANY_WORKER); } void runEx(void* data, void(*task)(void*), Signal* on_finished, u8 worker_index) { Job job; job.data = data; job.task = task; job.worker_index = worker_index != ANY_WORKER ? worker_index % getWorkersCount() : worker_index; job.dec_on_finish = on_finished; if (on_finished) { Lumix::MutexGuard guard(g_system->m_sync); ++on_finished->counter; if (on_finished->counter == 1) { on_finished->generation = atomicIncrement(&g_generation); } } if (worker_index != ANY_WORKER) { WorkerTask* worker = g_system->m_workers[worker_index % g_system->m_workers.size()]; { Lumix::MutexGuard lock(g_system->m_job_queue_sync); worker->m_job_queue.push(job); } worker->wakeup(); return; } { Lumix::MutexGuard lock(g_system->m_job_queue_sync); g_system->m_job_queue.push(job); } for (WorkerTask* worker : g_system->m_workers) { worker->wakeup(); } for (WorkerTask* worker : g_system->m_backup_workers) { if (worker->m_is_enabled) worker->wakeup(); } } #ifdef _WIN32 static void __stdcall manage(void* data) #else static void manage(void* data) #endif { g_system->m_sync.exit(); FiberDecl* this_fiber = (FiberDecl*)data; WorkerTask* worker = getWorker(); while (!worker->m_finished) { if (worker->m_is_backup) { Lumix::MutexGuard guard(g_system->m_sync); while (!worker->m_is_enabled && !worker->m_finished) { PROFILE_BLOCK("disabled"); profiler::blockColor(0xff, 0, 0xff); worker->sleep(g_system->m_sync); } } FiberDecl* fiber = nullptr; Job job; while (!worker->m_finished) { Lumix::MutexGuard lock(g_system->m_job_queue_sync); if (!worker->m_ready_fibers.empty()) { fiber = worker->m_ready_fibers.back(); worker->m_ready_fibers.pop(); break; } if (!worker->m_job_queue.empty()) { job = worker->m_job_queue.back(); worker->m_job_queue.pop(); break; } if (!g_system->m_ready_fibers.empty()) { fiber = g_system->m_ready_fibers.back(); g_system->m_ready_fibers.pop(); break; } if(!g_system->m_job_queue.empty()) { job = g_system->m_job_queue.back(); g_system->m_job_queue.pop(); break; } PROFILE_BLOCK("sleeping"); profiler::blockColor(0x30, 0x30, 0x30); worker->sleep(g_system->m_job_queue_sync); if (worker->m_is_backup) break; } if (worker->m_finished) break; if (fiber) { worker->m_current_fiber = fiber; g_system->m_sync.enter(); g_system->m_free_fibers.push(this_fiber); Fiber::switchTo(&this_fiber->fiber, fiber->fiber); g_system->m_sync.exit(); worker = getWorker(); worker->m_current_fiber = this_fiber; } else { if (!job.task) continue; profiler::beginBlock("job"); profiler::blockColor(0x60, 0x60, 0x60); if (job.dec_on_finish) { profiler::pushJobInfo(job.dec_on_finish->generation); } this_fiber->current_job = job; job.task(job.data); this_fiber->current_job.task = nullptr; if (job.dec_on_finish) { trigger<false>(job.dec_on_finish); } worker = getWorker(); profiler::endBlock(); } } Fiber::switchTo(&this_fiber->fiber, getWorker()->m_primary_fiber); } bool init(u8 workers_count, IAllocator& allocator) { g_system.create(allocator); g_system->m_free_fibers.reserve(lengthOf(g_system->m_fiber_pool)); for (FiberDecl& fiber : g_system->m_fiber_pool) { g_system->m_free_fibers.push(&fiber); } const int fiber_num = lengthOf(g_system->m_fiber_pool); for(int i = 0; i < fiber_num; ++i) { FiberDecl& decl = g_system->m_fiber_pool[i]; decl.idx = i; } int count = maximum(1, int(workers_count)); for (int i = 0; i < count; ++i) { WorkerTask* task = LUMIX_NEW(allocator, WorkerTask)(*g_system, i < 64 ? u64(1) << i : 0); if (task->create("Worker", false)) { task->m_is_enabled = true; g_system->m_workers.push(task); task->setAffinityMask((u64)1 << i); } else { logError("Job system worker failed to initialize."); LUMIX_DELETE(allocator, task); } } return !g_system->m_workers.empty(); } u8 getWorkersCount() { const int c = g_system->m_workers.size(); ASSERT(c <= 0xff); return (u8)c; } IAllocator& getAllocator() { return g_system->m_allocator; } void shutdown() { IAllocator& allocator = g_system->m_allocator; for (Thread* task : g_system->m_workers) { WorkerTask* wt = (WorkerTask*)task; wt->m_finished = true; } for (Thread* task : g_system->m_backup_workers) { WorkerTask* wt = (WorkerTask*)task; wt->m_finished = true; wt->wakeup(); } for (Thread* task : g_system->m_backup_workers) { while (!task->isFinished()) task->wakeup(); task->destroy(); LUMIX_DELETE(allocator, task); } for (WorkerTask* task : g_system->m_workers) { while (!task->isFinished()) task->wakeup(); task->destroy(); LUMIX_DELETE(allocator, task); } for (FiberDecl& fiber : g_system->m_fiber_pool) { if(Fiber::isValid(fiber.fiber)) { Fiber::destroy(fiber.fiber); } } g_system.destroy(); } static void waitEx(Signal* signal, bool is_mutex) { ASSERT(signal); if (signal->counter == 0) return; g_system->m_sync.enter(); if (signal->counter == 0) { g_system->m_sync.exit(); return; } if (!getWorker()) { while (signal->counter > 0) { g_system->m_sync.exit(); os::sleep(1); g_system->m_sync.enter(); } g_system->m_sync.exit(); return; } FiberDecl* this_fiber = getWorker()->m_current_fiber; Waitor waitor; waitor.fiber = this_fiber; waitor.next = signal->waitor; signal->waitor = &waitor; const profiler::FiberSwitchData& switch_data = profiler::beginFiberWait(signal->generation, is_mutex); FiberDecl* new_fiber = g_system->m_free_fibers.back(); g_system->m_free_fibers.pop(); if (!Fiber::isValid(new_fiber->fiber)) { new_fiber->fiber = Fiber::create(64 * 1024, manage, new_fiber); } getWorker()->m_current_fiber = new_fiber; Fiber::switchTo(&this_fiber->fiber, new_fiber->fiber); getWorker()->m_current_fiber = this_fiber; g_system->m_sync.exit(); profiler::endFiberWait(switch_data); } void enter(Mutex* mutex) { ASSERT(getWorker()); for (;;) { for (u32 i = 0; i < 400; ++i) { if (setRedEx(&mutex->signal)) return; } waitEx(&mutex->signal, true); } } void exit(Mutex* mutex) { ASSERT(getWorker()); setGreen(&mutex->signal); } void wait(Signal* handle) { waitEx(handle, false); } } // namespace Lumix::jobs
22.328685
115
0.686323
nemerle
39fc8b02a547193c70cf3a351b0c8f934e67566e
2,434
cpp
C++
lib/WebServer/WebServer.cpp
sidoh/esp8266_pin_server
31912034f660a9e174876aef7c3aa250f1674a9a
[ "MIT" ]
2
2019-02-18T01:01:29.000Z
2019-04-22T12:28:04.000Z
lib/WebServer/WebServer.cpp
sidoh/esp8266_pin_server
31912034f660a9e174876aef7c3aa250f1674a9a
[ "MIT" ]
1
2018-01-04T22:14:25.000Z
2018-01-06T19:17:12.000Z
lib/WebServer/WebServer.cpp
sidoh/esp8266_pin_server
31912034f660a9e174876aef7c3aa250f1674a9a
[ "MIT" ]
null
null
null
#include <PinHandler.h> #include <Settings.h> #include <WebServer.h> #include <FS.h> using namespace std::placeholders; WebServer::WebServer(Settings& settings, PinHandler& pinHandler) : settings(settings) , authProvider(settings) , server(80, authProvider) , pinHandler(pinHandler) { } void WebServer::begin() { server .buildHandler("/pin/:pin") .on(HTTP_GET, std::bind(&WebServer::handleGetPin, this, _1)) .on(HTTP_PUT, std::bind(&WebServer::handlePutPin, this, _1)); server .buildHandler("/settings") .on(HTTP_GET, std::bind(&WebServer::handleGetSettings, this, _1)) .on(HTTP_PUT, std::bind(&WebServer::handlePutSettings, this, _1)); server .buildHandler("/about") .on(HTTP_GET, std::bind(&WebServer::handleAbout, this, _1)); server .buildHandler("/firmware") .handleOTA(); } void WebServer::handleClient() { server.handleClient(); } void WebServer::handleAbout(RequestContext& request) { // Measure before allocating buffers uint32_t freeHeap = ESP.getFreeHeap(); JsonObject res = request.response.json.to<JsonObject>(); res["version"] = QUOTE(FIRMWARE_VERSION); res["variant"] = QUOTE(FIRMWARE_VARIANT); res["signal_strength"] = WiFi.RSSI(); res["free_heap"] = freeHeap; res["sdk_version"] = ESP.getSdkVersion(); } void WebServer::handleGetPin(RequestContext& request) { uint8_t pinId = atoi(request.pathVariables.get("pin")); JsonObject pin = request.response.json.createNestedObject("pin"); pin["value"] = digitalRead(pinId); } void WebServer::handlePutPin(RequestContext& request) { JsonObject body = request.getJsonBody().as<JsonObject>(); uint8_t pin = atoi(request.pathVariables.get("pin")); pinMode(pin, OUTPUT); pinHandler.handle(pin, body); handleGetPin(request); } void WebServer::handleGetSettings(RequestContext& request) { const char* file = SETTINGS_FILE; if (SPIFFS.exists(file)) { File f = SPIFFS.open(file, "r"); server.streamFile(f, "application/json"); f.close(); } else { request.response.json["error"] = F("Settings file not stored on SPIFFS. This is an unexpected error!"); request.response.setCode(500); } } void WebServer::handlePutSettings(RequestContext& request) { JsonObject newSettings = request.getJsonBody().as<JsonObject>(); settings.patch(newSettings); settings.save(); // just re-serve settings file handleGetSettings(request); ESP.restart(); }
26.747253
108
0.703369
sidoh
39feac86d433c898a5ebe6884160056bccfcb72b
685
cpp
C++
Pairs.cpp
nateshmbhat/Hackerrank
5ff65e8cb82da6c15cf068450cae503d2fb02952
[ "MIT" ]
null
null
null
Pairs.cpp
nateshmbhat/Hackerrank
5ff65e8cb82da6c15cf068450cae503d2fb02952
[ "MIT" ]
null
null
null
Pairs.cpp
nateshmbhat/Hackerrank
5ff65e8cb82da6c15cf068450cae503d2fb02952
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int pairs(int k, vector <int> arr) { // Complete this function int diff , count = 0 ,i=0 , j =1 ; while(i<=j && j<=arr.size()) { diff = arr[j]-arr[i] ; if(diff<k) j++ ; else if(diff>k) i++ ; else { count++ ; i++ ; } } return count; } int main() { int n; int k , temp , i ; cin >> n >> k; vector<int> arr(n); for(int arr_i = 0; arr_i < n; arr_i++){ cin >>arr[arr_i] ; } sort(arr.begin() , arr.end() ) ; int result = pairs(k, arr); cout << result << endl; return 0; }
17.564103
43
0.424818
nateshmbhat
260a596df97a0373c60f2a6b819b0d7762acd37c
460
hpp
C++
src/graphics/renderers/terrain_renderer.hpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/renderers/terrain_renderer.hpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/renderers/terrain_renderer.hpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
1
2021-03-02T16:54:40.000Z
2021-03-02T16:54:40.000Z
#pragma once // Local Headers #include "renderer.hpp" #include "common/planet.hpp" #include "graphics/shader.hpp" #include "graphics/texture.hpp" #include "graphics/texture_array.hpp" class TerrainRenderer: public Renderer { private: SharedTexture grass; //, ground, rock, sand, snow; SharedTexArray terrainTextures; void applyUniforms(Shader & shader); public: TerrainRenderer(); void render(double dt); };
23
58
0.686957
alexkafer
260b82ff984fb3982bf266d67275f4a12127f6ef
7,821
cc
C++
DED/i3-old/test.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
4
2015-06-12T05:08:56.000Z
2017-11-13T11:34:27.000Z
DED/i3-old/test.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
null
null
null
DED/i3-old/test.cc
flipk/pfkutils
d8f6c22720b6fcc44a882927c745a822282d1f69
[ "Unlicense" ]
1
2021-10-20T02:04:53.000Z
2021-10-20T02:04:53.000Z
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> */ #include "libprotossl.h" #include "protossl_test-libprotossl_test_proto.pb.h" #include "posix_fe.h" #include <unistd.h> using namespace ProtoSSL; using namespace PFK::Test; void timeval_to_PingInfo(PingInfo &pi, const pxfe_timeval &tv) { pi.set_time_seconds(tv.tv_sec); pi.set_time_useconds(tv.tv_usec); } void PingInfo_to_timeval(pxfe_timeval &tv, const PingInfo &pi) { tv.tv_sec = pi.time_seconds(); tv.tv_usec = pi.time_useconds(); } // // server // class myConnServer : public ProtoSSLConn<ClientToServer, ServerToClient> { public: myConnServer(void) { printf("myConnServer::myConnServer\n"); } ~myConnServer(void) { printf("myConnServer::~myConnServer\n"); } void handleConnect(void) { printf("myConnServer::handleConnect\n"); outMessage().set_type(STC_PROTO_VERSION); outMessage().mutable_proto_version()->set_app_name("LIBPROTOSSL_TEST"); outMessage().mutable_proto_version()->set_version(PROTOCOL_VERSION_3); sendMessage(); } void handleDisconnect(void) { printf("myConnClient::handleDisconnect\n"); } bool messageHandler(const ClientToServer &inMsg) { switch (inMsg.type()) { case CTS_PROTO_VERSION: printf("server got proto app %s version %d from client\n", inMsg.proto_version().app_name().c_str(), inMsg.proto_version().version()); break; case CTS_PING: { pxfe_timeval ts; uint32_t seq = inMsg.ping().seq(); PingInfo_to_timeval(ts, inMsg.ping()); outMessage().set_type(STC_PING_ACK); outMessage().mutable_ping()->set_seq(seq); timeval_to_PingInfo(*outMessage().mutable_ping(),ts); sendMessage(); break; } default: printf("server got unknown message %d\n", inMsg.type()); } return true; } }; class myFactoryServer : public ProtoSSLConnFactory { public: myFactoryServer(void) { } ~myFactoryServer(void) { } _ProtoSSLConn * newConnection(void) { return new myConnServer; } }; // // client // class myConnClient : public ProtoSSLConn<ServerToClient, ClientToServer> { public: myConnClient(void) { printf("myConnClient::myConnClient\n"); } ~myConnClient(void) { printf("myConnClient::~myConnClient\n"); } void handleConnect(void) { printf("myConnClient::handleConnect\n"); outMessage().set_type(CTS_PROTO_VERSION); outMessage().mutable_proto_version()->set_app_name("LIBPROTOSSL_TEST"); outMessage().mutable_proto_version()->set_version(PROTOCOL_VERSION_3); sendMessage(); } void handleDisconnect(void) { printf("myConnClient::handleDisconnect\n"); } bool messageHandler(const ServerToClient &inMsg) { bool done = false; switch (inMsg.type()) { case STC_PROTO_VERSION: { pxfe_timeval now; printf("client got proto app %s version %d from server\n", inMsg.proto_version().app_name().c_str(), inMsg.proto_version().version()); now.getNow(); outMessage().set_type(CTS_PING); outMessage().mutable_ping()->set_seq(1); timeval_to_PingInfo(*outMessage().mutable_ping(), now); sendMessage(); break; } case STC_PING_ACK: { pxfe_timeval ts, now, diff; uint32_t seq = inMsg.ping().seq(); now.getNow(); PingInfo_to_timeval(ts, inMsg.ping()); diff = now - ts; printf("client got PING_ACK seq %d delay %u.%06u\n", seq, (unsigned int) diff.tv_sec, (unsigned int) diff.tv_usec); if (seq < 10) { outMessage().set_type(CTS_PING); outMessage().mutable_ping()->set_seq(seq+1); timeval_to_PingInfo(*outMessage().mutable_ping(), now); sendMessage(); } else { printf("successful test\n"); stopMsgs(); done = true; } break; } default: printf("client got unknown message %d\n", inMsg.type()); } return !done; } }; class myFactoryClient : public ProtoSSLConnFactory { public: myFactoryClient(void) { } ~myFactoryClient(void) { } _ProtoSSLConn * newConnection(void) { return new myConnClient; } }; // // main // int main(int argc, char ** argv) { std::string cert_ca = "file:keys/Root-CA.crt"; std::string cert_server = "file:keys/Server-Cert.crt"; std::string key_server = "file:keys/Server-Cert-encrypted.key"; std::string key_pwd_server = "0KZ7QMalU75s0IXoWnhm3BXEtswirfwrXwwNiF6c"; std::string commonname_server = "Server Cert"; std::string cert_client = "file:keys/Client-Cert.crt"; std::string key_client = "file:keys/Client-Cert-encrypted.key"; std::string key_pwd_client = "IgiLNFWx3fTMioJycI8qXCep8j091yfHOwsBbo6f"; std::string commonname_client = "Client Cert"; if (argc < 2) { return 1; } std::string argv1(argv[1]); ProtoSSLMsgs msgs(/*debugFlag*/true); if (argv1 == "s") { ProtoSSLCertParams certs(cert_ca, cert_server, key_server, key_pwd_server, commonname_client); myFactoryServer fact; if (msgs.loadCertificates(certs) == false) return 1; msgs.startServer(fact, 2005); while (msgs.run()) ; } else if (argv1 == "c") { if (argc != 3) { printf("specify ip address of server\n"); return 2; } ProtoSSLCertParams certs(cert_ca, cert_client, key_client, key_pwd_client, commonname_server); myFactoryClient fact; if (msgs.loadCertificates(certs) == false) return 1; msgs.startClient(fact, argv[2], 2005); while (msgs.run()) ; } else { return 2; } return 0; }
29.513208
79
0.588927
flipk
260baed23247e7fdc04a28da812ef4d91946fa20
1,354
hpp
C++
app/src/main/cpp/graphics/resources/base.hpp
ktzevani/native-camera-vulkan
b9c03c956f8e9c2bda05ae31060d09518fd5790b
[ "Apache-2.0" ]
10
2021-06-06T15:30:05.000Z
2022-03-20T09:48:18.000Z
app/src/main/cpp/graphics/resources/base.hpp
ktzevani/native-camera-vulkan
b9c03c956f8e9c2bda05ae31060d09518fd5790b
[ "Apache-2.0" ]
1
2021-09-23T08:44:50.000Z
2021-09-23T08:44:50.000Z
app/src/main/cpp/graphics/resources/base.hpp
ktzevani/native-camera-vulkan
b9c03c956f8e9c2bda05ae31060d09518fd5790b
[ "Apache-2.0" ]
2
2021-08-09T07:50:10.000Z
2021-12-31T13:51:53.000Z
/* * Copyright 2020 Konstantinos Tzevanidis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef NCV_RESOURCES_BASE_HPP #define NCV_RESOURCES_BASE_HPP #include <vulkan_hpp/vulkan.hpp> namespace graphics{ namespace resources{ class base { public: enum class memory_location { device, host, external }; base(const vk::PhysicalDevice& a_gpu, const vk::UniqueDevice& a_device); size_t data_size() { return m_data_size; } protected: int get_memory_index(uint32_t a_memory_type_bits, memory_location a_location) noexcept; vk::Device m_device = nullptr; vk::PhysicalDeviceMemoryProperties m_mem_props; size_t m_data_size = 0; vk::DeviceSize m_size = 0; }; }} #endif //NCV_RESOURCES_BASE_HPP
25.54717
95
0.687592
ktzevani
260cb79404b9b57eecb28e6a5c2b65e36e695a54
49,193
cpp
C++
cppcrypto/whirlpool.cpp
crashdemons/kerukuro-cppcrypto
090d0e97280c0c34267ab50b72a2ffa5b991110b
[ "BSD-2-Clause" ]
null
null
null
cppcrypto/whirlpool.cpp
crashdemons/kerukuro-cppcrypto
090d0e97280c0c34267ab50b72a2ffa5b991110b
[ "BSD-2-Clause" ]
null
null
null
cppcrypto/whirlpool.cpp
crashdemons/kerukuro-cppcrypto
090d0e97280c0c34267ab50b72a2ffa5b991110b
[ "BSD-2-Clause" ]
null
null
null
/* This code is written by kerukuro for cppcrypto library (http://cppcrypto.sourceforge.net/) and released into public domain. */ #include "cpuinfo.h" #include "whirlpool.h" #include "portability.h" #include <functional> #include <memory.h> //#define CPPCRYPTO_DEBUG extern "C" { #ifndef _M_X64 void whirlpool_compress_asm(unsigned char state[64], const unsigned char block[64]); #endif } namespace cppcrypto { static const uint64_t RC[10] = { 0x4f01b887e8c62318, 0x52916f79f5d2a636, 0x357b0ca38e9bbc60, 0x57fe4b2ec2d7e01d, 0xda4af09fe5377715, 0x856ba0b10a29c958, 0x67053ecbf4105dbd, 0xd8957da78b4127e4, 0x9e4717dd667ceefb, 0x33835aad07bf2dca }; static const uint64_t T[8][256] = { { 0xd83078c018601818, 0x2646af05238c2323, 0xb891f97ec63fc6c6, 0xfbcd6f13e887e8e8, 0xcb13a14c87268787, 0x116d62a9b8dab8b8, 0x0902050801040101, 0x0d9e6e424f214f4f, 0x9b6ceead36d83636, 0xff510459a6a2a6a6, 0x0cb9bdded26fd2d2, 0x0ef706fbf5f3f5f5, 0x96f280ef79f97979, 0x30dece5f6fa16f6f, 0x6d3feffc917e9191, 0xf8a407aa52555252, 0x47c0fd27609d6060, 0x35657689bccabcbc, 0x372bcdac9b569b9b, 0x8a018c048e028e8e, 0xd25b1571a3b6a3a3, 0x6c183c600c300c0c, 0x84f68aff7bf17b7b, 0x806ae1b535d43535, 0xf53a69e81d741d1d, 0xb3dd4753e0a7e0e0, 0x21b3acf6d77bd7d7, 0x9c99ed5ec22fc2c2, 0x435c966d2eb82e2e, 0x29967a624b314b4b, 0x5de121a3fedffefe, 0xd5ae168257415757, 0xbd2a41a815541515, 0xe8eeb69f77c17777, 0x926eeba537dc3737, 0x9ed7567be5b3e5e5, 0x1323d98c9f469f9f, 0x23fd17d3f0e7f0f0, 0x20947f6a4a354a4a, 0x44a9959eda4fdada, 0xa2b025fa587d5858, 0xcf8fca06c903c9c9, 0x7c528d5529a42929, 0x5a1422500a280a0a, 0x507f4fe1b1feb1b1, 0xc95d1a69a0baa0a0, 0x14d6da7f6bb16b6b, 0xd917ab5c852e8585, 0x3c677381bdcebdbd, 0x8fba34d25d695d5d, 0x9020508010401010, 0x07f503f3f4f7f4f4, 0xdd8bc016cb0bcbcb, 0xd37cc6ed3ef83e3e, 0x2d0a112805140505, 0x78cee61f67816767, 0x97d55373e4b7e4e4, 0x024ebb25279c2727, 0x7382583241194141, 0xa70b9d2c8b168b8b, 0xf6530151a7a6a7a7, 0xb2fa94cf7de97d7d, 0x4937fbdc956e9595, 0x56ad9f8ed847d8d8, 0x70eb308bfbcbfbfb, 0xcdc17123ee9feeee, 0xbbf891c77ced7c7c, 0x71cce31766856666, 0x7ba78ea6dd53dddd, 0xaf2e4bb8175c1717, 0x458e460247014747, 0x1a21dc849e429e9e, 0xd489c51eca0fcaca, 0x585a99752db42d2d, 0x2e637991bfc6bfbf, 0x3f0e1b38071c0707, 0xac472301ad8eadad, 0xb0b42fea5a755a5a, 0xef1bb56c83368383, 0xb666ff8533cc3333, 0x5cc6f23f63916363, 0x12040a1002080202, 0x93493839aa92aaaa, 0xdee2a8af71d97171, 0xc68dcf0ec807c8c8, 0xd1327dc819641919, 0x3b92707249394949, 0x5faf9a86d943d9d9, 0x31f91dc3f2eff2f2, 0xa8db484be3abe3e3, 0xb9b62ae25b715b5b, 0xbc0d9234881a8888, 0x3e29c8a49a529a9a, 0x0b4cbe2d26982626, 0xbf64fa8d32c83232, 0x597d4ae9b0fab0b0, 0xf2cf6a1be983e9e9, 0x771e33780f3c0f0f, 0x33b7a6e6d573d5d5, 0xf41dba74803a8080, 0x27617c99bec2bebe, 0xeb87de26cd13cdcd, 0x8968e4bd34d03434, 0x3290757a483d4848, 0x54e324abffdbffff, 0x8df48ff77af57a7a, 0x643deaf4907a9090, 0x9dbe3ec25f615f5f, 0x3d40a01d20802020, 0x0fd0d56768bd6868, 0xca3472d01a681a1a, 0xb7412c19ae82aeae, 0x7d755ec9b4eab4b4, 0xcea8199a544d5454, 0x7f3be5ec93769393, 0x2f44aa0d22882222, 0x63c8e907648d6464, 0x2aff12dbf1e3f1f1, 0xcce6a2bf73d17373, 0x82245a9012481212, 0x7a805d3a401d4040, 0x4810284008200808, 0x959be856c32bc3c3, 0xdfc57b33ec97ecec, 0x4dab9096db4bdbdb, 0xc05f1f61a1bea1a1, 0x9107831c8d0e8d8d, 0xc87ac9f53df43d3d, 0x5b33f1cc97669797, 0x0000000000000000, 0xf983d436cf1bcfcf, 0x6e5687452bac2b2b, 0xe1ecb39776c57676, 0xe619b06482328282, 0x28b1a9fed67fd6d6, 0xc33677d81b6c1b1b, 0x74775bc1b5eeb5b5, 0xbe432911af86afaf, 0x1dd4df776ab56a6a, 0xeaa00dba505d5050, 0x578a4c1245094545, 0x38fb18cbf3ebf3f3, 0xad60f09d30c03030, 0xc4c3742bef9befef, 0xda7ec3e53ffc3f3f, 0xc7aa1c9255495555, 0xdb591079a2b2a2a2, 0xe9c96503ea8feaea, 0x6acaec0f65896565, 0x036968b9bad2baba, 0x4a5e93652fbc2f2f, 0x8e9de74ec027c0c0, 0x60a181bede5fdede, 0xfc386ce01c701c1c, 0x46e72ebbfdd3fdfd, 0x1f9a64524d294d4d, 0x7639e0e492729292, 0xfaeabc8f75c97575, 0x360c1e3006180606, 0xae0998248a128a8a, 0x4b7940f9b2f2b2b2, 0x85d15963e6bfe6e6, 0x7e1c36700e380e0e, 0xe73e63f81f7c1f1f, 0x55c4f73762956262, 0x3ab5a3eed477d4d4, 0x814d3229a89aa8a8, 0x5231f4c496629696, 0x62ef3a9bf9c3f9f9, 0xa397f666c533c5c5, 0x104ab13525942525, 0xabb220f259795959, 0xd015ae54842a8484, 0xc5e4a7b772d57272, 0xec72ddd539e43939, 0x1698615a4c2d4c4c, 0x94bc3bca5e655e5e, 0x9ff085e778fd7878, 0xe570d8dd38e03838, 0x980586148c0a8c8c, 0x17bfb2c6d163d1d1, 0xe4570b41a5aea5a5, 0xa1d94d43e2afe2e2, 0x4ec2f82f61996161, 0x427b45f1b3f6b3b3, 0x3442a51521842121, 0x0825d6949c4a9c9c, 0xee3c66f01e781e1e, 0x6186522243114343, 0xb193fc76c73bc7c7, 0x4fe52bb3fcd7fcfc, 0x2408142004100404, 0xe3a208b251595151, 0x252fc7bc995e9999, 0x22dac44f6da96d6d, 0x651a39680d340d0d, 0x79e93583facffafa, 0x69a384b6df5bdfdf, 0xa9fc9bd77ee57e7e, 0x1948b43d24902424, 0xfe76d7c53bec3b3b, 0x9a4b3d31ab96abab, 0xf081d13ece1fcece, 0x9922558811441111, 0x8303890c8f068f8f, 0x049c6b4a4e254e4e, 0x667351d1b7e6b7b7, 0xe0cb600beb8bebeb, 0xc178ccfd3cf03c3c, 0xfd1fbf7c813e8181, 0x4035fed4946a9494, 0x1cf30cebf7fbf7f7, 0x186f67a1b9deb9b9, 0x8b265f98134c1313, 0x51589c7d2cb02c2c, 0x05bbb8d6d36bd3d3, 0x8cd35c6be7bbe7e7, 0x39dccb576ea56e6e, 0xaa95f36ec437c4c4, 0x1b060f18030c0303, 0xdcac138a56455656, 0x5e88491a440d4444, 0xa0fe9edf7fe17f7f, 0x884f3721a99ea9a9, 0x6754824d2aa82a2a, 0x0a6b6db1bbd6bbbb, 0x879fe246c123c1c1, 0xf1a602a253515353, 0x72a58baedc57dcdc, 0x531627580b2c0b0b, 0x0127d39c9d4e9d9d, 0x2bd8c1476cad6c6c, 0xa462f59531c43131, 0xf3e8b98774cd7474, 0x15f109e3f6fff6f6, 0x4c8c430a46054646, 0xa5452609ac8aacac, 0xb50f973c891e8989, 0xb42844a014501414, 0xbadf425be1a3e1e1, 0xa62c4eb016581616, 0xf774d2cd3ae83a3a, 0x06d2d06f69b96969, 0x41122d4809240909, 0xd7e0ada770dd7070, 0x6f7154d9b6e2b6b6, 0x1ebdb7ced067d0d0, 0xd6c77e3bed93eded, 0xe285db2ecc17cccc, 0x6884572a42154242, 0x2c2dc2b4985a9898, 0xed550e49a4aaa4a4, 0x7550885d28a02828, 0x86b831da5c6d5c5c, 0x6bed3f93f8c7f8f8, 0xc211a44486228686, }, { 0x3078c018601818d8, 0x46af05238c232326, 0x91f97ec63fc6c6b8, 0xcd6f13e887e8e8fb, 0x13a14c87268787cb, 0x6d62a9b8dab8b811, 0x0205080104010109, 0x9e6e424f214f4f0d, 0x6ceead36d836369b, 0x510459a6a2a6a6ff, 0xb9bdded26fd2d20c, 0xf706fbf5f3f5f50e, 0xf280ef79f9797996, 0xdece5f6fa16f6f30, 0x3feffc917e91916d, 0xa407aa52555252f8, 0xc0fd27609d606047, 0x657689bccabcbc35, 0x2bcdac9b569b9b37, 0x018c048e028e8e8a, 0x5b1571a3b6a3a3d2, 0x183c600c300c0c6c, 0xf68aff7bf17b7b84, 0x6ae1b535d4353580, 0x3a69e81d741d1df5, 0xdd4753e0a7e0e0b3, 0xb3acf6d77bd7d721, 0x99ed5ec22fc2c29c, 0x5c966d2eb82e2e43, 0x967a624b314b4b29, 0xe121a3fedffefe5d, 0xae168257415757d5, 0x2a41a815541515bd, 0xeeb69f77c17777e8, 0x6eeba537dc373792, 0xd7567be5b3e5e59e, 0x23d98c9f469f9f13, 0xfd17d3f0e7f0f023, 0x947f6a4a354a4a20, 0xa9959eda4fdada44, 0xb025fa587d5858a2, 0x8fca06c903c9c9cf, 0x528d5529a429297c, 0x1422500a280a0a5a, 0x7f4fe1b1feb1b150, 0x5d1a69a0baa0a0c9, 0xd6da7f6bb16b6b14, 0x17ab5c852e8585d9, 0x677381bdcebdbd3c, 0xba34d25d695d5d8f, 0x2050801040101090, 0xf503f3f4f7f4f407, 0x8bc016cb0bcbcbdd, 0x7cc6ed3ef83e3ed3, 0x0a1128051405052d, 0xcee61f6781676778, 0xd55373e4b7e4e497, 0x4ebb25279c272702, 0x8258324119414173, 0x0b9d2c8b168b8ba7, 0x530151a7a6a7a7f6, 0xfa94cf7de97d7db2, 0x37fbdc956e959549, 0xad9f8ed847d8d856, 0xeb308bfbcbfbfb70, 0xc17123ee9feeeecd, 0xf891c77ced7c7cbb, 0xcce3176685666671, 0xa78ea6dd53dddd7b, 0x2e4bb8175c1717af, 0x8e46024701474745, 0x21dc849e429e9e1a, 0x89c51eca0fcacad4, 0x5a99752db42d2d58, 0x637991bfc6bfbf2e, 0x0e1b38071c07073f, 0x472301ad8eadadac, 0xb42fea5a755a5ab0, 0x1bb56c83368383ef, 0x66ff8533cc3333b6, 0xc6f23f639163635c, 0x040a100208020212, 0x493839aa92aaaa93, 0xe2a8af71d97171de, 0x8dcf0ec807c8c8c6, 0x327dc819641919d1, 0x927072493949493b, 0xaf9a86d943d9d95f, 0xf91dc3f2eff2f231, 0xdb484be3abe3e3a8, 0xb62ae25b715b5bb9, 0x0d9234881a8888bc, 0x29c8a49a529a9a3e, 0x4cbe2d269826260b, 0x64fa8d32c83232bf, 0x7d4ae9b0fab0b059, 0xcf6a1be983e9e9f2, 0x1e33780f3c0f0f77, 0xb7a6e6d573d5d533, 0x1dba74803a8080f4, 0x617c99bec2bebe27, 0x87de26cd13cdcdeb, 0x68e4bd34d0343489, 0x90757a483d484832, 0xe324abffdbffff54, 0xf48ff77af57a7a8d, 0x3deaf4907a909064, 0xbe3ec25f615f5f9d, 0x40a01d208020203d, 0xd0d56768bd68680f, 0x3472d01a681a1aca, 0x412c19ae82aeaeb7, 0x755ec9b4eab4b47d, 0xa8199a544d5454ce, 0x3be5ec937693937f, 0x44aa0d228822222f, 0xc8e907648d646463, 0xff12dbf1e3f1f12a, 0xe6a2bf73d17373cc, 0x245a901248121282, 0x805d3a401d40407a, 0x1028400820080848, 0x9be856c32bc3c395, 0xc57b33ec97ececdf, 0xab9096db4bdbdb4d, 0x5f1f61a1bea1a1c0, 0x07831c8d0e8d8d91, 0x7ac9f53df43d3dc8, 0x33f1cc976697975b, 0x0000000000000000, 0x83d436cf1bcfcff9, 0x5687452bac2b2b6e, 0xecb39776c57676e1, 0x19b06482328282e6, 0xb1a9fed67fd6d628, 0x3677d81b6c1b1bc3, 0x775bc1b5eeb5b574, 0x432911af86afafbe, 0xd4df776ab56a6a1d, 0xa00dba505d5050ea, 0x8a4c124509454557, 0xfb18cbf3ebf3f338, 0x60f09d30c03030ad, 0xc3742bef9befefc4, 0x7ec3e53ffc3f3fda, 0xaa1c9255495555c7, 0x591079a2b2a2a2db, 0xc96503ea8feaeae9, 0xcaec0f658965656a, 0x6968b9bad2baba03, 0x5e93652fbc2f2f4a, 0x9de74ec027c0c08e, 0xa181bede5fdede60, 0x386ce01c701c1cfc, 0xe72ebbfdd3fdfd46, 0x9a64524d294d4d1f, 0x39e0e49272929276, 0xeabc8f75c97575fa, 0x0c1e300618060636, 0x0998248a128a8aae, 0x7940f9b2f2b2b24b, 0xd15963e6bfe6e685, 0x1c36700e380e0e7e, 0x3e63f81f7c1f1fe7, 0xc4f7376295626255, 0xb5a3eed477d4d43a, 0x4d3229a89aa8a881, 0x31f4c49662969652, 0xef3a9bf9c3f9f962, 0x97f666c533c5c5a3, 0x4ab1352594252510, 0xb220f259795959ab, 0x15ae54842a8484d0, 0xe4a7b772d57272c5, 0x72ddd539e43939ec, 0x98615a4c2d4c4c16, 0xbc3bca5e655e5e94, 0xf085e778fd78789f, 0x70d8dd38e03838e5, 0x0586148c0a8c8c98, 0xbfb2c6d163d1d117, 0x570b41a5aea5a5e4, 0xd94d43e2afe2e2a1, 0xc2f82f619961614e, 0x7b45f1b3f6b3b342, 0x42a5152184212134, 0x25d6949c4a9c9c08, 0x3c66f01e781e1eee, 0x8652224311434361, 0x93fc76c73bc7c7b1, 0xe52bb3fcd7fcfc4f, 0x0814200410040424, 0xa208b251595151e3, 0x2fc7bc995e999925, 0xdac44f6da96d6d22, 0x1a39680d340d0d65, 0xe93583facffafa79, 0xa384b6df5bdfdf69, 0xfc9bd77ee57e7ea9, 0x48b43d2490242419, 0x76d7c53bec3b3bfe, 0x4b3d31ab96abab9a, 0x81d13ece1fcecef0, 0x2255881144111199, 0x03890c8f068f8f83, 0x9c6b4a4e254e4e04, 0x7351d1b7e6b7b766, 0xcb600beb8bebebe0, 0x78ccfd3cf03c3cc1, 0x1fbf7c813e8181fd, 0x35fed4946a949440, 0xf30cebf7fbf7f71c, 0x6f67a1b9deb9b918, 0x265f98134c13138b, 0x589c7d2cb02c2c51, 0xbbb8d6d36bd3d305, 0xd35c6be7bbe7e78c, 0xdccb576ea56e6e39, 0x95f36ec437c4c4aa, 0x060f18030c03031b, 0xac138a56455656dc, 0x88491a440d44445e, 0xfe9edf7fe17f7fa0, 0x4f3721a99ea9a988, 0x54824d2aa82a2a67, 0x6b6db1bbd6bbbb0a, 0x9fe246c123c1c187, 0xa602a253515353f1, 0xa58baedc57dcdc72, 0x1627580b2c0b0b53, 0x27d39c9d4e9d9d01, 0xd8c1476cad6c6c2b, 0x62f59531c43131a4, 0xe8b98774cd7474f3, 0xf109e3f6fff6f615, 0x8c430a460546464c, 0x452609ac8aacaca5, 0x0f973c891e8989b5, 0x2844a014501414b4, 0xdf425be1a3e1e1ba, 0x2c4eb016581616a6, 0x74d2cd3ae83a3af7, 0xd2d06f69b9696906, 0x122d480924090941, 0xe0ada770dd7070d7, 0x7154d9b6e2b6b66f, 0xbdb7ced067d0d01e, 0xc77e3bed93ededd6, 0x85db2ecc17cccce2, 0x84572a4215424268, 0x2dc2b4985a98982c, 0x550e49a4aaa4a4ed, 0x50885d28a0282875, 0xb831da5c6d5c5c86, 0xed3f93f8c7f8f86b, 0x11a44486228686c2, }, { 0x78c018601818d830, 0xaf05238c23232646, 0xf97ec63fc6c6b891, 0x6f13e887e8e8fbcd, 0xa14c87268787cb13, 0x62a9b8dab8b8116d, 0x0508010401010902, 0x6e424f214f4f0d9e, 0xeead36d836369b6c, 0x0459a6a2a6a6ff51, 0xbdded26fd2d20cb9, 0x06fbf5f3f5f50ef7, 0x80ef79f9797996f2, 0xce5f6fa16f6f30de, 0xeffc917e91916d3f, 0x07aa52555252f8a4, 0xfd27609d606047c0, 0x7689bccabcbc3565, 0xcdac9b569b9b372b, 0x8c048e028e8e8a01, 0x1571a3b6a3a3d25b, 0x3c600c300c0c6c18, 0x8aff7bf17b7b84f6, 0xe1b535d43535806a, 0x69e81d741d1df53a, 0x4753e0a7e0e0b3dd, 0xacf6d77bd7d721b3, 0xed5ec22fc2c29c99, 0x966d2eb82e2e435c, 0x7a624b314b4b2996, 0x21a3fedffefe5de1, 0x168257415757d5ae, 0x41a815541515bd2a, 0xb69f77c17777e8ee, 0xeba537dc3737926e, 0x567be5b3e5e59ed7, 0xd98c9f469f9f1323, 0x17d3f0e7f0f023fd, 0x7f6a4a354a4a2094, 0x959eda4fdada44a9, 0x25fa587d5858a2b0, 0xca06c903c9c9cf8f, 0x8d5529a429297c52, 0x22500a280a0a5a14, 0x4fe1b1feb1b1507f, 0x1a69a0baa0a0c95d, 0xda7f6bb16b6b14d6, 0xab5c852e8585d917, 0x7381bdcebdbd3c67, 0x34d25d695d5d8fba, 0x5080104010109020, 0x03f3f4f7f4f407f5, 0xc016cb0bcbcbdd8b, 0xc6ed3ef83e3ed37c, 0x1128051405052d0a, 0xe61f6781676778ce, 0x5373e4b7e4e497d5, 0xbb25279c2727024e, 0x5832411941417382, 0x9d2c8b168b8ba70b, 0x0151a7a6a7a7f653, 0x94cf7de97d7db2fa, 0xfbdc956e95954937, 0x9f8ed847d8d856ad, 0x308bfbcbfbfb70eb, 0x7123ee9feeeecdc1, 0x91c77ced7c7cbbf8, 0xe3176685666671cc, 0x8ea6dd53dddd7ba7, 0x4bb8175c1717af2e, 0x460247014747458e, 0xdc849e429e9e1a21, 0xc51eca0fcacad489, 0x99752db42d2d585a, 0x7991bfc6bfbf2e63, 0x1b38071c07073f0e, 0x2301ad8eadadac47, 0x2fea5a755a5ab0b4, 0xb56c83368383ef1b, 0xff8533cc3333b666, 0xf23f639163635cc6, 0x0a10020802021204, 0x3839aa92aaaa9349, 0xa8af71d97171dee2, 0xcf0ec807c8c8c68d, 0x7dc819641919d132, 0x7072493949493b92, 0x9a86d943d9d95faf, 0x1dc3f2eff2f231f9, 0x484be3abe3e3a8db, 0x2ae25b715b5bb9b6, 0x9234881a8888bc0d, 0xc8a49a529a9a3e29, 0xbe2d269826260b4c, 0xfa8d32c83232bf64, 0x4ae9b0fab0b0597d, 0x6a1be983e9e9f2cf, 0x33780f3c0f0f771e, 0xa6e6d573d5d533b7, 0xba74803a8080f41d, 0x7c99bec2bebe2761, 0xde26cd13cdcdeb87, 0xe4bd34d034348968, 0x757a483d48483290, 0x24abffdbffff54e3, 0x8ff77af57a7a8df4, 0xeaf4907a9090643d, 0x3ec25f615f5f9dbe, 0xa01d208020203d40, 0xd56768bd68680fd0, 0x72d01a681a1aca34, 0x2c19ae82aeaeb741, 0x5ec9b4eab4b47d75, 0x199a544d5454cea8, 0xe5ec937693937f3b, 0xaa0d228822222f44, 0xe907648d646463c8, 0x12dbf1e3f1f12aff, 0xa2bf73d17373cce6, 0x5a90124812128224, 0x5d3a401d40407a80, 0x2840082008084810, 0xe856c32bc3c3959b, 0x7b33ec97ececdfc5, 0x9096db4bdbdb4dab, 0x1f61a1bea1a1c05f, 0x831c8d0e8d8d9107, 0xc9f53df43d3dc87a, 0xf1cc976697975b33, 0x0000000000000000, 0xd436cf1bcfcff983, 0x87452bac2b2b6e56, 0xb39776c57676e1ec, 0xb06482328282e619, 0xa9fed67fd6d628b1, 0x77d81b6c1b1bc336, 0x5bc1b5eeb5b57477, 0x2911af86afafbe43, 0xdf776ab56a6a1dd4, 0x0dba505d5050eaa0, 0x4c1245094545578a, 0x18cbf3ebf3f338fb, 0xf09d30c03030ad60, 0x742bef9befefc4c3, 0xc3e53ffc3f3fda7e, 0x1c9255495555c7aa, 0x1079a2b2a2a2db59, 0x6503ea8feaeae9c9, 0xec0f658965656aca, 0x68b9bad2baba0369, 0x93652fbc2f2f4a5e, 0xe74ec027c0c08e9d, 0x81bede5fdede60a1, 0x6ce01c701c1cfc38, 0x2ebbfdd3fdfd46e7, 0x64524d294d4d1f9a, 0xe0e4927292927639, 0xbc8f75c97575faea, 0x1e3006180606360c, 0x98248a128a8aae09, 0x40f9b2f2b2b24b79, 0x5963e6bfe6e685d1, 0x36700e380e0e7e1c, 0x63f81f7c1f1fe73e, 0xf7376295626255c4, 0xa3eed477d4d43ab5, 0x3229a89aa8a8814d, 0xf4c4966296965231, 0x3a9bf9c3f9f962ef, 0xf666c533c5c5a397, 0xb13525942525104a, 0x20f259795959abb2, 0xae54842a8484d015, 0xa7b772d57272c5e4, 0xddd539e43939ec72, 0x615a4c2d4c4c1698, 0x3bca5e655e5e94bc, 0x85e778fd78789ff0, 0xd8dd38e03838e570, 0x86148c0a8c8c9805, 0xb2c6d163d1d117bf, 0x0b41a5aea5a5e457, 0x4d43e2afe2e2a1d9, 0xf82f619961614ec2, 0x45f1b3f6b3b3427b, 0xa515218421213442, 0xd6949c4a9c9c0825, 0x66f01e781e1eee3c, 0x5222431143436186, 0xfc76c73bc7c7b193, 0x2bb3fcd7fcfc4fe5, 0x1420041004042408, 0x08b251595151e3a2, 0xc7bc995e9999252f, 0xc44f6da96d6d22da, 0x39680d340d0d651a, 0x3583facffafa79e9, 0x84b6df5bdfdf69a3, 0x9bd77ee57e7ea9fc, 0xb43d249024241948, 0xd7c53bec3b3bfe76, 0x3d31ab96abab9a4b, 0xd13ece1fcecef081, 0x5588114411119922, 0x890c8f068f8f8303, 0x6b4a4e254e4e049c, 0x51d1b7e6b7b76673, 0x600beb8bebebe0cb, 0xccfd3cf03c3cc178, 0xbf7c813e8181fd1f, 0xfed4946a94944035, 0x0cebf7fbf7f71cf3, 0x67a1b9deb9b9186f, 0x5f98134c13138b26, 0x9c7d2cb02c2c5158, 0xb8d6d36bd3d305bb, 0x5c6be7bbe7e78cd3, 0xcb576ea56e6e39dc, 0xf36ec437c4c4aa95, 0x0f18030c03031b06, 0x138a56455656dcac, 0x491a440d44445e88, 0x9edf7fe17f7fa0fe, 0x3721a99ea9a9884f, 0x824d2aa82a2a6754, 0x6db1bbd6bbbb0a6b, 0xe246c123c1c1879f, 0x02a253515353f1a6, 0x8baedc57dcdc72a5, 0x27580b2c0b0b5316, 0xd39c9d4e9d9d0127, 0xc1476cad6c6c2bd8, 0xf59531c43131a462, 0xb98774cd7474f3e8, 0x09e3f6fff6f615f1, 0x430a460546464c8c, 0x2609ac8aacaca545, 0x973c891e8989b50f, 0x44a014501414b428, 0x425be1a3e1e1badf, 0x4eb016581616a62c, 0xd2cd3ae83a3af774, 0xd06f69b9696906d2, 0x2d48092409094112, 0xada770dd7070d7e0, 0x54d9b6e2b6b66f71, 0xb7ced067d0d01ebd, 0x7e3bed93ededd6c7, 0xdb2ecc17cccce285, 0x572a421542426884, 0xc2b4985a98982c2d, 0x0e49a4aaa4a4ed55, 0x885d28a028287550, 0x31da5c6d5c5c86b8, 0x3f93f8c7f8f86bed, 0xa44486228686c211, }, { 0xc018601818d83078, 0x05238c23232646af, 0x7ec63fc6c6b891f9, 0x13e887e8e8fbcd6f, 0x4c87268787cb13a1, 0xa9b8dab8b8116d62, 0x0801040101090205, 0x424f214f4f0d9e6e, 0xad36d836369b6cee, 0x59a6a2a6a6ff5104, 0xded26fd2d20cb9bd, 0xfbf5f3f5f50ef706, 0xef79f9797996f280, 0x5f6fa16f6f30dece, 0xfc917e91916d3fef, 0xaa52555252f8a407, 0x27609d606047c0fd, 0x89bccabcbc356576, 0xac9b569b9b372bcd, 0x048e028e8e8a018c, 0x71a3b6a3a3d25b15, 0x600c300c0c6c183c, 0xff7bf17b7b84f68a, 0xb535d43535806ae1, 0xe81d741d1df53a69, 0x53e0a7e0e0b3dd47, 0xf6d77bd7d721b3ac, 0x5ec22fc2c29c99ed, 0x6d2eb82e2e435c96, 0x624b314b4b29967a, 0xa3fedffefe5de121, 0x8257415757d5ae16, 0xa815541515bd2a41, 0x9f77c17777e8eeb6, 0xa537dc3737926eeb, 0x7be5b3e5e59ed756, 0x8c9f469f9f1323d9, 0xd3f0e7f0f023fd17, 0x6a4a354a4a20947f, 0x9eda4fdada44a995, 0xfa587d5858a2b025, 0x06c903c9c9cf8fca, 0x5529a429297c528d, 0x500a280a0a5a1422, 0xe1b1feb1b1507f4f, 0x69a0baa0a0c95d1a, 0x7f6bb16b6b14d6da, 0x5c852e8585d917ab, 0x81bdcebdbd3c6773, 0xd25d695d5d8fba34, 0x8010401010902050, 0xf3f4f7f4f407f503, 0x16cb0bcbcbdd8bc0, 0xed3ef83e3ed37cc6, 0x28051405052d0a11, 0x1f6781676778cee6, 0x73e4b7e4e497d553, 0x25279c2727024ebb, 0x3241194141738258, 0x2c8b168b8ba70b9d, 0x51a7a6a7a7f65301, 0xcf7de97d7db2fa94, 0xdc956e95954937fb, 0x8ed847d8d856ad9f, 0x8bfbcbfbfb70eb30, 0x23ee9feeeecdc171, 0xc77ced7c7cbbf891, 0x176685666671cce3, 0xa6dd53dddd7ba78e, 0xb8175c1717af2e4b, 0x0247014747458e46, 0x849e429e9e1a21dc, 0x1eca0fcacad489c5, 0x752db42d2d585a99, 0x91bfc6bfbf2e6379, 0x38071c07073f0e1b, 0x01ad8eadadac4723, 0xea5a755a5ab0b42f, 0x6c83368383ef1bb5, 0x8533cc3333b666ff, 0x3f639163635cc6f2, 0x100208020212040a, 0x39aa92aaaa934938, 0xaf71d97171dee2a8, 0x0ec807c8c8c68dcf, 0xc819641919d1327d, 0x72493949493b9270, 0x86d943d9d95faf9a, 0xc3f2eff2f231f91d, 0x4be3abe3e3a8db48, 0xe25b715b5bb9b62a, 0x34881a8888bc0d92, 0xa49a529a9a3e29c8, 0x2d269826260b4cbe, 0x8d32c83232bf64fa, 0xe9b0fab0b0597d4a, 0x1be983e9e9f2cf6a, 0x780f3c0f0f771e33, 0xe6d573d5d533b7a6, 0x74803a8080f41dba, 0x99bec2bebe27617c, 0x26cd13cdcdeb87de, 0xbd34d034348968e4, 0x7a483d4848329075, 0xabffdbffff54e324, 0xf77af57a7a8df48f, 0xf4907a9090643dea, 0xc25f615f5f9dbe3e, 0x1d208020203d40a0, 0x6768bd68680fd0d5, 0xd01a681a1aca3472, 0x19ae82aeaeb7412c, 0xc9b4eab4b47d755e, 0x9a544d5454cea819, 0xec937693937f3be5, 0x0d228822222f44aa, 0x07648d646463c8e9, 0xdbf1e3f1f12aff12, 0xbf73d17373cce6a2, 0x901248121282245a, 0x3a401d40407a805d, 0x4008200808481028, 0x56c32bc3c3959be8, 0x33ec97ececdfc57b, 0x96db4bdbdb4dab90, 0x61a1bea1a1c05f1f, 0x1c8d0e8d8d910783, 0xf53df43d3dc87ac9, 0xcc976697975b33f1, 0x0000000000000000, 0x36cf1bcfcff983d4, 0x452bac2b2b6e5687, 0x9776c57676e1ecb3, 0x6482328282e619b0, 0xfed67fd6d628b1a9, 0xd81b6c1b1bc33677, 0xc1b5eeb5b574775b, 0x11af86afafbe4329, 0x776ab56a6a1dd4df, 0xba505d5050eaa00d, 0x1245094545578a4c, 0xcbf3ebf3f338fb18, 0x9d30c03030ad60f0, 0x2bef9befefc4c374, 0xe53ffc3f3fda7ec3, 0x9255495555c7aa1c, 0x79a2b2a2a2db5910, 0x03ea8feaeae9c965, 0x0f658965656acaec, 0xb9bad2baba036968, 0x652fbc2f2f4a5e93, 0x4ec027c0c08e9de7, 0xbede5fdede60a181, 0xe01c701c1cfc386c, 0xbbfdd3fdfd46e72e, 0x524d294d4d1f9a64, 0xe4927292927639e0, 0x8f75c97575faeabc, 0x3006180606360c1e, 0x248a128a8aae0998, 0xf9b2f2b2b24b7940, 0x63e6bfe6e685d159, 0x700e380e0e7e1c36, 0xf81f7c1f1fe73e63, 0x376295626255c4f7, 0xeed477d4d43ab5a3, 0x29a89aa8a8814d32, 0xc4966296965231f4, 0x9bf9c3f9f962ef3a, 0x66c533c5c5a397f6, 0x3525942525104ab1, 0xf259795959abb220, 0x54842a8484d015ae, 0xb772d57272c5e4a7, 0xd539e43939ec72dd, 0x5a4c2d4c4c169861, 0xca5e655e5e94bc3b, 0xe778fd78789ff085, 0xdd38e03838e570d8, 0x148c0a8c8c980586, 0xc6d163d1d117bfb2, 0x41a5aea5a5e4570b, 0x43e2afe2e2a1d94d, 0x2f619961614ec2f8, 0xf1b3f6b3b3427b45, 0x15218421213442a5, 0x949c4a9c9c0825d6, 0xf01e781e1eee3c66, 0x2243114343618652, 0x76c73bc7c7b193fc, 0xb3fcd7fcfc4fe52b, 0x2004100404240814, 0xb251595151e3a208, 0xbc995e9999252fc7, 0x4f6da96d6d22dac4, 0x680d340d0d651a39, 0x83facffafa79e935, 0xb6df5bdfdf69a384, 0xd77ee57e7ea9fc9b, 0x3d249024241948b4, 0xc53bec3b3bfe76d7, 0x31ab96abab9a4b3d, 0x3ece1fcecef081d1, 0x8811441111992255, 0x0c8f068f8f830389, 0x4a4e254e4e049c6b, 0xd1b7e6b7b7667351, 0x0beb8bebebe0cb60, 0xfd3cf03c3cc178cc, 0x7c813e8181fd1fbf, 0xd4946a94944035fe, 0xebf7fbf7f71cf30c, 0xa1b9deb9b9186f67, 0x98134c13138b265f, 0x7d2cb02c2c51589c, 0xd6d36bd3d305bbb8, 0x6be7bbe7e78cd35c, 0x576ea56e6e39dccb, 0x6ec437c4c4aa95f3, 0x18030c03031b060f, 0x8a56455656dcac13, 0x1a440d44445e8849, 0xdf7fe17f7fa0fe9e, 0x21a99ea9a9884f37, 0x4d2aa82a2a675482, 0xb1bbd6bbbb0a6b6d, 0x46c123c1c1879fe2, 0xa253515353f1a602, 0xaedc57dcdc72a58b, 0x580b2c0b0b531627, 0x9c9d4e9d9d0127d3, 0x476cad6c6c2bd8c1, 0x9531c43131a462f5, 0x8774cd7474f3e8b9, 0xe3f6fff6f615f109, 0x0a460546464c8c43, 0x09ac8aacaca54526, 0x3c891e8989b50f97, 0xa014501414b42844, 0x5be1a3e1e1badf42, 0xb016581616a62c4e, 0xcd3ae83a3af774d2, 0x6f69b9696906d2d0, 0x480924090941122d, 0xa770dd7070d7e0ad, 0xd9b6e2b6b66f7154, 0xced067d0d01ebdb7, 0x3bed93ededd6c77e, 0x2ecc17cccce285db, 0x2a42154242688457, 0xb4985a98982c2dc2, 0x49a4aaa4a4ed550e, 0x5d28a02828755088, 0xda5c6d5c5c86b831, 0x93f8c7f8f86bed3f, 0x4486228686c211a4, }, { 0x18601818d83078c0, 0x238c23232646af05, 0xc63fc6c6b891f97e, 0xe887e8e8fbcd6f13, 0x87268787cb13a14c, 0xb8dab8b8116d62a9, 0x0104010109020508, 0x4f214f4f0d9e6e42, 0x36d836369b6ceead, 0xa6a2a6a6ff510459, 0xd26fd2d20cb9bdde, 0xf5f3f5f50ef706fb, 0x79f9797996f280ef, 0x6fa16f6f30dece5f, 0x917e91916d3feffc, 0x52555252f8a407aa, 0x609d606047c0fd27, 0xbccabcbc35657689, 0x9b569b9b372bcdac, 0x8e028e8e8a018c04, 0xa3b6a3a3d25b1571, 0x0c300c0c6c183c60, 0x7bf17b7b84f68aff, 0x35d43535806ae1b5, 0x1d741d1df53a69e8, 0xe0a7e0e0b3dd4753, 0xd77bd7d721b3acf6, 0xc22fc2c29c99ed5e, 0x2eb82e2e435c966d, 0x4b314b4b29967a62, 0xfedffefe5de121a3, 0x57415757d5ae1682, 0x15541515bd2a41a8, 0x77c17777e8eeb69f, 0x37dc3737926eeba5, 0xe5b3e5e59ed7567b, 0x9f469f9f1323d98c, 0xf0e7f0f023fd17d3, 0x4a354a4a20947f6a, 0xda4fdada44a9959e, 0x587d5858a2b025fa, 0xc903c9c9cf8fca06, 0x29a429297c528d55, 0x0a280a0a5a142250, 0xb1feb1b1507f4fe1, 0xa0baa0a0c95d1a69, 0x6bb16b6b14d6da7f, 0x852e8585d917ab5c, 0xbdcebdbd3c677381, 0x5d695d5d8fba34d2, 0x1040101090205080, 0xf4f7f4f407f503f3, 0xcb0bcbcbdd8bc016, 0x3ef83e3ed37cc6ed, 0x051405052d0a1128, 0x6781676778cee61f, 0xe4b7e4e497d55373, 0x279c2727024ebb25, 0x4119414173825832, 0x8b168b8ba70b9d2c, 0xa7a6a7a7f6530151, 0x7de97d7db2fa94cf, 0x956e95954937fbdc, 0xd847d8d856ad9f8e, 0xfbcbfbfb70eb308b, 0xee9feeeecdc17123, 0x7ced7c7cbbf891c7, 0x6685666671cce317, 0xdd53dddd7ba78ea6, 0x175c1717af2e4bb8, 0x47014747458e4602, 0x9e429e9e1a21dc84, 0xca0fcacad489c51e, 0x2db42d2d585a9975, 0xbfc6bfbf2e637991, 0x071c07073f0e1b38, 0xad8eadadac472301, 0x5a755a5ab0b42fea, 0x83368383ef1bb56c, 0x33cc3333b666ff85, 0x639163635cc6f23f, 0x0208020212040a10, 0xaa92aaaa93493839, 0x71d97171dee2a8af, 0xc807c8c8c68dcf0e, 0x19641919d1327dc8, 0x493949493b927072, 0xd943d9d95faf9a86, 0xf2eff2f231f91dc3, 0xe3abe3e3a8db484b, 0x5b715b5bb9b62ae2, 0x881a8888bc0d9234, 0x9a529a9a3e29c8a4, 0x269826260b4cbe2d, 0x32c83232bf64fa8d, 0xb0fab0b0597d4ae9, 0xe983e9e9f2cf6a1b, 0x0f3c0f0f771e3378, 0xd573d5d533b7a6e6, 0x803a8080f41dba74, 0xbec2bebe27617c99, 0xcd13cdcdeb87de26, 0x34d034348968e4bd, 0x483d48483290757a, 0xffdbffff54e324ab, 0x7af57a7a8df48ff7, 0x907a9090643deaf4, 0x5f615f5f9dbe3ec2, 0x208020203d40a01d, 0x68bd68680fd0d567, 0x1a681a1aca3472d0, 0xae82aeaeb7412c19, 0xb4eab4b47d755ec9, 0x544d5454cea8199a, 0x937693937f3be5ec, 0x228822222f44aa0d, 0x648d646463c8e907, 0xf1e3f1f12aff12db, 0x73d17373cce6a2bf, 0x1248121282245a90, 0x401d40407a805d3a, 0x0820080848102840, 0xc32bc3c3959be856, 0xec97ececdfc57b33, 0xdb4bdbdb4dab9096, 0xa1bea1a1c05f1f61, 0x8d0e8d8d9107831c, 0x3df43d3dc87ac9f5, 0x976697975b33f1cc, 0x0000000000000000, 0xcf1bcfcff983d436, 0x2bac2b2b6e568745, 0x76c57676e1ecb397, 0x82328282e619b064, 0xd67fd6d628b1a9fe, 0x1b6c1b1bc33677d8, 0xb5eeb5b574775bc1, 0xaf86afafbe432911, 0x6ab56a6a1dd4df77, 0x505d5050eaa00dba, 0x45094545578a4c12, 0xf3ebf3f338fb18cb, 0x30c03030ad60f09d, 0xef9befefc4c3742b, 0x3ffc3f3fda7ec3e5, 0x55495555c7aa1c92, 0xa2b2a2a2db591079, 0xea8feaeae9c96503, 0x658965656acaec0f, 0xbad2baba036968b9, 0x2fbc2f2f4a5e9365, 0xc027c0c08e9de74e, 0xde5fdede60a181be, 0x1c701c1cfc386ce0, 0xfdd3fdfd46e72ebb, 0x4d294d4d1f9a6452, 0x927292927639e0e4, 0x75c97575faeabc8f, 0x06180606360c1e30, 0x8a128a8aae099824, 0xb2f2b2b24b7940f9, 0xe6bfe6e685d15963, 0x0e380e0e7e1c3670, 0x1f7c1f1fe73e63f8, 0x6295626255c4f737, 0xd477d4d43ab5a3ee, 0xa89aa8a8814d3229, 0x966296965231f4c4, 0xf9c3f9f962ef3a9b, 0xc533c5c5a397f666, 0x25942525104ab135, 0x59795959abb220f2, 0x842a8484d015ae54, 0x72d57272c5e4a7b7, 0x39e43939ec72ddd5, 0x4c2d4c4c1698615a, 0x5e655e5e94bc3bca, 0x78fd78789ff085e7, 0x38e03838e570d8dd, 0x8c0a8c8c98058614, 0xd163d1d117bfb2c6, 0xa5aea5a5e4570b41, 0xe2afe2e2a1d94d43, 0x619961614ec2f82f, 0xb3f6b3b3427b45f1, 0x218421213442a515, 0x9c4a9c9c0825d694, 0x1e781e1eee3c66f0, 0x4311434361865222, 0xc73bc7c7b193fc76, 0xfcd7fcfc4fe52bb3, 0x0410040424081420, 0x51595151e3a208b2, 0x995e9999252fc7bc, 0x6da96d6d22dac44f, 0x0d340d0d651a3968, 0xfacffafa79e93583, 0xdf5bdfdf69a384b6, 0x7ee57e7ea9fc9bd7, 0x249024241948b43d, 0x3bec3b3bfe76d7c5, 0xab96abab9a4b3d31, 0xce1fcecef081d13e, 0x1144111199225588, 0x8f068f8f8303890c, 0x4e254e4e049c6b4a, 0xb7e6b7b7667351d1, 0xeb8bebebe0cb600b, 0x3cf03c3cc178ccfd, 0x813e8181fd1fbf7c, 0x946a94944035fed4, 0xf7fbf7f71cf30ceb, 0xb9deb9b9186f67a1, 0x134c13138b265f98, 0x2cb02c2c51589c7d, 0xd36bd3d305bbb8d6, 0xe7bbe7e78cd35c6b, 0x6ea56e6e39dccb57, 0xc437c4c4aa95f36e, 0x030c03031b060f18, 0x56455656dcac138a, 0x440d44445e88491a, 0x7fe17f7fa0fe9edf, 0xa99ea9a9884f3721, 0x2aa82a2a6754824d, 0xbbd6bbbb0a6b6db1, 0xc123c1c1879fe246, 0x53515353f1a602a2, 0xdc57dcdc72a58bae, 0x0b2c0b0b53162758, 0x9d4e9d9d0127d39c, 0x6cad6c6c2bd8c147, 0x31c43131a462f595, 0x74cd7474f3e8b987, 0xf6fff6f615f109e3, 0x460546464c8c430a, 0xac8aacaca5452609, 0x891e8989b50f973c, 0x14501414b42844a0, 0xe1a3e1e1badf425b, 0x16581616a62c4eb0, 0x3ae83a3af774d2cd, 0x69b9696906d2d06f, 0x0924090941122d48, 0x70dd7070d7e0ada7, 0xb6e2b6b66f7154d9, 0xd067d0d01ebdb7ce, 0xed93ededd6c77e3b, 0xcc17cccce285db2e, 0x421542426884572a, 0x985a98982c2dc2b4, 0xa4aaa4a4ed550e49, 0x28a028287550885d, 0x5c6d5c5c86b831da, 0xf8c7f8f86bed3f93, 0x86228686c211a444, }, { 0x601818d83078c018, 0x8c23232646af0523, 0x3fc6c6b891f97ec6, 0x87e8e8fbcd6f13e8, 0x268787cb13a14c87, 0xdab8b8116d62a9b8, 0x0401010902050801, 0x214f4f0d9e6e424f, 0xd836369b6ceead36, 0xa2a6a6ff510459a6, 0x6fd2d20cb9bdded2, 0xf3f5f50ef706fbf5, 0xf9797996f280ef79, 0xa16f6f30dece5f6f, 0x7e91916d3feffc91, 0x555252f8a407aa52, 0x9d606047c0fd2760, 0xcabcbc35657689bc, 0x569b9b372bcdac9b, 0x028e8e8a018c048e, 0xb6a3a3d25b1571a3, 0x300c0c6c183c600c, 0xf17b7b84f68aff7b, 0xd43535806ae1b535, 0x741d1df53a69e81d, 0xa7e0e0b3dd4753e0, 0x7bd7d721b3acf6d7, 0x2fc2c29c99ed5ec2, 0xb82e2e435c966d2e, 0x314b4b29967a624b, 0xdffefe5de121a3fe, 0x415757d5ae168257, 0x541515bd2a41a815, 0xc17777e8eeb69f77, 0xdc3737926eeba537, 0xb3e5e59ed7567be5, 0x469f9f1323d98c9f, 0xe7f0f023fd17d3f0, 0x354a4a20947f6a4a, 0x4fdada44a9959eda, 0x7d5858a2b025fa58, 0x03c9c9cf8fca06c9, 0xa429297c528d5529, 0x280a0a5a1422500a, 0xfeb1b1507f4fe1b1, 0xbaa0a0c95d1a69a0, 0xb16b6b14d6da7f6b, 0x2e8585d917ab5c85, 0xcebdbd3c677381bd, 0x695d5d8fba34d25d, 0x4010109020508010, 0xf7f4f407f503f3f4, 0x0bcbcbdd8bc016cb, 0xf83e3ed37cc6ed3e, 0x1405052d0a112805, 0x81676778cee61f67, 0xb7e4e497d55373e4, 0x9c2727024ebb2527, 0x1941417382583241, 0x168b8ba70b9d2c8b, 0xa6a7a7f6530151a7, 0xe97d7db2fa94cf7d, 0x6e95954937fbdc95, 0x47d8d856ad9f8ed8, 0xcbfbfb70eb308bfb, 0x9feeeecdc17123ee, 0xed7c7cbbf891c77c, 0x85666671cce31766, 0x53dddd7ba78ea6dd, 0x5c1717af2e4bb817, 0x014747458e460247, 0x429e9e1a21dc849e, 0x0fcacad489c51eca, 0xb42d2d585a99752d, 0xc6bfbf2e637991bf, 0x1c07073f0e1b3807, 0x8eadadac472301ad, 0x755a5ab0b42fea5a, 0x368383ef1bb56c83, 0xcc3333b666ff8533, 0x9163635cc6f23f63, 0x08020212040a1002, 0x92aaaa93493839aa, 0xd97171dee2a8af71, 0x07c8c8c68dcf0ec8, 0x641919d1327dc819, 0x3949493b92707249, 0x43d9d95faf9a86d9, 0xeff2f231f91dc3f2, 0xabe3e3a8db484be3, 0x715b5bb9b62ae25b, 0x1a8888bc0d923488, 0x529a9a3e29c8a49a, 0x9826260b4cbe2d26, 0xc83232bf64fa8d32, 0xfab0b0597d4ae9b0, 0x83e9e9f2cf6a1be9, 0x3c0f0f771e33780f, 0x73d5d533b7a6e6d5, 0x3a8080f41dba7480, 0xc2bebe27617c99be, 0x13cdcdeb87de26cd, 0xd034348968e4bd34, 0x3d48483290757a48, 0xdbffff54e324abff, 0xf57a7a8df48ff77a, 0x7a9090643deaf490, 0x615f5f9dbe3ec25f, 0x8020203d40a01d20, 0xbd68680fd0d56768, 0x681a1aca3472d01a, 0x82aeaeb7412c19ae, 0xeab4b47d755ec9b4, 0x4d5454cea8199a54, 0x7693937f3be5ec93, 0x8822222f44aa0d22, 0x8d646463c8e90764, 0xe3f1f12aff12dbf1, 0xd17373cce6a2bf73, 0x48121282245a9012, 0x1d40407a805d3a40, 0x2008084810284008, 0x2bc3c3959be856c3, 0x97ececdfc57b33ec, 0x4bdbdb4dab9096db, 0xbea1a1c05f1f61a1, 0x0e8d8d9107831c8d, 0xf43d3dc87ac9f53d, 0x6697975b33f1cc97, 0x0000000000000000, 0x1bcfcff983d436cf, 0xac2b2b6e5687452b, 0xc57676e1ecb39776, 0x328282e619b06482, 0x7fd6d628b1a9fed6, 0x6c1b1bc33677d81b, 0xeeb5b574775bc1b5, 0x86afafbe432911af, 0xb56a6a1dd4df776a, 0x5d5050eaa00dba50, 0x094545578a4c1245, 0xebf3f338fb18cbf3, 0xc03030ad60f09d30, 0x9befefc4c3742bef, 0xfc3f3fda7ec3e53f, 0x495555c7aa1c9255, 0xb2a2a2db591079a2, 0x8feaeae9c96503ea, 0x8965656acaec0f65, 0xd2baba036968b9ba, 0xbc2f2f4a5e93652f, 0x27c0c08e9de74ec0, 0x5fdede60a181bede, 0x701c1cfc386ce01c, 0xd3fdfd46e72ebbfd, 0x294d4d1f9a64524d, 0x7292927639e0e492, 0xc97575faeabc8f75, 0x180606360c1e3006, 0x128a8aae0998248a, 0xf2b2b24b7940f9b2, 0xbfe6e685d15963e6, 0x380e0e7e1c36700e, 0x7c1f1fe73e63f81f, 0x95626255c4f73762, 0x77d4d43ab5a3eed4, 0x9aa8a8814d3229a8, 0x6296965231f4c496, 0xc3f9f962ef3a9bf9, 0x33c5c5a397f666c5, 0x942525104ab13525, 0x795959abb220f259, 0x2a8484d015ae5484, 0xd57272c5e4a7b772, 0xe43939ec72ddd539, 0x2d4c4c1698615a4c, 0x655e5e94bc3bca5e, 0xfd78789ff085e778, 0xe03838e570d8dd38, 0x0a8c8c980586148c, 0x63d1d117bfb2c6d1, 0xaea5a5e4570b41a5, 0xafe2e2a1d94d43e2, 0x9961614ec2f82f61, 0xf6b3b3427b45f1b3, 0x8421213442a51521, 0x4a9c9c0825d6949c, 0x781e1eee3c66f01e, 0x1143436186522243, 0x3bc7c7b193fc76c7, 0xd7fcfc4fe52bb3fc, 0x1004042408142004, 0x595151e3a208b251, 0x5e9999252fc7bc99, 0xa96d6d22dac44f6d, 0x340d0d651a39680d, 0xcffafa79e93583fa, 0x5bdfdf69a384b6df, 0xe57e7ea9fc9bd77e, 0x9024241948b43d24, 0xec3b3bfe76d7c53b, 0x96abab9a4b3d31ab, 0x1fcecef081d13ece, 0x4411119922558811, 0x068f8f8303890c8f, 0x254e4e049c6b4a4e, 0xe6b7b7667351d1b7, 0x8bebebe0cb600beb, 0xf03c3cc178ccfd3c, 0x3e8181fd1fbf7c81, 0x6a94944035fed494, 0xfbf7f71cf30cebf7, 0xdeb9b9186f67a1b9, 0x4c13138b265f9813, 0xb02c2c51589c7d2c, 0x6bd3d305bbb8d6d3, 0xbbe7e78cd35c6be7, 0xa56e6e39dccb576e, 0x37c4c4aa95f36ec4, 0x0c03031b060f1803, 0x455656dcac138a56, 0x0d44445e88491a44, 0xe17f7fa0fe9edf7f, 0x9ea9a9884f3721a9, 0xa82a2a6754824d2a, 0xd6bbbb0a6b6db1bb, 0x23c1c1879fe246c1, 0x515353f1a602a253, 0x57dcdc72a58baedc, 0x2c0b0b531627580b, 0x4e9d9d0127d39c9d, 0xad6c6c2bd8c1476c, 0xc43131a462f59531, 0xcd7474f3e8b98774, 0xfff6f615f109e3f6, 0x0546464c8c430a46, 0x8aacaca5452609ac, 0x1e8989b50f973c89, 0x501414b42844a014, 0xa3e1e1badf425be1, 0x581616a62c4eb016, 0xe83a3af774d2cd3a, 0xb9696906d2d06f69, 0x24090941122d4809, 0xdd7070d7e0ada770, 0xe2b6b66f7154d9b6, 0x67d0d01ebdb7ced0, 0x93ededd6c77e3bed, 0x17cccce285db2ecc, 0x1542426884572a42, 0x5a98982c2dc2b498, 0xaaa4a4ed550e49a4, 0xa028287550885d28, 0x6d5c5c86b831da5c, 0xc7f8f86bed3f93f8, 0x228686c211a44486, }, { 0x1818d83078c01860, 0x23232646af05238c, 0xc6c6b891f97ec63f, 0xe8e8fbcd6f13e887, 0x8787cb13a14c8726, 0xb8b8116d62a9b8da, 0x0101090205080104, 0x4f4f0d9e6e424f21, 0x36369b6ceead36d8, 0xa6a6ff510459a6a2, 0xd2d20cb9bdded26f, 0xf5f50ef706fbf5f3, 0x797996f280ef79f9, 0x6f6f30dece5f6fa1, 0x91916d3feffc917e, 0x5252f8a407aa5255, 0x606047c0fd27609d, 0xbcbc35657689bcca, 0x9b9b372bcdac9b56, 0x8e8e8a018c048e02, 0xa3a3d25b1571a3b6, 0x0c0c6c183c600c30, 0x7b7b84f68aff7bf1, 0x3535806ae1b535d4, 0x1d1df53a69e81d74, 0xe0e0b3dd4753e0a7, 0xd7d721b3acf6d77b, 0xc2c29c99ed5ec22f, 0x2e2e435c966d2eb8, 0x4b4b29967a624b31, 0xfefe5de121a3fedf, 0x5757d5ae16825741, 0x1515bd2a41a81554, 0x7777e8eeb69f77c1, 0x3737926eeba537dc, 0xe5e59ed7567be5b3, 0x9f9f1323d98c9f46, 0xf0f023fd17d3f0e7, 0x4a4a20947f6a4a35, 0xdada44a9959eda4f, 0x5858a2b025fa587d, 0xc9c9cf8fca06c903, 0x29297c528d5529a4, 0x0a0a5a1422500a28, 0xb1b1507f4fe1b1fe, 0xa0a0c95d1a69a0ba, 0x6b6b14d6da7f6bb1, 0x8585d917ab5c852e, 0xbdbd3c677381bdce, 0x5d5d8fba34d25d69, 0x1010902050801040, 0xf4f407f503f3f4f7, 0xcbcbdd8bc016cb0b, 0x3e3ed37cc6ed3ef8, 0x05052d0a11280514, 0x676778cee61f6781, 0xe4e497d55373e4b7, 0x2727024ebb25279c, 0x4141738258324119, 0x8b8ba70b9d2c8b16, 0xa7a7f6530151a7a6, 0x7d7db2fa94cf7de9, 0x95954937fbdc956e, 0xd8d856ad9f8ed847, 0xfbfb70eb308bfbcb, 0xeeeecdc17123ee9f, 0x7c7cbbf891c77ced, 0x666671cce3176685, 0xdddd7ba78ea6dd53, 0x1717af2e4bb8175c, 0x4747458e46024701, 0x9e9e1a21dc849e42, 0xcacad489c51eca0f, 0x2d2d585a99752db4, 0xbfbf2e637991bfc6, 0x07073f0e1b38071c, 0xadadac472301ad8e, 0x5a5ab0b42fea5a75, 0x8383ef1bb56c8336, 0x3333b666ff8533cc, 0x63635cc6f23f6391, 0x020212040a100208, 0xaaaa93493839aa92, 0x7171dee2a8af71d9, 0xc8c8c68dcf0ec807, 0x1919d1327dc81964, 0x49493b9270724939, 0xd9d95faf9a86d943, 0xf2f231f91dc3f2ef, 0xe3e3a8db484be3ab, 0x5b5bb9b62ae25b71, 0x8888bc0d9234881a, 0x9a9a3e29c8a49a52, 0x26260b4cbe2d2698, 0x3232bf64fa8d32c8, 0xb0b0597d4ae9b0fa, 0xe9e9f2cf6a1be983, 0x0f0f771e33780f3c, 0xd5d533b7a6e6d573, 0x8080f41dba74803a, 0xbebe27617c99bec2, 0xcdcdeb87de26cd13, 0x34348968e4bd34d0, 0x48483290757a483d, 0xffff54e324abffdb, 0x7a7a8df48ff77af5, 0x9090643deaf4907a, 0x5f5f9dbe3ec25f61, 0x20203d40a01d2080, 0x68680fd0d56768bd, 0x1a1aca3472d01a68, 0xaeaeb7412c19ae82, 0xb4b47d755ec9b4ea, 0x5454cea8199a544d, 0x93937f3be5ec9376, 0x22222f44aa0d2288, 0x646463c8e907648d, 0xf1f12aff12dbf1e3, 0x7373cce6a2bf73d1, 0x121282245a901248, 0x40407a805d3a401d, 0x0808481028400820, 0xc3c3959be856c32b, 0xececdfc57b33ec97, 0xdbdb4dab9096db4b, 0xa1a1c05f1f61a1be, 0x8d8d9107831c8d0e, 0x3d3dc87ac9f53df4, 0x97975b33f1cc9766, 0x0000000000000000, 0xcfcff983d436cf1b, 0x2b2b6e5687452bac, 0x7676e1ecb39776c5, 0x8282e619b0648232, 0xd6d628b1a9fed67f, 0x1b1bc33677d81b6c, 0xb5b574775bc1b5ee, 0xafafbe432911af86, 0x6a6a1dd4df776ab5, 0x5050eaa00dba505d, 0x4545578a4c124509, 0xf3f338fb18cbf3eb, 0x3030ad60f09d30c0, 0xefefc4c3742bef9b, 0x3f3fda7ec3e53ffc, 0x5555c7aa1c925549, 0xa2a2db591079a2b2, 0xeaeae9c96503ea8f, 0x65656acaec0f6589, 0xbaba036968b9bad2, 0x2f2f4a5e93652fbc, 0xc0c08e9de74ec027, 0xdede60a181bede5f, 0x1c1cfc386ce01c70, 0xfdfd46e72ebbfdd3, 0x4d4d1f9a64524d29, 0x92927639e0e49272, 0x7575faeabc8f75c9, 0x0606360c1e300618, 0x8a8aae0998248a12, 0xb2b24b7940f9b2f2, 0xe6e685d15963e6bf, 0x0e0e7e1c36700e38, 0x1f1fe73e63f81f7c, 0x626255c4f7376295, 0xd4d43ab5a3eed477, 0xa8a8814d3229a89a, 0x96965231f4c49662, 0xf9f962ef3a9bf9c3, 0xc5c5a397f666c533, 0x2525104ab1352594, 0x5959abb220f25979, 0x8484d015ae54842a, 0x7272c5e4a7b772d5, 0x3939ec72ddd539e4, 0x4c4c1698615a4c2d, 0x5e5e94bc3bca5e65, 0x78789ff085e778fd, 0x3838e570d8dd38e0, 0x8c8c980586148c0a, 0xd1d117bfb2c6d163, 0xa5a5e4570b41a5ae, 0xe2e2a1d94d43e2af, 0x61614ec2f82f6199, 0xb3b3427b45f1b3f6, 0x21213442a5152184, 0x9c9c0825d6949c4a, 0x1e1eee3c66f01e78, 0x4343618652224311, 0xc7c7b193fc76c73b, 0xfcfc4fe52bb3fcd7, 0x0404240814200410, 0x5151e3a208b25159, 0x9999252fc7bc995e, 0x6d6d22dac44f6da9, 0x0d0d651a39680d34, 0xfafa79e93583facf, 0xdfdf69a384b6df5b, 0x7e7ea9fc9bd77ee5, 0x24241948b43d2490, 0x3b3bfe76d7c53bec, 0xabab9a4b3d31ab96, 0xcecef081d13ece1f, 0x1111992255881144, 0x8f8f8303890c8f06, 0x4e4e049c6b4a4e25, 0xb7b7667351d1b7e6, 0xebebe0cb600beb8b, 0x3c3cc178ccfd3cf0, 0x8181fd1fbf7c813e, 0x94944035fed4946a, 0xf7f71cf30cebf7fb, 0xb9b9186f67a1b9de, 0x13138b265f98134c, 0x2c2c51589c7d2cb0, 0xd3d305bbb8d6d36b, 0xe7e78cd35c6be7bb, 0x6e6e39dccb576ea5, 0xc4c4aa95f36ec437, 0x03031b060f18030c, 0x5656dcac138a5645, 0x44445e88491a440d, 0x7f7fa0fe9edf7fe1, 0xa9a9884f3721a99e, 0x2a2a6754824d2aa8, 0xbbbb0a6b6db1bbd6, 0xc1c1879fe246c123, 0x5353f1a602a25351, 0xdcdc72a58baedc57, 0x0b0b531627580b2c, 0x9d9d0127d39c9d4e, 0x6c6c2bd8c1476cad, 0x3131a462f59531c4, 0x7474f3e8b98774cd, 0xf6f615f109e3f6ff, 0x46464c8c430a4605, 0xacaca5452609ac8a, 0x8989b50f973c891e, 0x1414b42844a01450, 0xe1e1badf425be1a3, 0x1616a62c4eb01658, 0x3a3af774d2cd3ae8, 0x696906d2d06f69b9, 0x090941122d480924, 0x7070d7e0ada770dd, 0xb6b66f7154d9b6e2, 0xd0d01ebdb7ced067, 0xededd6c77e3bed93, 0xcccce285db2ecc17, 0x42426884572a4215, 0x98982c2dc2b4985a, 0xa4a4ed550e49a4aa, 0x28287550885d28a0, 0x5c5c86b831da5c6d, 0xf8f86bed3f93f8c7, 0x8686c211a4448622, }, { 0x18d83078c0186018, 0x232646af05238c23, 0xc6b891f97ec63fc6, 0xe8fbcd6f13e887e8, 0x87cb13a14c872687, 0xb8116d62a9b8dab8, 0x0109020508010401, 0x4f0d9e6e424f214f, 0x369b6ceead36d836, 0xa6ff510459a6a2a6, 0xd20cb9bdded26fd2, 0xf50ef706fbf5f3f5, 0x7996f280ef79f979, 0x6f30dece5f6fa16f, 0x916d3feffc917e91, 0x52f8a407aa525552, 0x6047c0fd27609d60, 0xbc35657689bccabc, 0x9b372bcdac9b569b, 0x8e8a018c048e028e, 0xa3d25b1571a3b6a3, 0x0c6c183c600c300c, 0x7b84f68aff7bf17b, 0x35806ae1b535d435, 0x1df53a69e81d741d, 0xe0b3dd4753e0a7e0, 0xd721b3acf6d77bd7, 0xc29c99ed5ec22fc2, 0x2e435c966d2eb82e, 0x4b29967a624b314b, 0xfe5de121a3fedffe, 0x57d5ae1682574157, 0x15bd2a41a8155415, 0x77e8eeb69f77c177, 0x37926eeba537dc37, 0xe59ed7567be5b3e5, 0x9f1323d98c9f469f, 0xf023fd17d3f0e7f0, 0x4a20947f6a4a354a, 0xda44a9959eda4fda, 0x58a2b025fa587d58, 0xc9cf8fca06c903c9, 0x297c528d5529a429, 0x0a5a1422500a280a, 0xb1507f4fe1b1feb1, 0xa0c95d1a69a0baa0, 0x6b14d6da7f6bb16b, 0x85d917ab5c852e85, 0xbd3c677381bdcebd, 0x5d8fba34d25d695d, 0x1090205080104010, 0xf407f503f3f4f7f4, 0xcbdd8bc016cb0bcb, 0x3ed37cc6ed3ef83e, 0x052d0a1128051405, 0x6778cee61f678167, 0xe497d55373e4b7e4, 0x27024ebb25279c27, 0x4173825832411941, 0x8ba70b9d2c8b168b, 0xa7f6530151a7a6a7, 0x7db2fa94cf7de97d, 0x954937fbdc956e95, 0xd856ad9f8ed847d8, 0xfb70eb308bfbcbfb, 0xeecdc17123ee9fee, 0x7cbbf891c77ced7c, 0x6671cce317668566, 0xdd7ba78ea6dd53dd, 0x17af2e4bb8175c17, 0x47458e4602470147, 0x9e1a21dc849e429e, 0xcad489c51eca0fca, 0x2d585a99752db42d, 0xbf2e637991bfc6bf, 0x073f0e1b38071c07, 0xadac472301ad8ead, 0x5ab0b42fea5a755a, 0x83ef1bb56c833683, 0x33b666ff8533cc33, 0x635cc6f23f639163, 0x0212040a10020802, 0xaa93493839aa92aa, 0x71dee2a8af71d971, 0xc8c68dcf0ec807c8, 0x19d1327dc8196419, 0x493b927072493949, 0xd95faf9a86d943d9, 0xf231f91dc3f2eff2, 0xe3a8db484be3abe3, 0x5bb9b62ae25b715b, 0x88bc0d9234881a88, 0x9a3e29c8a49a529a, 0x260b4cbe2d269826, 0x32bf64fa8d32c832, 0xb0597d4ae9b0fab0, 0xe9f2cf6a1be983e9, 0x0f771e33780f3c0f, 0xd533b7a6e6d573d5, 0x80f41dba74803a80, 0xbe27617c99bec2be, 0xcdeb87de26cd13cd, 0x348968e4bd34d034, 0x483290757a483d48, 0xff54e324abffdbff, 0x7a8df48ff77af57a, 0x90643deaf4907a90, 0x5f9dbe3ec25f615f, 0x203d40a01d208020, 0x680fd0d56768bd68, 0x1aca3472d01a681a, 0xaeb7412c19ae82ae, 0xb47d755ec9b4eab4, 0x54cea8199a544d54, 0x937f3be5ec937693, 0x222f44aa0d228822, 0x6463c8e907648d64, 0xf12aff12dbf1e3f1, 0x73cce6a2bf73d173, 0x1282245a90124812, 0x407a805d3a401d40, 0x0848102840082008, 0xc3959be856c32bc3, 0xecdfc57b33ec97ec, 0xdb4dab9096db4bdb, 0xa1c05f1f61a1bea1, 0x8d9107831c8d0e8d, 0x3dc87ac9f53df43d, 0x975b33f1cc976697, 0x0000000000000000, 0xcff983d436cf1bcf, 0x2b6e5687452bac2b, 0x76e1ecb39776c576, 0x82e619b064823282, 0xd628b1a9fed67fd6, 0x1bc33677d81b6c1b, 0xb574775bc1b5eeb5, 0xafbe432911af86af, 0x6a1dd4df776ab56a, 0x50eaa00dba505d50, 0x45578a4c12450945, 0xf338fb18cbf3ebf3, 0x30ad60f09d30c030, 0xefc4c3742bef9bef, 0x3fda7ec3e53ffc3f, 0x55c7aa1c92554955, 0xa2db591079a2b2a2, 0xeae9c96503ea8fea, 0x656acaec0f658965, 0xba036968b9bad2ba, 0x2f4a5e93652fbc2f, 0xc08e9de74ec027c0, 0xde60a181bede5fde, 0x1cfc386ce01c701c, 0xfd46e72ebbfdd3fd, 0x4d1f9a64524d294d, 0x927639e0e4927292, 0x75faeabc8f75c975, 0x06360c1e30061806, 0x8aae0998248a128a, 0xb24b7940f9b2f2b2, 0xe685d15963e6bfe6, 0x0e7e1c36700e380e, 0x1fe73e63f81f7c1f, 0x6255c4f737629562, 0xd43ab5a3eed477d4, 0xa8814d3229a89aa8, 0x965231f4c4966296, 0xf962ef3a9bf9c3f9, 0xc5a397f666c533c5, 0x25104ab135259425, 0x59abb220f2597959, 0x84d015ae54842a84, 0x72c5e4a7b772d572, 0x39ec72ddd539e439, 0x4c1698615a4c2d4c, 0x5e94bc3bca5e655e, 0x789ff085e778fd78, 0x38e570d8dd38e038, 0x8c980586148c0a8c, 0xd117bfb2c6d163d1, 0xa5e4570b41a5aea5, 0xe2a1d94d43e2afe2, 0x614ec2f82f619961, 0xb3427b45f1b3f6b3, 0x213442a515218421, 0x9c0825d6949c4a9c, 0x1eee3c66f01e781e, 0x4361865222431143, 0xc7b193fc76c73bc7, 0xfc4fe52bb3fcd7fc, 0x0424081420041004, 0x51e3a208b2515951, 0x99252fc7bc995e99, 0x6d22dac44f6da96d, 0x0d651a39680d340d, 0xfa79e93583facffa, 0xdf69a384b6df5bdf, 0x7ea9fc9bd77ee57e, 0x241948b43d249024, 0x3bfe76d7c53bec3b, 0xab9a4b3d31ab96ab, 0xcef081d13ece1fce, 0x1199225588114411, 0x8f8303890c8f068f, 0x4e049c6b4a4e254e, 0xb7667351d1b7e6b7, 0xebe0cb600beb8beb, 0x3cc178ccfd3cf03c, 0x81fd1fbf7c813e81, 0x944035fed4946a94, 0xf71cf30cebf7fbf7, 0xb9186f67a1b9deb9, 0x138b265f98134c13, 0x2c51589c7d2cb02c, 0xd305bbb8d6d36bd3, 0xe78cd35c6be7bbe7, 0x6e39dccb576ea56e, 0xc4aa95f36ec437c4, 0x031b060f18030c03, 0x56dcac138a564556, 0x445e88491a440d44, 0x7fa0fe9edf7fe17f, 0xa9884f3721a99ea9, 0x2a6754824d2aa82a, 0xbb0a6b6db1bbd6bb, 0xc1879fe246c123c1, 0x53f1a602a2535153, 0xdc72a58baedc57dc, 0x0b531627580b2c0b, 0x9d0127d39c9d4e9d, 0x6c2bd8c1476cad6c, 0x31a462f59531c431, 0x74f3e8b98774cd74, 0xf615f109e3f6fff6, 0x464c8c430a460546, 0xaca5452609ac8aac, 0x89b50f973c891e89, 0x14b42844a0145014, 0xe1badf425be1a3e1, 0x16a62c4eb0165816, 0x3af774d2cd3ae83a, 0x6906d2d06f69b969, 0x0941122d48092409, 0x70d7e0ada770dd70, 0xb66f7154d9b6e2b6, 0xd01ebdb7ced067d0, 0xedd6c77e3bed93ed, 0xcce285db2ecc17cc, 0x426884572a421542, 0x982c2dc2b4985a98, 0xa4ed550e49a4aaa4, 0x287550885d28a028, 0x5c86b831da5c6d5c, 0xf86bed3f93f8c7f8, 0x86c211a444862286, } }; void whirlpool::update(const unsigned char* data, size_t len) { if (pos && pos + len >= 64) { memcpy(m + pos, data, 64 - pos); transfunc(m, 1); len -= 64 - pos; total += (64 - pos) * 8; data += 64 - pos; pos = 0; } if (len >= 64) { size_t blocks = len / 64; size_t bytes = blocks * 64; transfunc((void*)(data), blocks); len -= bytes; total += (bytes)* 8; data += bytes; } memcpy(m+pos, data, len); pos += len; total += len * 8; } void whirlpool::final(unsigned char* hash) { #ifdef CPPCRYPTO_DEBUG dump_state("pre-final", h); #endif uint64_t mlen = swap_uint64(total); m[pos++] = 0x80; if (pos > 32) { memset(m + pos, 0, 64 - pos); transfunc(m, 1); pos = 0; } memset(m + pos, 0, 56 - pos); memcpy(m + (64 - 8), &mlen, 64 / 8); transfunc(m, 1); memcpy(hash, h, hashsize() / 8); #ifdef CPPCRYPTO_DEBUG dump_state("post-final", h); #endif } void whirlpool::init() { pos = 0; total = 0; memset(h, 0, sizeof(uint64_t) * 8); #ifdef CPPCRYPTO_DEBUG dump_state("init", h); #endif }; void whirlpool::transform(void* mp, uint64_t num_blks) { for (uint64_t b = 0; b < num_blks; b++) { union { unsigned char ch[64]; unsigned long long ll[8]; } K, state; unsigned long long L[8]; int r, i; i = 0; do state.ll[i] = (K.ll[i] = h[i]) ^ ((unsigned long long*)mp)[i]; while (++i < 8); r = 0; do { L[0] = T[0][K.ch[0 * 8 + 0]] ^ T[1][K.ch[7 * 8 + 1]] ^ T[2][K.ch[6 * 8 + 2]] ^ T[3][K.ch[5 * 8 + 3]] ^ T[4][K.ch[4 * 8 + 4]] ^ T[5][K.ch[3 * 8 + 5]] ^ T[6][K.ch[2 * 8 + 6]] ^ T[7][K.ch[1 * 8 + 7]] ^ RC[r]; L[1] = T[0][K.ch[1 * 8 + 0]] ^ T[1][K.ch[0 * 8 + 1]] ^ T[2][K.ch[7 * 8 + 2]] ^ T[3][K.ch[6 * 8 + 3]] ^ T[4][K.ch[5 * 8 + 4]] ^ T[5][K.ch[4 * 8 + 5]] ^ T[6][K.ch[3 * 8 + 6]] ^ T[7][K.ch[2 * 8 + 7]]; L[2] = T[0][K.ch[2 * 8 + 0]] ^ T[1][K.ch[1 * 8 + 1]] ^ T[2][K.ch[0 * 8 + 2]] ^ T[3][K.ch[7 * 8 + 3]] ^ T[4][K.ch[6 * 8 + 4]] ^ T[5][K.ch[5 * 8 + 5]] ^ T[6][K.ch[4 * 8 + 6]] ^ T[7][K.ch[3 * 8 + 7]]; L[3] = T[0][K.ch[3 * 8 + 0]] ^ T[1][K.ch[2 * 8 + 1]] ^ T[2][K.ch[1 * 8 + 2]] ^ T[3][K.ch[0 * 8 + 3]] ^ T[4][K.ch[7 * 8 + 4]] ^ T[5][K.ch[6 * 8 + 5]] ^ T[6][K.ch[5 * 8 + 6]] ^ T[7][K.ch[4 * 8 + 7]]; L[4] = T[0][K.ch[4 * 8 + 0]] ^ T[1][K.ch[3 * 8 + 1]] ^ T[2][K.ch[2 * 8 + 2]] ^ T[3][K.ch[1 * 8 + 3]] ^ T[4][K.ch[0 * 8 + 4]] ^ T[5][K.ch[7 * 8 + 5]] ^ T[6][K.ch[6 * 8 + 6]] ^ T[7][K.ch[5 * 8 + 7]]; L[5] = T[0][K.ch[5 * 8 + 0]] ^ T[1][K.ch[4 * 8 + 1]] ^ T[2][K.ch[3 * 8 + 2]] ^ T[3][K.ch[2 * 8 + 3]] ^ T[4][K.ch[1 * 8 + 4]] ^ T[5][K.ch[0 * 8 + 5]] ^ T[6][K.ch[7 * 8 + 6]] ^ T[7][K.ch[6 * 8 + 7]]; L[6] = T[0][K.ch[6 * 8 + 0]] ^ T[1][K.ch[5 * 8 + 1]] ^ T[2][K.ch[4 * 8 + 2]] ^ T[3][K.ch[3 * 8 + 3]] ^ T[4][K.ch[2 * 8 + 4]] ^ T[5][K.ch[1 * 8 + 5]] ^ T[6][K.ch[0 * 8 + 6]] ^ T[7][K.ch[7 * 8 + 7]]; L[7] = T[0][K.ch[7 * 8 + 0]] ^ T[1][K.ch[6 * 8 + 1]] ^ T[2][K.ch[5 * 8 + 2]] ^ T[3][K.ch[4 * 8 + 3]] ^ T[4][K.ch[3 * 8 + 4]] ^ T[5][K.ch[2 * 8 + 5]] ^ T[6][K.ch[1 * 8 + 6]] ^ T[7][K.ch[0 * 8 + 7]]; L[0] = (K.ll[0] = L[0]) ^ T[0][state.ch[0 * 8 + 0]] ^ T[1][state.ch[7 * 8 + 1]] ^ T[2][state.ch[6 * 8 + 2]] ^ T[3][state.ch[5 * 8 + 3]] ^ T[4][state.ch[4 * 8 + 4]] ^ T[5][state.ch[3 * 8 + 5]] ^ T[6][state.ch[2 * 8 + 6]] ^ T[7][state.ch[1 * 8 + 7]]; L[1] = (K.ll[1] = L[1]) ^ T[0][state.ch[1 * 8 + 0]] ^ T[1][state.ch[0 * 8 + 1]] ^ T[2][state.ch[7 * 8 + 2]] ^ T[3][state.ch[6 * 8 + 3]] ^ T[4][state.ch[5 * 8 + 4]] ^ T[5][state.ch[4 * 8 + 5]] ^ T[6][state.ch[3 * 8 + 6]] ^ T[7][state.ch[2 * 8 + 7]]; L[2] = (K.ll[2] = L[2]) ^ T[0][state.ch[2 * 8 + 0]] ^ T[1][state.ch[1 * 8 + 1]] ^ T[2][state.ch[0 * 8 + 2]] ^ T[3][state.ch[7 * 8 + 3]] ^ T[4][state.ch[6 * 8 + 4]] ^ T[5][state.ch[5 * 8 + 5]] ^ T[6][state.ch[4 * 8 + 6]] ^ T[7][state.ch[3 * 8 + 7]]; L[3] = (K.ll[3] = L[3]) ^ T[0][state.ch[3 * 8 + 0]] ^ T[1][state.ch[2 * 8 + 1]] ^ T[2][state.ch[1 * 8 + 2]] ^ T[3][state.ch[0 * 8 + 3]] ^ T[4][state.ch[7 * 8 + 4]] ^ T[5][state.ch[6 * 8 + 5]] ^ T[6][state.ch[5 * 8 + 6]] ^ T[7][state.ch[4 * 8 + 7]]; L[4] = (K.ll[4] = L[4]) ^ T[0][state.ch[4 * 8 + 0]] ^ T[1][state.ch[3 * 8 + 1]] ^ T[2][state.ch[2 * 8 + 2]] ^ T[3][state.ch[1 * 8 + 3]] ^ T[4][state.ch[0 * 8 + 4]] ^ T[5][state.ch[7 * 8 + 5]] ^ T[6][state.ch[6 * 8 + 6]] ^ T[7][state.ch[5 * 8 + 7]]; L[5] = (K.ll[5] = L[5]) ^ T[0][state.ch[5 * 8 + 0]] ^ T[1][state.ch[4 * 8 + 1]] ^ T[2][state.ch[3 * 8 + 2]] ^ T[3][state.ch[2 * 8 + 3]] ^ T[4][state.ch[1 * 8 + 4]] ^ T[5][state.ch[0 * 8 + 5]] ^ T[6][state.ch[7 * 8 + 6]] ^ T[7][state.ch[6 * 8 + 7]]; L[6] = (K.ll[6] = L[6]) ^ T[0][state.ch[6 * 8 + 0]] ^ T[1][state.ch[5 * 8 + 1]] ^ T[2][state.ch[4 * 8 + 2]] ^ T[3][state.ch[3 * 8 + 3]] ^ T[4][state.ch[2 * 8 + 4]] ^ T[5][state.ch[1 * 8 + 5]] ^ T[6][state.ch[0 * 8 + 6]] ^ T[7][state.ch[7 * 8 + 7]]; L[7] = (K.ll[7] = L[7]) ^ T[0][state.ch[7 * 8 + 0]] ^ T[1][state.ch[6 * 8 + 1]] ^ T[2][state.ch[5 * 8 + 2]] ^ T[3][state.ch[4 * 8 + 3]] ^ T[4][state.ch[3 * 8 + 4]] ^ T[5][state.ch[2 * 8 + 5]] ^ T[6][state.ch[1 * 8 + 6]] ^ T[7][state.ch[0 * 8 + 7]]; memcpy(state.ll, L, sizeof(L)); } while (++r < 10); i = 0; do h[i] ^= L[i] ^ ((unsigned long long*)mp)[i]; while (++i < 8); mp = ((unsigned long long*)mp)+8; } } whirlpool::whirlpool() { #ifndef NO_OPTIMIZED_VERSIONS #ifndef _M_X64 if (cpu_info::sse2()) transfunc = [this](void* mp, uint64_t num_blks) { for (uint64_t b = 0; b < num_blks; b++) whirlpool_compress_asm((unsigned char*)h.get(), ((const unsigned char*)mp)+b*64); }; else #endif #endif #ifdef NO_BIND_TO_FUNCTION transfunc = [this](void* mp, uint64_t num_blks) { transform(mp, num_blks); }; #else transfunc = std::bind(&whirlpool::transform, this, std::placeholders::_1, std::placeholders::_2); #endif } whirlpool::~whirlpool() { clear(); } void whirlpool::clear() { zero_memory(h.get(), h.bytes()); zero_memory(m.get(), m.bytes()); } }
70.98557
252
0.814791
crashdemons
260e6d3bdac5631718004f8e99dd6e4539deca0f
2,655
cpp
C++
src/base64.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
1
2015-10-10T14:05:56.000Z
2015-10-10T14:05:56.000Z
src/base64.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
null
null
null
src/base64.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
null
null
null
// Part of the Jade Engine -- Copyright (c) Christian Neumüller 2012--2013 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #include "base64.hpp" #include <array> #include <algorithm> #include <cassert> #include <cstdint> #include <cstring> namespace { static base64::byte charToByte(base64::byte c) { switch(c) { case '+': return 62; case '/': return 63; case '=': return -1; default: if (c >= '0' && c <= '9') return c - '0' + 52; if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; throw base64::InvalidCharacter(); } } } // anonymous namespace namespace base64 { std::vector<byte> decode(char const* encoded) { return decode(encoded, std::strlen(encoded)); } std::vector<byte> decode(std::vector<byte> const& encoded) { if (encoded.empty()) return std::vector<byte>(); return decode(&encoded[0], encoded.size()); } std::vector<byte> decode(std::string const& encoded) { return decode(encoded.data(), encoded.size()); } // Could be optimized: call transform once on encoded std::vector<byte> decode(byte const* encoded, std::size_t byteCount) { std::vector<byte> result; if (byteCount == 0) return result; assert(encoded); if (byteCount % 4 != 0) throw InvalidLength(); result.reserve(byteCount * 3 / 4 + 2); for (std::size_t i = 0; i < byteCount; i += 4) { std::array<byte, 4> inBytes; std::transform( encoded + i, encoded + i + 4, inBytes.begin(), charToByte); std::array<byte, 3> outBytes; outBytes[0] = static_cast<byte>(inBytes[0] << 2 | inBytes[1] >> 4); outBytes[1] = static_cast<byte>(inBytes[1] << 4 | inBytes[2] >> 2); outBytes[2] = static_cast<byte>(inBytes[2] << 6 | inBytes[3]); if (i + 4 == byteCount) { std::size_t discard = 0; if (inBytes[2] == -1) { ++discard; if (inBytes[1] == -1) ++discard; } else if (inBytes[1] == -1) { throw InvalidCharacter(); } result.insert(result.end(), outBytes.begin(), outBytes.end() - discard); } else if (inBytes[0] == -1 || inBytes[1] == -1) { throw InvalidCharacter(); } else { result.insert(result.end(), outBytes.begin(), outBytes.end()); } } return result; } } // namespace base64
26.818182
84
0.534087
Oberon00
261109756f4725a31c8361d39f975f87b8415af7
3,449
cpp
C++
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/APSParser/elements/APSDictionary.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/APSParser/elements/APSDictionary.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/APSParser/elements/APSDictionary.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File APSDictionary.cpp * Author Y.H Mun * * -------------------------------------------------------------------------- * * Copyright (c) 2012 ArtPig Software LLC * * http://www.artpigsoft.com * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * Contact Email: xmsoft77@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 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 in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "extensions/CCArtPig/APSDictionary.h" #include "extensions/CCArtPig/APSString.h" NS_APS_BEGIN APSDictionary::~APSDictionary ( KDvoid ) { this->clear ( ); } APSDictionary* APSDictionary::dictionary ( KDvoid ) { APSDictionary* pRet = new APSDictionary ( ); pRet->autorelease ( ); return pRet; } KDvoid APSDictionary::setObjectForKey ( APSObject* pObject, const std::string& sKey ) { APSDictionaryStorage::iterator iter = this->m_aTable.find ( sKey ); if ( iter != this->m_aTable.end ( ) ) { if ( iter->second != pObject ) { APS_SAFE_RETAIN ( pObject ); APS_SAFE_RELEASE ( iter->second ); iter->second = pObject; } } else { APS_SAFE_RETAIN ( pObject ); this->m_aTable [ sKey ] = pObject; } } APSObject* APSDictionary::getObjectForKey ( const std::string& sKey ) { return this->m_aTable [ sKey ]; } // Adds to the receiving dictionary the entries from another dictionary. KDvoid APSDictionary::addEntriesFromDictionary ( const APSDictionary* pOtherDictionary ) { // ! Although otherDictionary is converted to none constant object, this loop only accesses its' properties without any change to otherDictionary. APS_FOREACH ( APSDictionaryStorage, ( (APSDictionary) *pOtherDictionary ), iter ) { this->setObjectForKey ( ( *iter ).second, ( *iter ).first ); } } KDvoid APSDictionary::removeForKey ( const std::string& sKey ) { APSDictionaryStorage::iterator iter = this->m_aTable.find ( sKey ); if ( iter != this->m_aTable.end ( ) ) { APS_SAFE_RELEASE ( iter->second ); this->m_aTable.erase ( iter ); } } KDvoid APSDictionary::clear ( KDvoid ) { APS_FOREACH ( APSDictionaryStorage, this->m_aTable, iter ) { APS_SAFE_RELEASE ( ( *iter ).second ); } this->m_aTable.clear ( ); } NS_APS_END
28.741667
150
0.574079
mcodegeeks
2611e2856e3ac8d7acd24edab7ee13f10e239bdc
2,660
cpp
C++
src/data/SourceCodeLocationsModel.cpp
vitorjna/LoggerClient
b447f36224e98919045138bb08a849df211e5491
[ "MIT" ]
null
null
null
src/data/SourceCodeLocationsModel.cpp
vitorjna/LoggerClient
b447f36224e98919045138bb08a849df211e5491
[ "MIT" ]
null
null
null
src/data/SourceCodeLocationsModel.cpp
vitorjna/LoggerClient
b447f36224e98919045138bb08a849df211e5491
[ "MIT" ]
null
null
null
#include "SourceCodeLocationsModel.h" #include "util/NetworkUtils.h" SourceCodeLocationsModel::SourceCodeLocationsModel(QObject *parent) : StandardItemModel(parent) { setupHeader(); } SourceCodeLocationsModel::~SourceCodeLocationsModel() = default; QString SourceCodeLocationsModel::getColumnName(const SourceCodeLocationsEnum::Columns eColumn) { switch (eColumn) { case SourceCodeLocationsEnum::COLUMN_PROJECT_NAME: return tr("Project"); case SourceCodeLocationsEnum::COLUMN_SOURCE_PATH: return tr("Path"); case SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS: return QLatin1String(""); } } void SourceCodeLocationsModel::setupHeader() { this->setColumnCount(SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS); for (int nIndex = 0; nIndex < SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS; ++nIndex) { this->setHeaderData(nIndex, Qt::Horizontal, getColumnName(static_cast<SourceCodeLocationsEnum::Columns>(nIndex)), Qt::DisplayRole); } } QVariant SourceCodeLocationsModel::data(const QModelIndex &index, int role) const { switch (role) { case Qt::TextAlignmentRole: if (index.column() == SourceCodeLocationsEnum::COLUMN_PROJECT_NAME) { return Qt::AlignCenter; } else { static const QVariant myAlignCenterLeft(Qt::AlignVCenter | Qt::AlignLeft); return myAlignCenterLeft; } // case Qt::BackgroundRole: { // switch (static_cast<SourceCodeLocationsEnum::Columns>(index.column())) { // case NetworkAddressesEnum::COLUMN_ADDRESS_NAME: // break; // case NetworkAddressesEnum::COLUMN_SERVER_IP: // if (NetworkUtils::isIpV4Address(this->item(index.row(), NetworkAddressesEnum::COLUMN_SERVER_IP)->text()) == false) { // return myBrushError; // } // break; // case NetworkAddressesEnum::COLUMN_SERVER_PORT: // if (NetworkUtils::isValidPort(this->item(index.row(), NetworkAddressesEnum::COLUMN_SERVER_PORT)->text()) == false) { // return myBrushError; // } // break; // case SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS: // break; // } // break; // } default: return StandardItemModel::data(index, role); } return StandardItemModel::data(index, role); }
32.048193
138
0.59812
vitorjna
2612601b86ac87bb1928207ed4b547cdeb80a239
3,461
cc
C++
base/io_buffer_test.cc
wuyongchn/trpc
ee492ce8c40ef6a156f298aa295ed4e1fe4b4545
[ "BSD-2-Clause" ]
null
null
null
base/io_buffer_test.cc
wuyongchn/trpc
ee492ce8c40ef6a156f298aa295ed4e1fe4b4545
[ "BSD-2-Clause" ]
null
null
null
base/io_buffer_test.cc
wuyongchn/trpc
ee492ce8c40ef6a156f298aa295ed4e1fe4b4545
[ "BSD-2-Clause" ]
null
null
null
#include "base/io_buffer.h" #include "base/scoped_refptr.h" #include <glog/logging.h> #include <gtest/gtest.h> #include <string.h> namespace pbrpc { namespace unittest { TEST(IOBufferWithSizeTest, TestConstructor) { const int kBufSize = 128; auto buffer = MakeRefCounted<IOBufferWithSize>(kBufSize); } TEST(IOBufferWithSizeTest, TestSize) { const int kBufSize = 128; auto buffer = MakeRefCounted<IOBufferWithSize>(kBufSize); CHECK_EQ(kBufSize, buffer->size()); } TEST(StringIOBufferTest, TestConstructor) { std::string data; auto buffer = MakeRefCounted<StringIOBuffer>(data); } TEST(StringIOBufferTest, TestSize) { std::string data("test"); auto buffer = MakeRefCounted<StringIOBuffer>(data); CHECK_EQ(data.size(), buffer->size()); } TEST(DrainableIOBufferTest, TestConstructor) { const int kBufSize = 128; auto base = MakeRefCounted<IOBuffer>(kBufSize); auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize); } TEST(DrainableIOBufferTest, TestDidConsume) { const int kBufSize = 128; auto base = MakeRefCounted<IOBuffer>(kBufSize); auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize); const int kBatchSize = 32; buffer->DidConsume(kBatchSize); CHECK_EQ(kBatchSize, buffer->BytesConsumed()); CHECK_EQ(kBufSize - kBatchSize, buffer->BytesRemaining()); } TEST(DrainableIOBufferTest, TestSetOffset) { const int kBufSize = 128; auto base = MakeRefCounted<IOBuffer>(kBufSize); auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize); const int kBatchSize = 32; buffer->SetOffset(kBatchSize); CHECK_EQ(kBatchSize, buffer->BytesConsumed()); CHECK_EQ(kBufSize - kBatchSize, buffer->BytesRemaining()); } TEST(DrainableIOBufferTest, TestSetOffset2) { std::string data("this is test"); auto base = MakeRefCounted<StringIOBuffer>(data); auto buffer = MakeRefCounted<DrainableIOBuffer>(base, data.size()); const int kBatchSize = 4; buffer->SetOffset(kBatchSize); std::string remaining(buffer->data(), data.size() - kBatchSize); CHECK_EQ(data.substr(kBatchSize), remaining); } TEST(GrowableIOBufferTest, TestConstructor) { auto buffer = MakeRefCounted<GrowableIOBuffer>(); CHECK_EQ(0, buffer->capacity()); CHECK_EQ(0, buffer->offset()); CHECK_EQ(0, buffer->RemainingCapacity()); } TEST(GrowableIOBufferTest, TestSetCapacity) { auto buffer = MakeRefCounted<GrowableIOBuffer>(); const int kCapacity = 128; buffer->SetCapacity(kCapacity); CHECK_EQ(kCapacity, buffer->capacity()); CHECK_EQ(0, buffer->offset()); CHECK_EQ(kCapacity, buffer->RemainingCapacity()); } TEST(GrowableIOBufferTest, TestSetOffset) { auto buffer = MakeRefCounted<GrowableIOBuffer>(); const int kCapacity = 128; buffer->SetCapacity(kCapacity); const int kBatchSize = 32; buffer->set_offset(kBatchSize); CHECK_EQ(kCapacity, buffer->capacity()); CHECK_EQ(kBatchSize, buffer->offset()); CHECK_EQ(kCapacity - kBatchSize, buffer->RemainingCapacity()); } TEST(GrowableIOBufferTest, TestStartOfBuffer) { auto buffer = MakeRefCounted<GrowableIOBuffer>(); buffer->SetCapacity(8); std::string data("test"); memcpy(buffer->StartOfBuffer(), data.data(), data.size()); buffer->SetCapacity(32); std::string buf(buffer->data(), data.size()); CHECK_EQ(buf, data); } } // namespace unittest } // namespace pbrpc int main(int argc, char* argv[]) { ::google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.359649
69
0.737937
wuyongchn
2613c230b86e3ace3ee1dc68d5649ce109d96676
4,009
cpp
C++
SPOJ/SPOJ CERC07K - Key Task.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
2
2020-04-23T17:47:27.000Z
2020-04-25T19:40:50.000Z
SPOJ/SPOJ CERC07K - Key Task.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
null
null
null
SPOJ/SPOJ CERC07K - Key Task.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
1
2020-06-14T20:52:39.000Z
2020-06-14T20:52:39.000Z
#include<bits/stdc++.h> #include<iostream> #include<string> #include<vector> #include<cmath> #include<list> #include <algorithm> #include<vector> #include<set> #include <cctype> #include <cstring> #include <cstdio> #include<queue> #include<stack> #include<bitset> #include<time.h> #include<fstream> /******************************************************/ using namespace std; /********************define***************************/ #define ll long long #define ld long double #define all(v) ((v).begin()), ((v).end()) #define for_(vec) for(int i=0;i<(int)vec.size();i++) #define lp(j,n) for(int i=j;i<(int)(n);i++) #define rlp(j,n) for(int i=j;i>=(int)(n);i--) #define clr(arr,x) memset(arr,x,sizeof(arr)) #define fillstl(arr,X) fill(arr.begin(),arr.end(),X) #define pb push_back #define mp make_pair #define print_vector(X) for(int i=0;i<X.size();i++) /********************************************************/ typedef vector<int> vi; typedef vector<pair<int, int> > vii; typedef vector<vector<int> > vvi; typedef vector<ll> vl; /***********************function************************/ void fast() { ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0); } void online_judge() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } const int flag_max=0x3f3f3f3f; const ll OO=1e15+9 ; const double EPS = (1e-7); int dcmp(double x, double y) { return fabs(x-y) <= EPS ? 0 : x < y ? -1 : 1; } ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } ll Power(ll n,ll deg) { if(!deg)return 1; else if(deg & 1) return Power(n,deg-1)*n; else { ll half=Power(n,deg/2); return half*half; } } /***********************main_problem****************************/ int dx[4]= {1,-1,0,0}; int dy[4]= {0,0,-1,1}; char arr[100][100]; int visited[100][100][17]; int dis[100][100][17]; int n,m; bool valid(int x,int y) { return x>=0 && x<n && y>=0 && y<m; } bool can(int x,int y,int mask) { // "&" compair bits 01 return ( (arr[x][y]=='R' && mask & 1) || (arr[x][y]=='G' && mask & 2 ) || (arr[x][y]=='B' && mask & 4) || (arr[x][y]=='Y' && mask & 8) || arr[x][y]=='*' || arr[x][y]=='X' || arr[x][y]=='.' || arr[x][y]=='r' || arr[x][y]=='g' || arr[x][y]=='y' || arr[x][y]=='b' ); } string BFS(int i,int j) { queue<pair<pair<int,int>,int> >q; int mask=0,ans=-1; q.push({{i,j},mask}); visited[i][j][mask]=1; while(!q.empty()) { pair<pair<int,int>,int> now=q.front(); q.pop(); mask=now.second; int x=now.first.first,y=now.first.second; if(arr[x][y]=='X') { ans=dis[x][y][mask]; break; } else if(arr[x][y]=='r') mask|=1; else if ( arr[x][y] == 'g') mask|=2; else if (arr[x][y]=='b') mask|=4; else if (arr[x][y]=='y') mask|=8; for(int k=0; k<4; k++) { int new_x=x+dx[k],new_y=y+dy[k]; if(!visited[new_x][new_y][mask] && valid(new_x,new_y) && can(new_x,new_y,mask) ) { //"now.second" old mask mark it visited[new_x][new_y][now.second]=1; dis[new_x][new_y][mask]=dis[x][y][now.second]+1; q.push({{new_x,new_y},mask}); } } } return ans==-1 ?"The poor student is trapped!":"Escape possible in "+to_string(ans)+" steps."; } /***********𝓢𝓣𝓞𝓟 𝓦𝓗𝓔𝓝 𝓨𝓞𝓤 𝓡𝓔𝓐𝓒𝓗 𝓣𝓗𝓔 𝓒𝓞𝓝𝓒𝓔𝓟𝓣 𝓞𝓕 𝓓𝓞𝓝'𝓣 𝓢𝓣𝓞𝓟******************/ int main() { fast(); while( cin>>n>>m && n && m) { int x_star,y_star; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>arr[i][j]; if(arr[i][j]=='*')x_star=i,y_star=j; } } clr(visited,0); clr(dis,0); cout<<BFS(x_star,y_star)<<'\n'; } return 0; }
20.880208
116
0.467199
bishoy-magdy
2617d234f36327f4a417092231cbeac3db3a699b
1,687
cpp
C++
src/Arduino/ADXL345/example_grativity_to_tilt.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
src/Arduino/ADXL345/example_grativity_to_tilt.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
src/Arduino/ADXL345/example_grativity_to_tilt.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <stdint.h> #include <Math.h> #include "ADXL345.h" #define OFFSETX 270 #define OFFSETY 270 ADXL345 accel; void setup() { Serial.begin(9600); Wire.begin(); accel.begin(); delay(1500); } void loop() { // Data acquisition from accelerometer float x = (int16_t) accel.getXAccel(); float y = (int16_t) accel.getYAccel(); float z = (int16_t) accel.getZAccel(); // For around X axis... // Turning gravital vector components into angle in RAD float angRadX = atan2(z, y); // Turning angle in RAD into DEGREE float angDegX = angRadX * (180.0/PI); // Scale transformation: [-180, +180] to [0, 360[ if(angDegX > -180 && angDegX < 0) { angDegX = angDegX * (-1); angDegX = (180.0 - angDegX); angDegX = angDegX + 180.0; } // Offset if((angDegX + OFFSETX) >= 360.0) angDegX = (angDegX + OFFSETX) - 360.0; else angDegX = angDegX + OFFSETX; // For around Y axis... // Turning gravital vector components int angle in RAD float angRadY = atan2(z, x); // Turning angle in RAD into DEGREE float angDegY = angRadY * (180.0/PI); // Scale transformation: [-180, +180] to [0, 360[ if(angDegY > -180 && angDegY < 0) { angDegY = angDegY * (-1); angDegY = (180.0 - angDegY); angDegY = angDegY + 180.0; } // Offset if((angDegY + OFFSETY) >= 360.0) angDegY = (angDegY + OFFSETY) - 360.0; else angDegY = angDegY + OFFSETY; // For presentation... Serial.println(angDegX); Serial.println(angDegY); Serial.println(); delay(500); }
22.197368
59
0.571429
smurilogs
2619264756c7ffa89a744f064279c8a85a05d335
3,117
cc
C++
src/sim/parsim/cplaceholdermod.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
15
2021-08-20T08:10:01.000Z
2022-03-24T21:24:50.000Z
src/sim/parsim/cplaceholdermod.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
1
2022-03-30T09:03:39.000Z
2022-03-30T09:03:39.000Z
src/sim/parsim/cplaceholdermod.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
3
2021-08-20T08:10:34.000Z
2021-12-02T06:15:02.000Z
//========================================================================== // CPLACEHOLDERMOD.CC - header for // // OMNeT++/OMNEST // Discrete System Simulation in C++ // // Author: Andras Varga, 2003 // Dept. of Electrical and Computer Systems Engineering, // Monash University, Melbourne, Australia // //========================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. Copyright (C) 2014 RWTH Aachen University, Chair of Communication and Distributed Systems This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #include "cplaceholdermod.h" #include "cproxygate.h" #include "cfilecomm.h" #include "cnamedpipecomm.h" #include "cmpicomm.h" #include "cnosynchronization.h" #include "cnullmessageprot.h" #include "cispeventlogger.h" #include "cidealsimulationprot.h" #include "clinkdelaylookahead.h" #include <stdio.h> NAMESPACE_BEGIN cPlaceholderModule::cPlaceholderModule() { remoteProcId = -1; } cPlaceholderModule::cPlaceholderModule(const char *originName) { remoteProcId = -1; originClassNamep = opp_strdup(originName); } cPlaceholderModule::~cPlaceholderModule() { delete[] originClassNamep; } void cPlaceholderModule::setRemoteProcId(int procid) { remoteProcId = procid; } int cPlaceholderModule::getRemoteProcId() { return remoteProcId; } std::string cPlaceholderModule::info() const { std::stringstream out; out << "id=" << getId() << ", PLACEHOLDER"; return out.str(); } void cPlaceholderModule::arrived(cMessage *msg, cGate *ongate, simtime_t t) { throw cRuntimeError(this, "internal error: arrived() called"); } void cPlaceholderModule::scheduleStart(simtime_t t) { // do nothing } cGate *cPlaceholderModule::createGateObject(cGate::Type type) { if (type==cGate::INPUT) return new cProxyGate(); else return cModule::createGateObject(type); } //so that serial/parallel case get the same ids and so the same RNG seeds void cPlaceholderModule::doBuildInside() { getModuleType()->buildInside(this, isPlaceholder()); } const char* cPlaceholderModule::getOriginClassName() { return originClassNamep; } /*char *cPlaceholderModule::getOriginClassName() { return originClassNamep; }*/ /*const char *cPlaceholderModule::getClassName() const { return originClassNamep; }*/ //---------------------------------------- // as usual: tribute to smart linkers void parsim_dummy() { cFileCommunications fc; cNamedPipeCommunications npc; #ifdef WITH_MPI cMPICommunications mc; #endif cNoSynchronization ns; cNullMessageProtocol np; cISPEventLogger iel; cIdealSimulationProtocol ip; cLinkDelayLookahead ldla; // prevent "unused variable" warnings: (void)fc; (void)npc; (void)ns; (void)np; (void)iel; (void)ip; (void)ldla; } NAMESPACE_END
23.976923
91
0.641001
eniac
26194c3bdf8b2234686f873fc6c989481ab274f2
15,419
cpp
C++
fuse_publishers/test/test_pose_2d_publisher.cpp
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
383
2018-07-02T07:20:32.000Z
2022-03-31T12:51:06.000Z
fuse_publishers/test/test_pose_2d_publisher.cpp
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
117
2018-07-16T10:32:52.000Z
2022-02-02T20:15:16.000Z
fuse_publishers/test/test_pose_2d_publisher.cpp
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
74
2018-10-01T10:10:45.000Z
2022-03-02T04:48:22.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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. */ #include <fuse_constraints/absolute_pose_2d_stamped_constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/transaction.h> #include <fuse_core/uuid.h> #include <fuse_graphs/hash_graph.h> #include <fuse_publishers/pose_2d_publisher.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <ros/ros.h> #include <tf2/utils.h> #include <tf2_msgs/TFMessage.h> #include <tf2_ros/static_transform_broadcaster.h> #include <gtest/gtest.h> #include <vector> /** * @brief Test fixture for the LatestStampedPose2DPublisher * * This test fixture provides a populated graph for testing the publish() function, and subscriber callbacks * for each of the different possible output topics. */ class Pose2DPublisherTestFixture : public ::testing::Test { public: Pose2DPublisherTestFixture() : private_node_handle_("~"), graph_(fuse_graphs::HashGraph::make_shared()), transaction_(fuse_core::Transaction::make_shared()), received_pose_msg_(false), received_pose_with_covariance_msg_(false), received_tf_msg_(false) { // Add a few pose variables auto position1 = fuse_variables::Position2DStamped::make_shared(ros::Time(1234, 10)); position1->x() = 1.01; position1->y() = 2.01; auto orientation1 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1234, 10)); orientation1->yaw() = 3.01; auto position2 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 10)); position2->x() = 1.02; position2->y() = 2.02; auto orientation2 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 10)); orientation2->yaw() = 3.02; auto position3 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 9)); position3->x() = 1.03; position3->y() = 2.03; auto orientation3 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 9)); orientation3->yaw() = 3.03; auto position4 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 11), fuse_core::uuid::generate("kitt")); position4->x() = 1.04; position4->y() = 2.04; auto orientation4 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 11), fuse_core::uuid::generate("kitt")); orientation4->yaw() = 3.04; transaction_->addInvolvedStamp(position1->stamp()); transaction_->addInvolvedStamp(orientation1->stamp()); transaction_->addInvolvedStamp(position2->stamp()); transaction_->addInvolvedStamp(orientation2->stamp()); transaction_->addInvolvedStamp(position3->stamp()); transaction_->addInvolvedStamp(orientation3->stamp()); transaction_->addInvolvedStamp(position4->stamp()); transaction_->addInvolvedStamp(orientation4->stamp()); transaction_->addVariable(position1); transaction_->addVariable(orientation1); transaction_->addVariable(position2); transaction_->addVariable(orientation2); transaction_->addVariable(position3); transaction_->addVariable(orientation3); transaction_->addVariable(position4); transaction_->addVariable(orientation4); // Add some priors on the variables some we can optimize the graph fuse_core::Vector3d mean1; mean1 << 1.01, 2.01, 3.01; fuse_core::Matrix3d cov1; cov1 << 1.01, 0.0, 0.0, 0.0, 2.01, 0.0, 0.0, 0.0, 3.01; auto constraint1 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared( "test", *position1, *orientation1, mean1, cov1); fuse_core::Vector3d mean2; mean2 << 1.02, 2.02, 3.02; fuse_core::Matrix3d cov2; cov2 << 1.02, 0.0, 0.0, 0.0, 2.02, 0.0, 0.0, 0.0, 3.02; auto constraint2 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared( "test", *position2, *orientation2, mean2, cov2); fuse_core::Vector3d mean3; mean3 << 1.03, 2.03, 3.03; fuse_core::Matrix3d cov3; cov3 << 1.03, 0.0, 0.0, 0.0, 2.03, 0.0, 0.0, 0.0, 3.03; auto constraint3 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared( "test", *position3, *orientation3, mean3, cov3); fuse_core::Vector3d mean4; mean4 << 1.04, 2.04, 3.04; fuse_core::Matrix3d cov4; cov4 << 1.04, 0.0, 0.0, 0.0, 2.04, 0.0, 0.0, 0.0, 3.04; auto constraint4 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared( "test", *position4, *orientation4, mean4, cov4); transaction_->addConstraint(constraint1); transaction_->addConstraint(constraint2); transaction_->addConstraint(constraint3); transaction_->addConstraint(constraint4); // Add the transaction to the graph graph_->update(*transaction_); // Optimize the graph graph_->optimize(); // Publish a odom->base transform so tf lookups will succeed geometry_msgs::TransformStamped odom_to_base; odom_to_base.header.stamp = ros::Time(0, 0); odom_to_base.header.frame_id = "test_odom"; odom_to_base.child_frame_id = "test_base"; odom_to_base.transform.translation.x = -0.10; odom_to_base.transform.translation.y = -0.20; odom_to_base.transform.translation.z = -0.30; odom_to_base.transform.rotation.x = 0.0; odom_to_base.transform.rotation.y = 0.0; odom_to_base.transform.rotation.z = -0.1986693307950612164; odom_to_base.transform.rotation.w = 0.98006657784124162625; // -0.4rad in yaw static_broadcaster_.sendTransform(odom_to_base); } void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) { received_pose_msg_ = true; pose_msg_ = *msg; } void poseWithCovarianceCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) { received_pose_with_covariance_msg_ = true; pose_with_covariance_msg_ = *msg; } void tfCallback(const tf2_msgs::TFMessage::ConstPtr& msg) { received_tf_msg_ = true; tf_msg_ = *msg; } protected: ros::NodeHandle node_handle_; ros::NodeHandle private_node_handle_; fuse_graphs::HashGraph::SharedPtr graph_; fuse_core::Transaction::SharedPtr transaction_; bool received_pose_msg_; geometry_msgs::PoseStamped pose_msg_; bool received_pose_with_covariance_msg_; geometry_msgs::PoseWithCovarianceStamped pose_with_covariance_msg_; bool received_tf_msg_; tf2_msgs::TFMessage tf_msg_; tf2_ros::StaticTransformBroadcaster static_broadcaster_; }; TEST_F(Pose2DPublisherTestFixture, PublishPose) { // Test that the expected PoseStamped message is published // Create a publisher and send it the graph private_node_handle_.setParam("test_publisher/map_frame", "test_map"); private_node_handle_.setParam("test_publisher/odom_frame", "test_odom"); private_node_handle_.setParam("test_publisher/base_frame", "test_base"); private_node_handle_.setParam("test_publisher/publish_to_tf", false); fuse_publishers::Pose2DPublisher publisher; publisher.initialize("test_publisher"); publisher.start(); // Subscribe to the "pose" topic ros::Subscriber subscriber = private_node_handle_.subscribe( "test_publisher/pose", 1, &Pose2DPublisherTestFixture::poseCallback, reinterpret_cast<Pose2DPublisherTestFixture*>(this)); // Send the graph to the Publisher to trigger message publishing publisher.notify(transaction_, graph_); // Verify the subscriber received the expected pose ros::Time timeout = ros::Time::now() + ros::Duration(10.0); while ((!received_pose_msg_) && (ros::Time::now() < timeout)) { ros::Duration(0.10).sleep(); } ASSERT_TRUE(received_pose_msg_); EXPECT_EQ(ros::Time(1235, 10), pose_msg_.header.stamp); EXPECT_EQ("test_map", pose_msg_.header.frame_id); EXPECT_NEAR(1.02, pose_msg_.pose.position.x, 1.0e-9); EXPECT_NEAR(2.02, pose_msg_.pose.position.y, 1.0e-9); EXPECT_NEAR(0.00, pose_msg_.pose.position.z, 1.0e-9); EXPECT_NEAR(3.02, tf2::getYaw(pose_msg_.pose.orientation), 1.0e-9); } TEST_F(Pose2DPublisherTestFixture, PublishPoseWithCovariance) { // Test that the expected PoseWithCovarianceStamped message is published // Create a publisher and send it the graph private_node_handle_.setParam("test_publisher/map_frame", "test_map"); private_node_handle_.setParam("test_publisher/odom_frame", "test_odom"); private_node_handle_.setParam("test_publisher/base_frame", "test_base"); private_node_handle_.setParam("test_publisher/publish_to_tf", false); fuse_publishers::Pose2DPublisher publisher; publisher.initialize("test_publisher"); publisher.start(); // Subscribe to the "pose_with_covariance" topic ros::Subscriber subscriber = private_node_handle_.subscribe( "test_publisher/pose_with_covariance", 1, &Pose2DPublisherTestFixture::poseWithCovarianceCallback, reinterpret_cast<Pose2DPublisherTestFixture*>(this)); // Send the graph to the Publisher to trigger message publishing publisher.notify(transaction_, graph_); // Verify the subscriber received the expected pose ros::Time timeout = ros::Time::now() + ros::Duration(10.0); while ((!received_pose_with_covariance_msg_) && (ros::Time::now() < timeout)) { ros::Duration(0.10).sleep(); } ASSERT_TRUE(received_pose_with_covariance_msg_); EXPECT_EQ(ros::Time(1235, 10), pose_with_covariance_msg_.header.stamp); EXPECT_EQ("test_map", pose_with_covariance_msg_.header.frame_id); EXPECT_NEAR(1.02, pose_with_covariance_msg_.pose.pose.position.x, 1.0e-9); EXPECT_NEAR(2.02, pose_with_covariance_msg_.pose.pose.position.y, 1.0e-9); EXPECT_NEAR(0.00, pose_with_covariance_msg_.pose.pose.position.z, 1.0e-9); EXPECT_NEAR(3.02, tf2::getYaw(pose_with_covariance_msg_.pose.pose.orientation), 1.0e-9); std::vector<double> expected_covariance = { 1.02, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 2.02, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 3.02 }; for (size_t i = 0; i < 36; ++i) { EXPECT_NEAR(expected_covariance[i], pose_with_covariance_msg_.pose.covariance[i], 1.0e-9); } } TEST_F(Pose2DPublisherTestFixture, PublishTfWithoutOdom) { // Test that the expected TFMessage is published // Create a publisher and send it the graph private_node_handle_.setParam("test_publisher/map_frame", "test_map"); private_node_handle_.setParam("test_publisher/odom_frame", "test_base"); private_node_handle_.setParam("test_publisher/base_frame", "test_base"); private_node_handle_.setParam("test_publisher/publish_to_tf", true); fuse_publishers::Pose2DPublisher publisher; publisher.initialize("test_publisher"); publisher.start(); // Subscribe to the "pose" topic ros::Subscriber subscriber = private_node_handle_.subscribe( "/tf", 1, &Pose2DPublisherTestFixture::tfCallback, reinterpret_cast<Pose2DPublisherTestFixture*>(this)); // Send the graph to the Publisher to trigger message publishing publisher.notify(transaction_, graph_); // Verify the subscriber received the expected pose ros::Time timeout = ros::Time::now() + ros::Duration(10.0); while ((!received_tf_msg_) && (ros::Time::now() < timeout)) { ros::Duration(0.10).sleep(); } ASSERT_TRUE(received_tf_msg_); ASSERT_EQ(1ul, tf_msg_.transforms.size()); EXPECT_EQ("test_map", tf_msg_.transforms[0].header.frame_id); EXPECT_EQ("test_base", tf_msg_.transforms[0].child_frame_id); EXPECT_NEAR(1.02, tf_msg_.transforms[0].transform.translation.x, 1.0e-9); EXPECT_NEAR(2.02, tf_msg_.transforms[0].transform.translation.y, 1.0e-9); EXPECT_NEAR(0.00, tf_msg_.transforms[0].transform.translation.z, 1.0e-9); EXPECT_NEAR(3.02, tf2::getYaw(tf_msg_.transforms[0].transform.rotation), 1.0e-9); } TEST_F(Pose2DPublisherTestFixture, PublishTfWithOdom) { // Test that the expected TFMessage is published // Create a publisher and send it the graph private_node_handle_.setParam("test_publisher/map_frame", "test_map"); private_node_handle_.setParam("test_publisher/odom_frame", "test_odom"); private_node_handle_.setParam("test_publisher/base_frame", "test_base"); private_node_handle_.setParam("test_publisher/publish_to_tf", true); fuse_publishers::Pose2DPublisher publisher; publisher.initialize("test_publisher"); publisher.start(); // Subscribe to the "pose" topic ros::Subscriber subscriber = private_node_handle_.subscribe( "/tf", 1, &Pose2DPublisherTestFixture::tfCallback, reinterpret_cast<Pose2DPublisherTestFixture*>(this)); // Send the graph to the Publisher to trigger message publishing publisher.notify(transaction_, graph_); // Verify the subscriber received the expected pose ros::Time timeout = ros::Time::now() + ros::Duration(10.0); while ((!received_tf_msg_) && (ros::Time::now() < timeout)) { ros::Duration(0.10).sleep(); } ASSERT_TRUE(received_tf_msg_); ASSERT_EQ(1ul, tf_msg_.transforms.size()); EXPECT_EQ("test_map", tf_msg_.transforms[0].header.frame_id); EXPECT_EQ("test_odom", tf_msg_.transforms[0].child_frame_id); EXPECT_NEAR(0.9788154983, tf_msg_.transforms[0].transform.translation.x, 1.0e-9); EXPECT_NEAR(1.8002186614, tf_msg_.transforms[0].transform.translation.y, 1.0e-9); EXPECT_NEAR(0.3000000000, tf_msg_.transforms[0].transform.translation.z, 1.0e-9); EXPECT_NEAR(-2.8631853072, tf2::getYaw(tf_msg_.transforms[0].transform.rotation), 1.0e-9); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_pose_2d_publisher"); ros::AsyncSpinner spinner(1); spinner.start(); int ret = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return ret; }
41.117333
109
0.728841
congleetea
2619858f4c1b9cb2a74da55cafd12f8a801bc386
3,854
cpp
C++
applications/plugins/ManifoldTopologies/ManifoldEdgeSetGeometryAlgorithms.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/ManifoldTopologies/ManifoldEdgeSetGeometryAlgorithms.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/ManifoldTopologies/ManifoldEdgeSetGeometryAlgorithms.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "ManifoldEdgeSetGeometryAlgorithms.inl" #include <sofa/defaulttype/Vec3Types.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/core/ObjectFactory.h> namespace sofa { namespace component { namespace topology { using namespace sofa::defaulttype; SOFA_DECL_CLASS(ManifoldEdgeSetGeometryAlgorithms) int ManifoldEdgeSetGeometryAlgorithmsClass = core::RegisterObject("ManifoldEdge set geometry algorithms") #ifdef SOFA_FLOAT .add< ManifoldEdgeSetGeometryAlgorithms<sofa::defaulttype::Vec3fTypes> >(true) // default template #else .add< ManifoldEdgeSetGeometryAlgorithms<sofa::defaulttype::Vec3dTypes> >(true) // default template #ifndef SOFA_DOUBLE .add< ManifoldEdgeSetGeometryAlgorithms<sofa::defaulttype::Vec3fTypes> >() // default template #endif #endif #ifndef SOFA_FLOAT .add< ManifoldEdgeSetGeometryAlgorithms<Vec2dTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Vec1dTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Rigid3dTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Rigid2dTypes> >() #endif #ifndef SOFA_DOUBLE .add< ManifoldEdgeSetGeometryAlgorithms<Vec2fTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Vec1fTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Rigid3fTypes> >() .add< ManifoldEdgeSetGeometryAlgorithms<Rigid2fTypes> >() #endif ; #ifndef SOFA_FLOAT template class ManifoldEdgeSetGeometryAlgorithms<sofa::defaulttype::Vec3dTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Vec2dTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Vec1dTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Rigid3dTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Rigid2dTypes>; #endif #ifndef SOFA_DOUBLE template class ManifoldEdgeSetGeometryAlgorithms<sofa::defaulttype::Vec3fTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Vec2fTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Vec1fTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Rigid3fTypes>; template class ManifoldEdgeSetGeometryAlgorithms<Rigid2fTypes>; #endif } // namespace topology } // namespace component } // namespace sofa
47
106
0.630254
sofa-framework
261c3a982176fb59cb4adb48f6970cbe839b934c
7,690
cpp
C++
src/downloads/downloadfilehelper.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
1
2017-05-21T15:31:02.000Z
2017-05-21T15:31:02.000Z
src/downloads/downloadfilehelper.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
src/downloads/downloadfilehelper.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2012 David Rosca <nowrep@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 "downloadfilehelper.h" #include "webpage.h" #include "webview.h" #include "downloadoptionsdialog.h" #include "mainapplication.h" #include "qupzilla.h" #include "downloaditem.h" #include "downloadmanager.h" #include "globalfunctions.h" #include "settings.h" DownloadFileHelper::DownloadFileHelper(const QString &lastDownloadPath, const QString &downloadPath, bool useNativeDialog, WebPage* page) : QObject() , m_lastDownloadOption(DownloadManager::SaveFile) , m_lastDownloadPath(lastDownloadPath) , m_downloadPath(downloadPath) , m_useNativeDialog(useNativeDialog) , m_timer(0) , m_reply(0) , m_openFileChoosed(false) , m_listWidget(0) , m_iconProvider(new QFileIconProvider) , m_manager(0) , m_webPage(page) { } ////////////////////////////////////////////////////// //// Getting where to download requested file //// in 3 functions, as we are using non blocking //// dialogs ( this is important to make secure downloading //// on Windows working properly ) ////////////////////////////////////////////////////// void DownloadFileHelper::handleUnsupportedContent(QNetworkReply* reply, bool askWhatToDo) { m_timer = new QTime(); m_timer->start(); m_h_fileName = getFileName(reply); m_reply = reply; QFileInfo info(reply->url().toString()); QTemporaryFile tempFile("XXXXXX." + info.suffix()); tempFile.open(); QFileInfo tempInfo(tempFile.fileName()); m_fileIcon = m_iconProvider->icon(tempInfo).pixmap(30, 30); QString mimeType = m_iconProvider->type(tempInfo); // Close Empty Tab if (m_webPage) { if (!m_webPage->mainFrame()->url().isEmpty() && m_webPage->mainFrame()->url().toString() != "about:blank") { m_downloadPage = m_webPage->mainFrame()->url(); } else if (m_webPage->history()->canGoBack()) { m_downloadPage = m_webPage->history()->backItem().url(); } else if (m_webPage->history()->count() == 0) { m_webPage->getView()->closeTab(); } } if (askWhatToDo) { DownloadOptionsDialog* dialog = new DownloadOptionsDialog(m_h_fileName, m_fileIcon, mimeType, reply->url(), mApp->activeWindow()); dialog->setLastDownloadOption(m_lastDownloadOption); dialog->show(); connect(dialog, SIGNAL(dialogFinished(int)), this, SLOT(optionsDialogAccepted(int))); } else { optionsDialogAccepted(2); } } void DownloadFileHelper::optionsDialogAccepted(int finish) { m_openFileChoosed = false; switch (finish) { case 0: //Cancelled if (m_timer) { delete m_timer; } return; break; case 1: //Open m_openFileChoosed = true; m_lastDownloadOption = DownloadManager::OpenFile; break; case 2: //Save m_lastDownloadOption = DownloadManager::SaveFile; break; } m_manager->setLastDownloadOption(m_lastDownloadOption); if (!m_openFileChoosed) { if (m_downloadPath.isEmpty()) { if (m_useNativeDialog) { fileNameChoosed(QFileDialog::getSaveFileName(mApp->getWindow(), tr("Save file as..."), m_lastDownloadPath + m_h_fileName)); } else { QFileDialog* dialog = new QFileDialog(mApp->getWindow()); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setWindowTitle(tr("Save file as...")); dialog->setDirectory(m_lastDownloadPath); dialog->selectFile(m_h_fileName); dialog->show(); connect(dialog, SIGNAL(fileSelected(QString)), this, SLOT(fileNameChoosed(QString))); } } else { fileNameChoosed(m_downloadPath + m_h_fileName, true); } } else { fileNameChoosed(QDir::tempPath() + "/" + m_h_fileName, true); } } void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoGenerated) { m_userFileName = name; if (m_userFileName.isEmpty()) { m_reply->abort(); if (m_timer) { delete m_timer; } return; } int pos = m_userFileName.lastIndexOf("/"); if (pos != -1) { int size = m_userFileName.size(); m_path = m_userFileName.left(pos + 1); m_fileName = m_userFileName.right(size - pos - 1); } if (fileNameAutoGenerated && QFile::exists(m_userFileName)) { QString _tmpFileName = m_fileName; int i = 1; while (QFile::exists(m_path + "/" + _tmpFileName)) { _tmpFileName = m_fileName; int index = _tmpFileName.lastIndexOf("."); if (index == -1) { _tmpFileName.append("(" + QString::number(i) + ")"); } else { _tmpFileName = _tmpFileName.mid(0, index) + "(" + QString::number(i) + ")" + _tmpFileName.mid(index); } i++; } m_fileName = _tmpFileName; } if (!m_path.contains(QDir::tempPath())) { m_lastDownloadPath = m_path; } Settings settings; settings.beginGroup("DownloadManager"); settings.setValue("lastDownloadPath", m_lastDownloadPath); settings.endGroup(); m_manager->setLastDownloadPath(m_lastDownloadPath); QListWidgetItem* item = new QListWidgetItem(m_listWidget); DownloadItem* downItem = new DownloadItem(item, m_reply, m_path, m_fileName, m_fileIcon, m_timer, m_openFileChoosed, m_downloadPage, m_manager); emit itemCreated(item, downItem); } ////////////////////////////////////////////////////// //// End here ////////////////////////////////////////////////////// QString DownloadFileHelper::getFileName(QNetworkReply* reply) { QString path; if (reply->hasRawHeader("Content-Disposition")) { QString value = QString::fromLatin1(reply->rawHeader("Content-Disposition")); int pos = value.indexOf("filename="); if (pos != -1) { QString name = value.mid(pos + 9); if (name.startsWith('"') && name.endsWith('"')) { name = name.mid(1, name.size() - 2); } path = name; } } if (path.isEmpty()) { path = reply->url().path(); } QFileInfo info(path); QString baseName = info.completeBaseName(); QString endName = info.suffix(); if (baseName.isEmpty()) { baseName = tr("NoNameDownload"); } if (!endName.isEmpty()) { endName = "." + endName; } QString name = baseName + endName; if (name.startsWith("\"")) { name = name.mid(1); } if (name.endsWith("\";")) { name.remove("\";"); } name = qz_filterCharsFromFilename(name); return name; } DownloadFileHelper::~DownloadFileHelper() { delete m_iconProvider; }
32.041667
148
0.597529
bubapl
1c7a16b52d0a2598419413ef6684c2331805539d
10,204
cpp
C++
homework/AvilovaEM/05/BI.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
12
2018-02-20T15:25:12.000Z
2022-02-15T03:31:55.000Z
homework/AvilovaEM/05/BI.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
1
2018-02-26T12:40:47.000Z
2018-02-26T12:40:47.000Z
homework/AvilovaEM/05/BI.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
33
2018-02-20T15:25:11.000Z
2019-02-13T22:33:36.000Z
#include <cstdlib> #include <cstring> #include <stdint.h> #include <utility> #include <ostream> #include <iostream> #include <algorithm> #include <memory> class BigInt { public: BigInt() : sign(0) , length(0) , dataSize(0) , data(nullptr) {} BigInt(const long long &x) { if (x == 0) { resize(1); data[0] = 0; sign = 0; length = 1; } else { sign = (x < 0 ? -1 : 1); resize(1); length = 0; long long y = std::abs(x); while (y > 0) { if (length == dataSize) resize(dataSize * 2); data[length] = y % 10; y /= 10; ++length; } } } BigInt(const BigInt& other) { sign = other.sign; length = other.length; dataSize = other.dataSize; data.reset(new int8_t[dataSize]); memset(data.get(), 0, sizeof(int8_t) * dataSize); memcpy(data.get(), other.data.get(), length); } BigInt(BigInt&& other) : sign(std::move(other.sign)) , length(std::move(other.length)) , dataSize(std::move(other.dataSize)) , data(std::move(other.data)) {} BigInt abs(const BigInt& x) const { BigInt answer(x); if (answer.sign < 0) answer.sign = 1; return answer; } BigInt& operator=(const BigInt& other) { sign = other.sign; length = other.length; dataSize = other.dataSize; data.reset(new int8_t[dataSize]); memset(data.get(), 0, sizeof(int8_t) * dataSize); memcpy(data.get(), other.data.get(), length); return *this; } BigInt& operator=(BigInt&& other) { sign = std::move(other.sign); length = std::move(other.length); dataSize = std::move(other.dataSize); data = std::move(other.data); return *this; } bool operator!=(const BigInt& other) const { if (sign != other.sign) return true; if (length != other.length) return true; for (uint32_t i = 0; i < length; ++i) if (data[i] != other.data[i]) return true; return false; } bool operator==(const BigInt& other) const { return !operator!=(other); } bool operator<=(const BigInt& other) const { if (sign < other.sign) return true; if (sign > other.sign) return false; if (length < other.length) return true; if (length > other.length) return false; for (uint32_t i = length; i > 0; --i) { if (data[i - 1] * sign < other.data[i - 1] * other.sign) return true; if (data[i - 1] * sign > other.data[i - 1] * other.sign) return false; } return true; } bool operator>=(const BigInt& other) const { if (sign < other.sign) return false; if (sign > other.sign) return true; if (length < other.length) return false; if (length > other.length) return true; for (uint32_t i = length; i > 0; --i) { if (data[i - 1] * sign < other.data[i - 1] * other.sign) return false; if (data[i - 1] * sign > other.data[i - 1] * other.sign) return true; } return true; } bool operator<(const BigInt& other) const { return !operator>=(other); } bool operator>(const BigInt& other) const { return !operator<=(other); } BigInt operator-() const { BigInt answer(*this); answer.sign *= -1; return answer; } BigInt operator+(const BigInt& other) const { if (sign == 0) { BigInt answer(other); return answer; } if (other.sign == 0) { BigInt answer(*this); return answer; } if (sign == other.sign) { BigInt answer(*this), second(other); sum(answer, second); return answer; } else { BigInt a(abs(*this)); BigInt b(abs(other)); if (a >= b) { minus(a, b); if (a.sign != 0) a.sign = sign; return a; } else { minus(b, a); if (b.sign != 0) b.sign = other.sign; return b; } } } BigInt operator-(const BigInt& other) const { return operator+(-other); } BigInt operator*(const BigInt& other) const { BigInt answer(0); if ((*this) == 0 || other == 0) return answer; answer.sign = sign * other.sign; answer.resize(length + other.length); answer.length = length + other.length - 1; for (uint32_t i = 0; i < length; ++i) { int t = 0; for (uint32_t j = 0; j < other.length; ++j) { t += answer.data[i + j] + data[i] * other.data[j]; answer.data[i + j] = t % 10; t /= 10; } uint32_t j = i + other.length; while (t > 0) { if (answer.length <= j) { if (answer.length == answer.dataSize) answer.resize(answer.dataSize * 2); ++answer.length; } t += answer.data[j]; answer.data[j] = t % 10; t /= 10; ++j; } } return answer; } BigInt operator/(const BigInt& other) const { if (abs(*this) < abs(other)) { BigInt answer(0); return answer; } if (other == 0) return 0; BigInt a(*this), b, c; a.sign = 1; b.sign = 1; b.length = length; b.dataSize = dataSize; b.data.reset(new int8_t[length]); memset(b.data.get(), 0, sizeof(int8_t) * length); memcpy(b.data.get() + length - other.length, other.data.get(), other.length); c.sign = sign * other.sign; c.length = length - other.length + 1; c.dataSize = c.length; c.data.reset(new int8_t[c.length]); memset(c.data.get(), 0, sizeof(int8_t) * c.length); for (uint32_t i = 0; i < c.length; ++i) { while (a >= b) { BigInt d(a - b); a = d; ++c.data[c.length - i - 1]; } for (uint32_t j = 1; j < b.length; ++j) b.data[j - 1] = b.data[j]; --b.length; } while (c.length > 1 && c.data[c.length - 1] == 0) --c.length; if (c.length == 1 && c.data[0] == 0) c.sign = 0; if (c.length * 2 <= c.dataSize) c.resize(c.dataSize); return c; } BigInt operator%(const BigInt& other) const { return ((*this) - ((*this) / other) * other); } private: int32_t sign; uint32_t length = 0; uint32_t dataSize = 0; std::unique_ptr<int8_t[]> data; void resize(uint32_t newSize) { int8_t* newData = new int8_t[newSize]; memset(newData, 0, sizeof(int8_t) * newSize); if (data != nullptr) memcpy(newData, data.get(), std::min(length, newSize)); dataSize = newSize; data.reset(newData); } void sum(BigInt& a, BigInt& b) const { if (b.dataSize > a.dataSize) a.resize(b.dataSize); a.length = std::max(a.length, b.length); a.resize(a.length); b.resize(a.length); int8_t t = 0; for (uint32_t i = 0; i < a.length; ++i) { t += a.data[i] + b.data[i]; a.data[i] = t % 10; t /= 10; } if (t > 0) { if (a.dataSize == a.length) { a.resize(a.dataSize * 2); a.data[a.length] = t; ++a.length; } } } void minus(BigInt& a, BigInt& b) const { a.length = std::max(a.length, b.length); a.resize(a.length); b.resize(a.length); int8_t t = 0; for (uint32_t i = 0; i < a.length; ++i) { t += a.data[i] - b.data[i]; if (t < 0) { t += 10; a.data[i] = t; t = -1; } else { a.data[i] = t; t = 0; } } while (a.length > 1 && a.data[a.length - 1] == 0) --a.length; if (a.length == 1 && a.data[0] == 0) a.sign = 0; uint32_t s = a.dataSize; while (a.length * 2 <= s) s /= 2; if (a.dataSize != s) a.resize(s); a.resize(s); } friend std::ostream& operator<<(std::ostream& out, const BigInt& value); }; std::ostream& operator<<(std::ostream& out, const BigInt& value) { if (value.sign == 0) out << 0; else { if (value.sign < 0) out << "-"; for (uint32_t i = value.length; i > 0; --i) out << static_cast<int>(value.data[i - 1]); } return out; }
24.353222
85
0.409643
nkotelevskii
1c7b3fe3cf86dba04992823ab919c18ad59f7092
367
hpp
C++
glib/include/triangle.hpp
cesarus777/kt_glib
96b4740f660535c3481645c4b45a3fd89a08c9e2
[ "BSD-3-Clause" ]
2
2020-09-22T13:44:47.000Z
2021-12-10T07:46:24.000Z
glib/include/triangle.hpp
cesarus777/kt_glib
96b4740f660535c3481645c4b45a3fd89a08c9e2
[ "BSD-3-Clause" ]
null
null
null
glib/include/triangle.hpp
cesarus777/kt_glib
96b4740f660535c3481645c4b45a3fd89a08c9e2
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <base.hpp> namespace mygeo { class Triangle : public Polygon { public: Triangle(Point p1, Point p2, Point p3) : Polygon({ p1, p2, p3 }, TRIANGLE) {} Triangle(std::vector<Point> v) : Polygon(v, TRIANGLE) { if(v.size() != 3) throw std::invalid_argument("Invalid Triangle : wrong number of points"); } }; }
19.315789
81
0.613079
cesarus777
1c7d2a3d01ed78eabca75cff56475777866f1206
1,470
hpp
C++
include/proton/_mapped_type.hpp
calmdan/libproton
229f2a963771049523c8a58dfa25d79b4b2417e0
[ "BSD-2-Clause" ]
1
2020-07-12T13:43:40.000Z
2020-07-12T13:43:40.000Z
include/proton/_mapped_type.hpp
calmdan/libproton
229f2a963771049523c8a58dfa25d79b4b2417e0
[ "BSD-2-Clause" ]
null
null
null
include/proton/_mapped_type.hpp
calmdan/libproton
229f2a963771049523c8a58dfa25d79b4b2417e0
[ "BSD-2-Clause" ]
null
null
null
#ifndef PROTON_MAPPED_TYPE_HEADER #define PROTON_MAPPED_TYPE_HEADER namespace proton{ template <typename mapT, typename K> typename mapT::mapped_type get(const mapT& x, K&& key) { auto it=x.find(key); PROTON_THROW_IF(it==x.end(), "can't find the key in a map"); return it->second; } template <typename mapT, typename K, typename V> typename mapT::mapped_type get(const mapT& x, K&& key, V&& dft) { auto it=x.find(key); if(it==x.end()) return dft; return it->second; } template <typename mapT, typename K> bool test_get(typename mapT::mapped_type& v, const mapT& x, K&& key) { auto it=x.find(key); if(it==x.end()) return false; v=it->second; return true; } template <typename mapT, typename K, typename V> bool test_insert(mapT& x, K&& k, V&& v) { return x.insert({k,v}).second; } template <typename mapT, typename K, typename V> bool test_insert_or_get(mapT& x, K&& k, V& v) { auto p=x.insert({k,v}); if(p.second) return true; v=p.first->second; return false; } template <typename mapT, typename K, typename ...argT> typename mapT::mapped_type& get_or_create(bool& hit, mapT& x, K&& k, argT&& ... v) { auto p=x.find(k); if(p!=x.end()){ hit= true; return p->second; } hit=false; #if 0 p=x.emplace(k, v...); #else p=x.insert({k,typename mapT::mapped_type(v...)}).first; #endif return p->second; } } #endif // PROTON_MAPPED_TYPE_HEADER
21.304348
82
0.631293
calmdan
1c80b6327bfbc8e4e1b6903e5ffc1e73575f323b
2,387
cpp
C++
source/std.groupboxbuttonscontrol.cpp
wilsonsouza/stdx.frame.x86
c9e0cc4c748f161367531990e5795a700f40e5ec
[ "Apache-2.0" ]
null
null
null
source/std.groupboxbuttonscontrol.cpp
wilsonsouza/stdx.frame.x86
c9e0cc4c748f161367531990e5795a700f40e5ec
[ "Apache-2.0" ]
null
null
null
source/std.groupboxbuttonscontrol.cpp
wilsonsouza/stdx.frame.x86
c9e0cc4c748f161367531990e5795a700f40e5ec
[ "Apache-2.0" ]
null
null
null
//-----------------------------------------------------------------------------------------------// // dedaluslib.lib for Windows // // Created by Wilson.Souza 2012, 2013 // For Libbs Farma // // Dedalus Prime // (c) 2012, 2013 //-----------------------------------------------------------------------------------------------// #pragma once #include <std.groupboxbuttonscontrol.hpp> //-----------------------------------------------------------------------------------------------// using namespace std; //-----------------------------------------------------------------------------------------------// GroupBoxButtonsControl::GroupBoxButtonsControl(std::ustring const & szCaption, int const & nCols, int const & nOffset): GroupBoxImpl<VerticalBox>(szCaption, szCaption) { SetCols(nCols); SetOffset(nOffset); SetName(szCaption); SetFontSize(0xc); SetFontStyle(QFont::Bold); SetButtonSize(shared_ptr<QPoint>(new QPoint{ 0xc, 0xc })); } //-----------------------------------------------------------------------------------------------// GroupBoxButtonsControl::~GroupBoxButtonsControl() { for(auto i = m_Queue->begin(); i != m_Queue->end(); i++) i.operator->()->second->disconnect(); } //-----------------------------------------------------------------------------------------------// Button * GroupBoxButtonsControl::GetButton(int const nId) { auto p = m_Queue->find(nId); if(p != m_Queue->end()) return p.operator->()->second; return nullptr; } //-----------------------------------------------------------------------------------------------// GroupBoxButtonsControl * GroupBoxButtonsControl::Create() { for(int i = 0; i <= m_Offset; ++i) { WidgetImpl<> * w = new WidgetImpl<>(); for(int n = 0; n < m_Cols; ++n, ++i) { Button * b = new Button { std::ustring(), QIcon(), std::ustring().sprintf("%d", i), true }; QFont f = b->font(); { b->setFixedSize(m_ButtonSize->x(), m_ButtonSize->y()); f.setPixelSize(m_FontSize); f.setStyle(QFont::Style(m_FontStyle)); } w->addWidget(b); } addWidget(w); } return this; } //-----------------------------------------------------------------------------------------------//
34.1
100
0.385002
wilsonsouza
1c85325531a36596e3ceaa4b65f7076b2f8050e4
181
hpp
C++
include/FrogJump.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/FrogJump.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/FrogJump.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef FROG_JUMP_HPP_ #define FROG_JUMP_HPP_ #include <vector> using namespace std; class FrogJump { public: bool canCross(vector<int> &stones); }; #endif // FROG_JUMP_HPP_
13.923077
39
0.745856
yanzhe-chen
1c87b3a731b5caabbb11384d8e86864be62d7c23
2,026
cpp
C++
LMS7002M/lms7suite/controlPanelGUI/dlgViewIRAM.cpp
myriadrf/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
14
2015-01-16T17:01:05.000Z
2020-10-31T17:52:53.000Z
LMS7002M/lms7suite/controlPanelGUI/dlgViewIRAM.cpp
serojik91/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
null
null
null
LMS7002M/lms7suite/controlPanelGUI/dlgViewIRAM.cpp
serojik91/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
12
2015-02-01T23:32:31.000Z
2021-01-09T16:34:51.000Z
/** @file dlgViewIRAM.cpp @author Lime Microsystems @brief dialog for viewing MCU IRAM data */ #include "dlgViewIRAM.h" //(*InternalHeaders(dlgViewIRAM) #include <wx/sizer.h> #include <wx/grid.h> #include <wx/intl.h> #include <wx/string.h> //*) //(*IdInit(dlgViewIRAM) const long dlgViewIRAM::ID_GRID1 = wxNewId(); //*) BEGIN_EVENT_TABLE(dlgViewIRAM,wxDialog) //(*EventTable(dlgViewIRAM) //*) END_EVENT_TABLE() dlgViewIRAM::dlgViewIRAM(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size) { pPnlMCU_BD=(pnlMCU_BD *)parent; //(*Initialize(dlgViewIRAM) wxBoxSizer* BoxSizer1; Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("id")); SetClientSize(wxDefaultSize); Move(wxDefaultPosition); BoxSizer1 = new wxBoxSizer(wxHORIZONTAL); Grid1 = new wxGrid(this, ID_GRID1, wxDefaultPosition, wxDefaultSize, 0, _T("ID_GRID1")); Grid1->CreateGrid(32,8); Grid1->EnableEditing(false); Grid1->EnableGridLines(true); Grid1->SetDefaultCellFont( Grid1->GetFont() ); Grid1->SetDefaultCellTextColour( Grid1->GetForegroundColour() ); BoxSizer1->Add(Grid1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); SetSizer(BoxSizer1); BoxSizer1->Fit(this); BoxSizer1->SetSizeHints(this); //*) } dlgViewIRAM::~dlgViewIRAM() { //(*Destroy(dlgViewIRAM) //*) } void dlgViewIRAM::InitDialog(){ InitGridData(); } void dlgViewIRAM::InitGridData() { int row=0; int col=0; int i=0; int j=0; int value; wxString temps=""; for (i=0; i<=31; i++){ temps.Printf(_("Row: 0x%02X"), 0xF8-i*8); Grid1->SetRowLabelValue(i, temps); //Grid1->SetCellValue(i+1, 0, temps); } for (j=0; j<8; j++){ //colums temps.Printf(_T("Col.: 0x%02X"), j); Grid1->SetColLabelValue(j, temps); //CellValue(0, j+1,temps); } for (i=0x0000; i<=0x00FF; i++) { value=pPnlMCU_BD->lmsControl->getMCU_BD()->m_IRAM[i]; row=(i/8); col=(i-row*8); row=31-row; temps.Printf(_T("0x%02X"), value); Grid1->SetCellValue(row,col,temps); } }
21.784946
103
0.692991
myriadrf
1c8c19d674c1611e12874901794e29cc4ed89d85
10,093
cpp
C++
tests/http/http_fields/main.cpp
Stiffstream/arataga
b6e1720dd2df055949847425f12bb1af56edbe83
[ "MIT", "Newsletr", "BSL-1.0", "BSD-3-Clause" ]
14
2021-01-08T15:43:37.000Z
2021-11-06T19:30:15.000Z
tests/http/http_fields/main.cpp
Stiffstream/arataga
b6e1720dd2df055949847425f12bb1af56edbe83
[ "MIT", "Newsletr", "BSL-1.0", "BSD-3-Clause" ]
5
2021-03-07T06:51:33.000Z
2021-07-01T09:54:30.000Z
tests/http/http_fields/main.cpp
Stiffstream/arataga
b6e1720dd2df055949847425f12bb1af56edbe83
[ "MIT", "Newsletr", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <doctest/doctest.h> #include <arataga/acl_handler/buffers.hpp> #include <restinio/helpers/string_algo.hpp> #include <tests/connection_handler_simulator/pub.hpp> #include <asio.hpp> using namespace std::string_view_literals; using namespace std::chrono_literals; namespace chs = connection_handler_simulator; TEST_CASE("headers without the body") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_headers_complete_timeout = 2s; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET http://localhost:8080/ HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Accept: */*\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 408 Request Timeout\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); } TEST_CASE("severals Host headers") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_headers_complete_timeout = 2s; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Host: localhost:8080\r\n" "Accept: */*\r\n" "Content-Length: 0\r\n" "\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 400 Bad Request\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); } TEST_CASE("request-target too long") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_message_limits.m_max_request_target_length = 100u; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET /123456789/123456789/123456789/123456789/123456789/123456789/" "123456789/123456789/123456789/123456789/123456789/123456789 " "HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Host: localhost:8080\r\n" "Accept: */*\r\n" "Content-Length: 0\r\n" "\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 400 Bad Request\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); } TEST_CASE("HTTP-field name too long") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_message_limits.m_max_field_name_length = 100u; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Host: localhost:8080\r\n" "Header-With-Very-Very-Long-Name-123456789" "-123456789-123456789-123456789-123456789-123456789" "-123456789-123456789-123456789-123456789-123456789: Boo!\r\n" "Accept: */*\r\n" "Content-Length: 0\r\n" "\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 400 Bad Request\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); } TEST_CASE("HTTP-field value too long") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_message_limits.m_max_field_value_length = 100u; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Host: localhost:8080\r\n" "Header-With-Very-Very-Long-Value: 123456789" "-123456789-123456789-123456789-123456789-123456789" "-123456789-123456789-123456789-123456789-123456789 Boo!\r\n" "Accept: */*\r\n" "Content-Length: 0\r\n" "\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 400 Bad Request\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); } TEST_CASE("total http-fields size too big") { asio::ip::tcp::endpoint proxy_endpoint{ asio::ip::make_address_v4( "127.0.0.1" ), 2444 }; chs::handler_config_values_t config_values; config_values.m_http_message_limits.m_max_total_headers_size = 100u; chs::simulator_t simulator{ proxy_endpoint, config_values }; asio::io_context ctx; asio::ip::tcp::socket connection{ ctx }; REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) ); asio::ip::tcp::no_delay no_delay_opt{ true }; connection.set_option( no_delay_opt ); { std::string_view outgoing_request{ "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Host: localhost:8080\r\n" "Accept: */*\r\n" "Content-Length: 0\r\n" "Dummy-Header-1: 01234567890123456789\r\n" "Dummy-Header-2: 01234567890123456789\r\n" "Dummy-Header-3: 01234567890123456789\r\n" "Dummy-Header-4: 01234567890123456789\r\n" "Dummy-Header-5: 01234567890123456789\r\n" "Dummy-Header-6: 01234567890123456789\r\n" "\r\n" }; REQUIRE_NOTHROW( asio::write(connection, asio::buffer(outgoing_request)) ); } // A negative response is expected. { std::array< char, 512 > data; std::size_t bytes_read; REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) ); std::string_view response{ &data[ 0 ], bytes_read }; REQUIRE( restinio::string_algo::starts_with( response, "HTTP/1.1 400 Bad Request\r\n"sv ) ); } // The connection has to be closed on the other side. { std::array< std::uint8_t, 20 > data; asio::error_code ec; REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) ); REQUIRE( asio::error::eof == ec ); } chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() ); }
26.012887
75
0.688497
Stiffstream
1c8fdeb36ffc81fbe2ba897bdcf5e51799311342
1,828
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgDB/Archive.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgDB/Archive.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgDB/Archive.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Notify> #include <osg/Endian> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/Archive> #include <streambuf> using namespace osgDB; osgDB::Archive* osgDB::openArchive(const std::string& filename, ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint) { return openArchive(filename, status, indexBlockSizeHint, Registry::instance()->getOptions()); } osgDB::Archive* osgDB::openArchive(const std::string& filename, ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint,ReaderWriter::Options* options) { // ensure archive extension is in the registry list std::string::size_type dot = filename.find_last_of('.'); if (dot != std::string::npos) { std::string ext = filename.substr(dot+1); Registry::instance()->addArchiveExtension(ext); } ReaderWriter::ReadResult result = osgDB::Registry::instance()->openArchive(filename, status, indexBlockSizeHint, options); return result.takeArchive(); } Archive::Archive() { osg::notify(osg::INFO)<<"Archive::Archive() open"<<std::endl; } Archive::~Archive() { osg::notify(osg::INFO)<<"Archive::~Archive() closed"<<std::endl; }
34.490566
163
0.727024
UM-ARM-Lab
1c97d0af2d6e76bd95eb25c247ed0c479bf1420e
1,306
hpp
C++
includes/text_analysis.hpp
JaredsAlgorithms/CS-131-Project-6
e911ef84ed3cdc89251ead24eb5cf21da7282272
[ "MIT" ]
null
null
null
includes/text_analysis.hpp
JaredsAlgorithms/CS-131-Project-6
e911ef84ed3cdc89251ead24eb5cf21da7282272
[ "MIT" ]
null
null
null
includes/text_analysis.hpp
JaredsAlgorithms/CS-131-Project-6
e911ef84ed3cdc89251ead24eb5cf21da7282272
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> /* std::transform */ #include <iostream> #include <list> #include <set> #include <string> /* not needed for Mac OSX */ #include <unordered_map> #include <vector> class TextAnalysis { public: TextAnalysis() = default; void add_word(const std::string&, size_t); // IMPLEMENT BELOW size_t countWord(const std::string&); // IMPLEMENT BELOW size_t countTwoWords(const std::string&, const std::string&); // IMPLEMENT BELOW void read_text(std::istream&, const std::string&); // ALREADY DONE private: std::unordered_map<std::string, std::vector<size_t> > wordtable; // hash table with key=word and value=vector of page numbers }; // ALREADY DONE: BREAK A LINE INTO A LIST OF WORDS // Courtesy of Martin Broadhurst -- // http://www.martinbroadhurst.com/how-to-split-a-string-in-c.html template <class Container> void split(const std::string& str, Container& cont, const std::string& delims = " ") { std::size_t curr, prev = 0; curr = str.find_first_of(delims); while (curr != std::string::npos) { // largest possible unsigned number cont.push_back(str.substr(prev, curr - prev)); prev = curr + 1; curr = str.find_first_of(delims, prev); } cont.push_back(str.substr(prev, curr - prev)); }
31.095238
78
0.671516
JaredsAlgorithms
1c98609ac81992193bbb7728945e00c6f3bfbee2
5,232
cpp
C++
VkMaterialSystem/os_input.cpp
khalladay/VkMaterialSystem
b8f83ed0ff0a4810d7f19868267d8e62f061e3c3
[ "MIT" ]
26
2017-12-04T17:51:22.000Z
2022-02-17T16:50:54.000Z
VkMaterialSystem/os_input.cpp
khalladay/VkMaterialSystem
b8f83ed0ff0a4810d7f19868267d8e62f061e3c3
[ "MIT" ]
1
2019-07-08T12:48:30.000Z
2019-08-09T11:51:08.000Z
VkMaterialSystem/os_input.cpp
khalladay/VkMaterialSystem
b8f83ed0ff0a4810d7f19868267d8e62f061e3c3
[ "MIT" ]
4
2018-06-14T18:31:07.000Z
2022-02-28T12:16:00.000Z
#pragma once #include "stdafx.h" #include "os_input.h" #include "os_support.h" #define checkhf(expr, format, ...) if (FAILED(expr)) \ { \ fprintf(stdout, "CHECK FAILED: %s:%d:%s " format "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ CString dbgstr; \ dbgstr.Format(("%s"), format); \ MessageBox(NULL,dbgstr, "FATAL ERROR", MB_OK); \ } #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> struct InputState { int screenWidth; int screenHeight; int mouseX; int mouseY; int mouseDX; int mouseDY; unsigned char keyStates[256]; DIMOUSESTATE mouseState; IDirectInput8* diDevice; IDirectInputDevice8* diKeyboard; IDirectInputDevice8* diMouse; }; InputState GInputState; void os_initializeInput() { HRESULT result; GInputState.screenHeight = GAppInfo.curH; GInputState.screenWidth = GAppInfo.curH; GInputState.mouseX = 0; GInputState.mouseY = 0; // Initialize the main direct input interface. result = DirectInput8Create(GAppInfo.instance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&GInputState.diDevice, NULL); checkhf(result, "Failed to create DirectInput device"); // Initialize the direct input interface for the keyboard. result = GInputState.diDevice->CreateDevice(GUID_SysKeyboard, &GInputState.diKeyboard, NULL); checkhf(result, "Failed to create DirectInput keyboard"); // Set the data format. In this case since it is a keyboard we can use the predefined data format. result = GInputState.diKeyboard->SetDataFormat(&c_dfDIKeyboard); checkhf(result, "Failed to set data format for DirectInput kayboard"); // Set the cooperative level of the keyboard to not share with other programs. result = GInputState.diKeyboard->SetCooperativeLevel(GAppInfo.wndHdl, DISCL_FOREGROUND | DISCL_EXCLUSIVE); checkhf(result, "Failed to set keyboard to foreground exclusive"); // Now acquire the keyboard. result = GInputState.diKeyboard->Acquire(); checkhf(result, "Failed to acquire DI Keyboard"); // Initialize the direct input interface for the mouse. result = GInputState.diDevice->CreateDevice(GUID_SysMouse, &GInputState.diMouse, NULL); checkhf(result, "Failed ot create DirectInput keyboard"); // Set the data format for the mouse using the pre-defined mouse data format. result = GInputState.diMouse->SetDataFormat(&c_dfDIMouse); checkhf(result, "Failed to set data format for DirectInput mouse"); //result = GInputState.diMouse->SetCooperativeLevel(wndHdl, DISCL_FOREGROUND | DISCL_EXCLUSIVE); //checkhf(result, "Failed to get exclusive access to DirectInput mouse"); // Acquire the mouse. result = GInputState.diMouse->Acquire(); checkhf(result, "Failed to acquire DirectInput mouse"); } void os_pollInput() { HRESULT result; // Read the keyboard device. result = GInputState.diKeyboard->GetDeviceState(sizeof(GInputState.keyStates), (LPVOID)&GInputState.keyStates); if (FAILED(result)) { // If the keyboard lost focus or was not acquired then try to get control back. if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED)) { GInputState.diKeyboard->Acquire(); } else { checkf(0, "Error polling keyboard"); } } // Read the mouse device. result = GInputState.diMouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&GInputState.mouseState); if (FAILED(result)) { // If the mouse lost focus or was not acquired then try to get control back. if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED)) { GInputState.diMouse->Acquire(); } else { checkf(0, "Error polling mouse"); } } // Update the location of the mouse cursor based on the change of the mouse location during the frame. GInputState.mouseX += GInputState.mouseState.lX; GInputState.mouseY += GInputState.mouseState.lY; GInputState.mouseDX = GInputState.mouseState.lX; GInputState.mouseDY = GInputState.mouseState.lY; // Ensure the mouse location doesn't exceed the screen width or height. if (GInputState.mouseX < 0) { GInputState.mouseX = 0; } if (GInputState.mouseY < 0) { GInputState.mouseY = 0; } if (GInputState.mouseX > GInputState.screenWidth) { GInputState.mouseX = GInputState.screenWidth; } if (GInputState.mouseY > GInputState.screenHeight) { GInputState.mouseY = GInputState.screenHeight; } } void os_shutdownInput() { if (GInputState.diMouse) { GInputState.diMouse->Unacquire(); GInputState.diMouse->Release(); GInputState.diMouse = 0; } // Release the keyboard. if (GInputState.diKeyboard) { GInputState.diKeyboard->Unacquire(); GInputState.diKeyboard->Release(); GInputState.diKeyboard = 0; } // Release the main interface to direct input. if (GInputState.diDevice) { GInputState.diDevice->Release(); GInputState.diDevice = 0; } } bool getKey(KeyCode key) { return GInputState.keyStates[key] > 0; } int getMouseDX() { return GInputState.mouseDX; } int getMouseDY() { return GInputState.mouseDY; } int getMouseX() { return GInputState.mouseX; } int getMouseY() { return GInputState.mouseY; } int getMouseLeftButton() { return GInputState.mouseState.rgbButtons[0] > 0; } int getMouseRightButton() { return GInputState.mouseState.rgbButtons[2] > 0; }
27.536842
125
0.728402
khalladay
1c9a2ee7e7d53924ad0bc7a2663238d2aeb48c86
1,222
cpp
C++
0639-Word Abbreviation/0639-Word Abbreviation.cpp
akekho/LintCode
2d31f1ec092d89e70d5059c7fb2df2ee03da5981
[ "MIT" ]
77
2017-12-30T13:33:37.000Z
2022-01-16T23:47:08.000Z
0601-0700/0639-Word Abbreviation/0639-Word Abbreviation.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
1
2018-05-14T14:15:40.000Z
2018-05-14T14:15:40.000Z
0601-0700/0639-Word Abbreviation/0639-Word Abbreviation.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
39
2017-12-07T14:36:25.000Z
2022-03-10T23:05:37.000Z
class Solution { public: /** * @param dict: an array of n distinct non-empty strings * @return: an array of minimal possible abbreviations for every word */ vector<string> wordsAbbreviation(vector<string> &dict) { // write your code here int n = dict.size(); unordered_map<string, int> table; vector<int> prefix(n, 1); vector<string> result(n); for (int i = 0; i < n; ++i) { string s = getAbbr(dict[i], prefix[i]); result[i] = s; ++table[s]; } bool unique = true; do { unique = true; for (int i = 0; i < n; ++i) { if (table[result[i]] > 1) { string s = getAbbr(dict[i], ++prefix[i]); result[i] = s; ++table[s]; unique = false; } } } while (!unique); return result; } private: string getAbbr(string& s, int prefix) { if (prefix >= int(s.size()) - 2) { return s; } return s.substr(0, prefix) + to_string(s.size() - 1 - prefix) + s.back(); } };
27.772727
82
0.438625
akekho
1ca2a7117330734b01c768bfca8c047ff7a1daa8
5,469
cpp
C++
src/obj_reg.cpp
robinzhoucmu/MLab_TrackingMocap
e9bd71ea546c545dfb1f4f406e72fe2822992046
[ "BSD-2-Clause" ]
null
null
null
src/obj_reg.cpp
robinzhoucmu/MLab_TrackingMocap
e9bd71ea546c545dfb1f4f406e72fe2822992046
[ "BSD-2-Clause" ]
null
null
null
src/obj_reg.cpp
robinzhoucmu/MLab_TrackingMocap
e9bd71ea546c545dfb1f4f406e72fe2822992046
[ "BSD-2-Clause" ]
null
null
null
#include "obj_reg.h" ObjectReg::ObjectReg() { } void ObjectReg::Serialize(std::ostream & fout) { // First 3 lines of cali marker positions. for (int i = 0; i < 3; ++i) { const Vec& p = cali_markers_pos[i]; for (int j = 0; j < 3; ++j ) { fout << p[j] << " "; } fout << std::endl; } // Serialize relevant homogenious transformations. SerializeHomog(fout, tf_robot_mctractable); SerializeHomog(fout, tf_robot_calimarkers); SerializeHomog(fout, tf_mctractable_obj); } void ObjectReg::Deserialize(std::istream& fin) { // Deserialize vector of cali marker positions. cali_markers_pos.clear(); for (int i = 0; i < 3; ++i) { Vec p(3); for (int j = 0; j < 3; ++j) { fin >> p[j]; } cali_markers_pos.push_back(p); } DeserializeHomog(fin, &tf_robot_mctractable); DeserializeHomog(fin, &tf_robot_calimarkers); DeserializeHomog(fin, &tf_mctractable_obj); } void ObjectReg::DeserializeHomog(std::istream& fin, HomogTransf* tf) { double tf_mat[4][4]; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { fin >> tf_mat[i][j]; } } *tf = HomogTransf(tf_mat); } void ObjectReg::SerializeHomog(std::ostream& fout, const HomogTransf& tf) { assert(tf.nn == 4 && tf.mm == 4); for (int i = 0; i < tf.nn; ++i) { for (int j = 0; j < tf.mm; ++j) { fout << tf[i][j]<< " "; } fout << std::endl; } } void ObjectReg::ReadCaliMarkersFromMocap(MocapComm& mocap_comm) { cali_markers_pos.clear(); Mocap::mocap_frame mocap_msg; mocap_comm.GetMocapFrame(&mocap_msg); // Extract cali markers(which NatNet will treat as unidenfied markers). int num_markers = mocap_msg.uid_markers.markers.size(); // Check for size. assert(num_markers == 3); for (int i = 0; i < num_markers; ++i) { const geometry_msgs::Point& pt_mocap = mocap_msg.uid_markers.markers[i]; Vec pt(3); pt[0] = pt_mocap.x; pt[1] = pt_mocap.y; pt[2] = pt_mocap.z; cali_markers_pos.push_back(pt); } FormCaliMarkerCoordinateFrame(); } void ObjectReg::FormCaliMarkerCoordinateFrame() { int num_markers = cali_markers_pos.size(); assert(num_markers == 3); int id_origin = -1; const double eps_dot_product = 0.1; Vec axis_x; Vec axis_y; for (int i = 0; i < num_markers; ++i) { // Determine the ith point can be set as the origin. // Check the angle between axis is close to right angle or not. axis_x = cali_markers_pos[(i+1) % num_markers] - cali_markers_pos[i]; axis_y = cali_markers_pos[(i+2) % num_markers] - cali_markers_pos[i]; const double norm_axis_x = sqrt(axis_x * axis_x); const double norm_axis_y = sqrt(axis_y * axis_y); // Use the longer axis as the y axis. if (norm_axis_x > norm_axis_y) { Vec tmp = axis_x; axis_x = axis_y; axis_y = tmp; } // Check dot product. double dot_product = (axis_x * axis_y) / (sqrt(axis_x * axis_x) * sqrt(axis_y * axis_y)); if (dot_product < eps_dot_product) { id_origin = i; break; } } double z[3] = {0, 0, 1}; Vec axis_z(z,3); // axis_x and axis_y may not be perfectly perpendicular, we reset axis_x as // the cross-product of axis_z and axis_y. // Todo(Jiaji): Find the nearest rotation matrix by projection. axis_x = axis_y ^ axis_z; // Form the RefFrame. RotMat rot_mat(axis_x, axis_y, axis_z); // Form the Translation. Vec trans(cali_markers_pos[id_origin]); // Update the homogenious transformation. tf_robot_calimarkers.setRotation(rot_mat); tf_robot_calimarkers.setTranslation(trans); } void ObjectReg::ReadTractablePoseFromMocap(MocapComm& mocap_comm) { Mocap::mocap_frame mocap_msg; mocap_comm.GetMocapFrame(&mocap_msg); // We are assuming during registration process, there is only one tractable in view. assert(mocap_msg.body_poses.poses.size() == 1); // Extract pose from mocap output. double tractable_pose[7]; geometry_msgs::Pose pose = mocap_msg.body_poses.poses[0]; tractable_pose[0] = pose.position.x; tractable_pose[1] = pose.position.y; tractable_pose[2] = pose.position.z; tractable_pose[3] = pose.orientation.x; tractable_pose[4] = pose.orientation.y; tractable_pose[5] = pose.orientation.z; tractable_pose[6] = pose.orientation.w; // Update the tf. tf_robot_mctractable.setPose(tractable_pose); } void ObjectReg::ComputeTransformation() { tf_mctractable_obj = tf_robot_mctractable.inv() * tf_robot_calimarkers; } int main(int argc, char* argv[]) { ros::init(argc, argv, "ObjectRegistration"); ros::NodeHandle np; MocapComm mocap_comm(&np); ObjectReg obj_reg; // Shell based interactive process. std::cout << "Object Registration Process Starts. Remeber to calibrate mocap frame to robot base frame first." << std::endl; std::cout << "Place JUST the paper cali markers on the table." << std::endl; std::cout << "Input Object Name" << std::endl; std::string name; std::cin >> name; obj_reg.SetObjName(name); std::cout << "Setting Up Cali Marker Frame" << std::endl; //std::cout << "Enter any key to start acquiring" << std::endl; system("Pause"); obj_reg.ReadCaliMarkersFromMocap(mocap_comm); std::cout << "Now put the object on the paper." << std::endl; system("Pause"); obj_reg.ReadTractablePoseFromMocap(mocap_comm); std::cout << "Computing transformation." << std::endl; obj_reg.ComputeTransformation(); std::cout << obj_reg.GetTransformation() << std::endl; return 0; }
31.796512
126
0.669592
robinzhoucmu
1caab0212a24f6b421caa406dfc7099da758fd9c
2,749
cc
C++
autolign.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
autolign.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
autolign.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#include "project.hh" #include "topology.hh" #include "random.hh" #include "cudamem.hh" #include "project.hh" #include "ppm.hh" #include "warp.hh" #include "partrait.hh" #include "encgen.hh" #include "autoposer.hh" #include "imgutils.hh" #include <math.h> #include <map> using namespace makemore; int main(int argc, char **argv) { seedrand(); Autoposer autoposer("bestposer.proj"); Autoposer autoposer2("newposer.proj"); Encgen egd("bigsham.proj", 1); Partrait par; Pose curpose; bool first = 1; while (par.read_ppm(stdin)) { if (first) { curpose = Pose::STANDARD; curpose.scale = 64; curpose.center.x = (double)par.w / 2.0; curpose.center.y = (double)par.h / 2.0; par.set_pose(curpose); } first = 0; Pose lastpose = par.get_pose(); double cdrift = 0.2; double sdrift = 0.5; double drift = 0.5; curpose.center.x = (1.0 - cdrift) * lastpose.center.x + cdrift * (par.w / 2.0); curpose.center.y = (1.0 - cdrift) * lastpose.center.y + cdrift * (par.h / 2.0); curpose.scale = (1.0 - sdrift) * lastpose.scale + sdrift * 64.0; curpose.angle = (1.0 - drift) * lastpose.angle; curpose.stretch = (1.0 - drift) * lastpose.stretch + 1.0 * drift; curpose.skew = (1.0 - drift) * lastpose.skew; if (curpose.center.x < 0) curpose.center.x = 0; if (curpose.center.x >= par.w) curpose.center.x = par.w - 1; if (curpose.center.y < 0) curpose.center.y = 0; if (curpose.center.y >= par.h) curpose.center.y = par.h - 1; if (curpose.skew > 0.1) curpose.skew = 0.1; if (curpose.skew < -0.1) curpose.skew = -0.1; if (curpose.scale > 128.0) curpose.scale = 128.0; if (curpose.scale < 32.0) curpose.scale = 32.0; if (curpose.angle > 1.0) curpose.angle = 1.0; if (curpose.angle < -1.0) curpose.angle = -1.0; if (curpose.stretch > 1.2) curpose.stretch = 1.2; if (curpose.stretch < 0.8) curpose.stretch = 0.8; par.set_pose(curpose); autoposer.autopose(&par); autoposer2.autopose(&par); autoposer2.autopose(&par); Partrait stdpar(256, 256); stdpar.set_pose(Pose::STANDARD); par.warp(&stdpar); memset(egd.ctxbuf, 0, egd.ctxlay->n * sizeof(double)); stdpar.make_sketch(egd.ctxbuf); Hashbag hb; hb.add("white"); hb.add("male"); memcpy(egd.ctxbuf + 192, hb.vec, sizeof(double) * 64); egd.ctxbuf[256] = par.get_tag("angle", 0.0); egd.ctxbuf[257] = par.get_tag("stretch", 1.0); egd.ctxbuf[258] = par.get_tag("skew", 0.0); assert(egd.tgtlay->n == stdpar.w * stdpar.h * 3); rgblab(stdpar.rgb, egd.tgtlay->n, egd.tgtbuf); egd.encode(); egd.generate(); labrgb(egd.tgtbuf, egd.tgtlay->n, stdpar.rgb); stdpar.warpover(&par); par.write_ppm(stdout); } return 0; }
26.432692
83
0.624227
jdb19937
1cac5bf0ffb66bfd0e666fa89b54afb0ff511e1c
1,961
cpp
C++
src/libmerklecpp/test/demo_tree.cpp
rneatherway/CCF
e04c6bbbe0b5ba044abaab9f972287194b6fc6cc
[ "Apache-2.0" ]
2
2020-08-06T04:12:36.000Z
2021-09-09T04:15:25.000Z
src/libmerklecpp/test/demo_tree.cpp
rajdhandus/CCF
96edbc9db6bd14c559a8c59bcda1c2a4835768d2
[ "Apache-2.0" ]
1
2021-02-09T22:43:48.000Z
2021-02-09T22:43:48.000Z
src/libmerklecpp/test/demo_tree.cpp
syhamza/CCF
67eafefb1f6ce4ce4812a733746c952e25b907e8
[ "Apache-2.0" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #include <chrono> #include <iomanip> #include <iostream> #ifdef HAVE_EVERCRYPT # include <MerkleTree.h> #endif #include "util.h" #include <merklecpp.h> #define PRINT_HASH_SIZE 3 int main() { try { const size_t num_leaves = 11; { auto hashes = make_hashes(num_leaves); merkle::Tree mt; for (auto h : hashes) mt.insert(h); merkle::Tree::Hash root = mt.root(); std::cout << mt.to_string(PRINT_HASH_SIZE) << std::endl; #ifdef HAVE_EVERCRYPT merkle_tree* ec_mt = NULL; uint8_t* ec_hash = mt_init_hash(32); for (auto h : hashes) { if (!ec_mt) ec_mt = mt_create(h.bytes); else mt_insert(ec_mt, h.bytes); } mt_get_root(ec_mt, ec_hash); std::cout << "EverCrypt: " << std::endl; std::cout << "R: " << merkle::Hash(ec_hash).to_string() << std::endl; mt_free_hash(ec_hash); mt_free(ec_mt); std::cout << std::endl; #endif std::cout << "Paths: " << std::endl; for (size_t i = mt.min_index(); i <= mt.max_index(); i++) { mt.flush_to(i); auto path = mt.path(i); std::cout << "P" << std::setw(2) << std::setfill('0') << i << ": " << path->to_string(PRINT_HASH_SIZE) << " " << std::endl; if (!path->verify(root)) throw std::runtime_error("root hash mismatch"); std::vector<uint8_t> chk = *path; } std::vector<uint8_t> buffer; mt.serialise(buffer); merkle::Tree dmt(buffer); if (mt.root() != dmt.root()) throw std::runtime_error("root hash mismatch"); std::cout << std::endl; } } catch (std::exception& ex) { std::cout << "Error: " << ex.what() << std::endl; return 1; } catch (...) { std::cout << "Error" << std::endl; return 1; } return 0; }
22.802326
75
0.5487
rneatherway
1cac63c7b53ef8aa89468f7fd2a0f13da2f162e5
24,976
cpp
C++
qd/cae/dyna_cpp/db/DB_Elements.cpp
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
104
2017-08-29T19:33:53.000Z
2022-03-19T11:36:05.000Z
qd/cae/dyna_cpp/db/DB_Elements.cpp
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
72
2017-08-10T10:59:43.000Z
2021-10-06T19:06:50.000Z
qd/cae/dyna_cpp/db/DB_Elements.cpp
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
37
2017-11-20T14:00:56.000Z
2022-03-09T17:19:06.000Z
#include <algorithm> #include <unordered_set> #include "DB_Elements.hpp" #include "DB_Nodes.hpp" #include "DB_Parts.hpp" #include "Element.hpp" #include "FEMFile.hpp" #include "Node.hpp" #include "Part.hpp" namespace qd { /** Constructor * * @param FEMFile* _femfile : parent file */ DB_Elements::DB_Elements(FEMFile* _femfile) : femfile(_femfile) , db_nodes(_femfile->get_db_nodes()) , db_parts(_femfile->get_db_parts()) {} /* * Destructor. */ DB_Elements::~DB_Elements() { #ifdef QD_DEBUG std::cout << "DB_Elements::~DB_Elements called." << std::endl; #endif } /** Add an element to the database (internal usage only) * * @param _etype : type of the element * @param _elementID : id of the element * @param _node_indexes : node indexes in db (must be in same db!!!) * * Adds an element, will not perform checks that the element * has the same database as nodes and part. * Also not checked whether the nodes with the specified indexes * exist. */ std::shared_ptr<Element> DB_Elements::create_element_unchecked(Element::ElementType _eType, int32_t _element_id, int32_t _part_id, const std::vector<int32_t>& _node_ids) { std::shared_ptr<Element> element = std::make_shared<Element>(_element_id, _part_id, _eType, _node_ids, this); switch (_eType) { case (Element::SHELL): #pragma omp critical { // std::lock_guard<std::mutex> lock(_elem4_mutex); if (id2index_elements4.find(_element_id) != id2index_elements4.end()) throw(std::invalid_argument( "Trying to insert an element with same id twice:" + std::to_string(_element_id))); id2index_elements4.insert( std::pair<int32_t, size_t>(_element_id, elements4.size())); elements4.push_back(element); } break; case (Element::SOLID): #pragma omp critical { // std::lock_guard<std::mutex> lock(_elem8_mutex); if (id2index_elements8.find(_element_id) != id2index_elements8.end()) throw(std::invalid_argument( "Trying to insert an element with same id twice:" + std::to_string(_element_id))); id2index_elements8.insert( std::pair<int32_t, size_t>(_element_id, elements8.size())); elements8.push_back(element); } break; case (Element::BEAM): #pragma omp critical { // std::lock_guard<std::mutex> lock(_elem2_mutex); if (id2index_elements2.find(_element_id) != id2index_elements2.end()) throw(std::invalid_argument( "Trying to insert an element with same id twice:" + std::to_string(_element_id))); this->id2index_elements2.insert( std::pair<int32_t, size_t>(_element_id, elements2.size())); this->elements2.push_back(element); } break; case (Element::TSHELL): #pragma omp critical { // std::lock_guard<std::mutex> lock(_elem4th_mutex); if (id2index_elements4th.find(_element_id) != id2index_elements4th.end()) throw(std::invalid_argument( "Trying to insert an element with same id twice:" + std::to_string(_element_id))); id2index_elements4th.insert( std::pair<int32_t, size_t>(_element_id, this->elements4th.size())); elements4th.push_back(element); } break; default: throw(std::invalid_argument( "Element with an invalid element type was tried to get inserted " "into the database.")); break; } return element; } /** Add an element to the database from node indexes * * @param _etype : type of the element * @param _elementID : id of the element * @param _part_id : id of the part the element belongs to * @param _node_indexes : indexes of nodes */ std::shared_ptr<Element> DB_Elements::add_elementByNodeIndex(const Element::ElementType _eType, int32_t _elementID, int32_t _part_id, const std::vector<size_t>& _node_indexes) { if (_elementID < 0) { throw(std::invalid_argument("Element-ID may not be negative!")); } // Find part const auto part = db_parts->get_partByID(_part_id); if (part == nullptr) { throw(std::invalid_argument( "Could not find part with id:" + std::to_string(_part_id) + " in db.")); } // Find (unique) nodes std::vector<std::shared_ptr<Node>> nodes; std::vector<int32_t> unique_node_ids; std::unordered_set<int32_t> node_ids_set; for (size_t iNode = 0; iNode < _node_indexes.size(); ++iNode) { // get node auto node = db_nodes->get_nodeByIndex(_node_indexes[iNode]); // check for duplicate auto old_size = node_ids_set.size(); node_ids_set.insert(node->get_nodeID()); if (node_ids_set.size() == old_size) continue; // get node nodes.push_back(node); unique_node_ids.push_back(node->get_nodeID()); } // Create element auto element = create_element_unchecked(_eType, _part_id, _elementID, unique_node_ids); // Register Element for (auto& node : nodes) node->add_element(element); part->add_element(element); return element; } /** Add an element to the database from node id * * @param _etype : type of the element * @param _elementID : id of the element * @param _part_id : id of the part the element belongs to * @param _node_ids : ids of nodes */ std::shared_ptr<Element> DB_Elements::add_elementByNodeID(const Element::ElementType _eType, int32_t _elementID, int32_t _part_id, const std::vector<int32_t>& _node_ids) { if (_elementID < 0) { throw(std::invalid_argument("Element-ID may not be negative!")); } // Find part const auto part = db_parts->get_partByID(_part_id); if (part == nullptr) { throw(std::invalid_argument( "Could not find part with id:" + std::to_string(_part_id) + " in db.")); } // Find (unique) nodes std::vector<std::shared_ptr<Node>> nodes; std::vector<int32_t> unique_node_ids; std::unordered_set<int32_t> node_ids_set; for (size_t iNode = 0; iNode < _node_ids.size(); ++iNode) { // get node (fast) size_t node_index = db_nodes->get_index_from_id(_node_ids[iNode]); auto node = db_nodes->get_nodeByIndex(node_index); // check for duplicate auto old_size = node_ids_set.size(); node_ids_set.insert(node->get_nodeID()); if (node_ids_set.size() == old_size) continue; // get node nodes.push_back(node); unique_node_ids.push_back(_node_ids[iNode]); } // Create element auto element = create_element_unchecked(_eType, _elementID, _part_id, unique_node_ids); // Register Element for (auto& node : nodes) node->add_element(element); part->add_element(element); return element; } /** Add an element coming from a D3plot file * * @param ElementType _eType : type of the element to add, enum in Element.hpp * @param int32_t _elementID : id of the element to add * @param std::vector<int32_t> _elementData : element data from d3plot, node * ids and * part * id * @return std::shared_ptr<Element> element : pointer to created instance * * Add an element to the db by it's ID and it's nodeIndexes. Throws an * exception * if one nodeIndex is invalid or if the elementID is already existing. */ std::shared_ptr<Element> DB_Elements::add_element_byD3plot(const Element::ElementType _eType, const int32_t _elementID, const std::vector<int32_t>& _elementData) { if (_elementID < 0) { throw(std::invalid_argument("Element-ID may not be negative!")); } // Find part // index is decremented once, since ls-dyna starts at 1 (fortran array // style) auto part = this->db_parts->get_partByIndex(_elementData.back() - 1); if (part == nullptr) { // part = this->db_parts->add_partByID(_elementData.back() - 1); throw(std::invalid_argument( "Could not find part with index:" + std::to_string(_elementData.back()) + " in db.")); } // Find nodes std::unordered_set<int32_t> node_id_set; // just for testing std::vector<int32_t> node_ids; std::vector<std::shared_ptr<Node>> nodes; for (size_t iNode = 0; iNode < _elementData.size() - 1; iNode++) { // last is mat // dyna starts at index 1 (fortran), this program at 0 of course auto _node = this->db_nodes->get_nodeByIndex(_elementData[iNode] - 1); // check if duplicate auto tmp = node_id_set.size(); node_id_set.insert(_elementData[iNode]); if (node_id_set.size() == tmp) continue; // add new node data nodes.push_back(_node); node_ids.push_back(_node->get_nodeID()); } // Create element auto element = create_element_unchecked(_eType, _elementID, part->get_partID(), node_ids); // Register Elements for (auto& node : nodes) { node->add_element(element); } part->add_element(element); return element; } /** Get the DynaInputFile pointer * @return DnyaInputFile* keyfile */ FEMFile* DB_Elements::get_femfile() { return this->femfile; } /** Get the node-db. * @return DB_Nodes* db_nodes */ DB_Nodes* DB_Elements::get_db_nodes() { return this->db_nodes; } /** Reserve memory for future elements * @param _type element type to apply reserve on * @param _size size to reserve internally * * Does nothing if _type is NONE. */ void DB_Elements::reserve(const Element::ElementType _type, const size_t _size) { switch (_type) { case Element::BEAM: elements2.reserve(_size); break; case Element::SHELL: elements4.reserve(_size); break; case Element::SOLID: elements8.reserve(_size); break; case Element::TSHELL: elements4th.reserve(_size); break; default: throw std::invalid_argument( "Can not reserve memory for an unknown ElementType: " + std::to_string(_type)); break; } } /** Get the number of in the db. * @return unsigned int32_t nElements : returns the total number of elements * in the db */ size_t DB_Elements::get_nElements(const Element::ElementType _type) const { switch (_type) { case Element::BEAM: return elements2.size(); case Element::SHELL: return elements4.size(); case Element::SOLID: return elements8.size(); case Element::TSHELL: return elements4th.size(); case Element::NONE: return elements4.size() + elements2.size() + elements8.size() + elements4th.size(); } throw(std::invalid_argument("Unknown element type specified.")); } /** Get the elements of the database of a certain type * * @param _type : optional filtering type * @return elems : std::vector of elements */ std::vector<std::shared_ptr<Element>> DB_Elements::get_elements(const Element::ElementType _type) { switch (_type) { case Element::BEAM: return elements2; case Element::SHELL: return elements4; case Element::SOLID: return elements8; case Element::TSHELL: return elements4th; case Element::NONE: { std::vector<std::shared_ptr<Element>> elems; elems.reserve(get_nElements(_type)); elems.insert(elems.end(), elements2.begin(), elements2.end()); elems.insert(elems.end(), elements4.begin(), elements4.end()); elems.insert(elems.end(), elements8.begin(), elements8.end()); elems.insert(elems.end(), elements4th.begin(), elements4th.end()); return elems; } } throw(std::invalid_argument("Unknown element type specified.")); } /** Get the element ids * * @param element_filter : filter type for elements * @return tensor */ Tensor_ptr<int32_t> DB_Elements::get_element_ids(Element::ElementType element_filter) { size_t element_offset = 0; auto tensor = std::make_shared<Tensor<int32_t>>(); tensor->resize({ this->get_nElements(element_filter) }); auto& data = tensor->get_data(); if (element_filter == Element::NONE || element_filter == Element::BEAM) { for (auto& elem : elements2) data[element_offset++] = elem->get_elementID(); } if (element_filter == Element::NONE || element_filter == Element::SHELL) { for (auto& elem : elements4) data[element_offset++] = elem->get_elementID(); } if (element_filter == Element::NONE || element_filter == Element::SOLID) { for (auto& elem : elements8) data[element_offset++] = elem->get_elementID(); } if (element_filter == Element::NONE || element_filter == Element::TSHELL) { for (auto& elem : elements4th) data[element_offset++] = elem->get_elementID(); } return tensor; } /** Get the node ids of elements * * @param element_type : type of the elements * @param n_nodes : number of nodes * @return tensor */ Tensor_ptr<int32_t> DB_Elements::get_element_node_ids(Element::ElementType element_type, size_t n_nodes) { size_t offset = 0; auto tensor = std::make_shared<Tensor<int32_t>>(); tensor->resize({ this->get_nElements(element_type), n_nodes }); auto& data = tensor->get_data(); switch (element_type) { case Element::BEAM: for (auto& elem : elements2) { if (elem->get_nNodes() == n_nodes) { const auto& node_ids = elem->get_node_ids(); std::copy(node_ids.begin(), node_ids.end(), data.begin() + offset); offset += node_ids.size(); } } break; case Element::SHELL: for (auto& elem : elements4) { if (elem->get_nNodes() == n_nodes) { const auto& node_ids = elem->get_node_ids(); std::copy(node_ids.begin(), node_ids.end(), data.begin() + offset); offset += node_ids.size(); } } break; case Element::SOLID: for (auto& elem : elements8) { if (elem->get_nNodes() == n_nodes) { const auto& node_ids = elem->get_node_ids(); std::copy(node_ids.begin(), node_ids.end(), data.begin() + offset); offset += node_ids.size(); } } break; case Element::TSHELL: for (auto& elem : elements4th) { if (elem->get_nNodes() == n_nodes) { const auto& node_ids = elem->get_node_ids(); std::copy(node_ids.begin(), node_ids.end(), data.begin() + offset); offset += node_ids.size(); } } break; case Element::NONE: default: break; } return tensor; } /** Get the energy of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_energy(Element::ElementType element_filter) { constexpr auto default_value = 0.; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize({ this->get_nElements(element_filter), nTimesteps }); auto& data = tensor->get_data(); auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_energy(); if (result.size() != 0) { std::copy(result.begin(), result.end(), data.begin() + offset); offset += nTimesteps; } else { std::fill(data.begin() + offset, data.begin() + offset + nTimesteps, default_value); offset += nTimesteps; } } return tensor; } /** Get the mises stress of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_stress_mises(Element::ElementType element_filter) { constexpr auto default_value = 0.; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize({ this->get_nElements(element_filter), nTimesteps }); auto& data = tensor->get_data(); auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_stress_mises(); if (result.size() != 0) { std::copy(result.begin(), result.end(), data.begin() + offset); offset += nTimesteps; } else { std::fill(data.begin() + offset, data.begin() + offset + nTimesteps, default_value); offset += nTimesteps; } } return tensor; } /** Get the plastic strain of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_plastic_strain(Element::ElementType element_filter) { constexpr auto default_value = 0.; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize tensor (nElems x nTimesteps) const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize({ this->get_nElements(element_filter), nTimesteps }); auto& data = tensor->get_data(); auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_plastic_strain(); if (result.size() != 0) { std::copy(result.begin(), result.end(), data.begin() + offset); offset += nTimesteps; } else { std::fill(data.begin() + offset, data.begin() + offset + nTimesteps, default_value); offset += nTimesteps; } } return tensor; } /** Get the strain of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_strain(Element::ElementType element_filter) { constexpr auto default_value = 0.; constexpr size_t nComponents = 6; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize (nElems x nTimesteps x nStrain) const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize( { this->get_nElements(element_filter), nTimesteps, nComponents }); auto& data = tensor->get_data(); auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_strain(); if (result.size() != 0) { #ifdef QD_DEBUG if (result.size() != nTimesteps) throw(std::runtime_error( "element timeseries has a wrong number of timesteps.")); #endif for (auto& vec : result) { #ifdef QD_DEBUG if (vec.size() != nComponents) throw(std::runtime_error("vector has wrong number of components:" + std::to_string(vec.size()) + " != " + std::to_string(nComponents))); #endif std::copy(vec.begin(), vec.end(), data.begin() + offset); offset += vec.size(); } } else { const auto tmp = nTimesteps * nComponents; std::fill( data.begin() + offset, data.begin() + offset + tmp, default_value); offset += tmp; } } return tensor; } /** Get the stress of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_stress(Element::ElementType element_filter) { constexpr auto default_value = 0.; constexpr size_t nComponents = 6; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize (nElems x nTimesteps x nStrain) const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize( { this->get_nElements(element_filter), nTimesteps, nComponents }); auto& data = tensor->get_data(); const auto element_offset = nTimesteps * nComponents; auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_stress(); if (result.size() != 0) { #ifdef QD_DEBUG if (result.size() != nTimesteps) throw(std::runtime_error( "element timeseries has a wrong number of timesteps.")); #endif for (auto& vec : result) { #ifdef QD_DEBUG if (vec.size() != nComponents) throw(std::runtime_error("vector has wrong number of components:" + std::to_string(vec.size()) + " != " + std::to_string(nComponents))); #endif std::copy(vec.begin(), vec.end(), data.begin() + offset); offset += vec.size(); } } else { std::fill(data.begin() + offset, data.begin() + offset + element_offset, default_value); offset += element_offset; } } return tensor; } /** Get the coords of elements * * @param element_filter : optional element filter * @return tensor : result data array * * If a value is not present for an element, the it will be initialized as 0 by * default. */ Tensor_ptr<float> DB_Elements::get_element_coords(Element::ElementType element_filter) { constexpr auto default_value = 0.; constexpr size_t nComponents = 3; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // resize (nElems x nTimesteps x nStrain) const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize( { this->get_nElements(element_filter), nTimesteps, nComponents }); auto& data = tensor->get_data(); const auto element_offset = nTimesteps * nComponents; auto elements = get_elements(element_filter); for (auto& element : elements) { auto result = element->get_coords(); if (result.size() != 0) { #ifdef QD_DEBUG if (result.size() != nTimesteps) throw(std::runtime_error( "element timeseries has a wrong number of timesteps.")); #endif for (auto& vec : result) { #ifdef QD_DEBUG if (vec.size() != nComponents) throw(std::runtime_error("vector has wrong number of components:" + std::to_string(vec.size()) + " != " + std::to_string(nComponents))); #endif std::copy(vec.begin(), vec.end(), data.begin() + offset); offset += vec.size(); } } else { std::fill(data.begin() + offset, data.begin() + offset + element_offset, default_value); offset += element_offset; } } return tensor; } /** Get the history vars for a specific element type * * @param element_type : type of the element * @return tensor : data array * * In contrast to all other array functions this function actually needs a * specific element type for the reason, that history vars usually differ * between the element types. We didn't screw this up! */ Tensor_ptr<float> DB_Elements::get_element_history_vars(Element::ElementType element_type) { // test if (element_type == Element::ElementType::NONE) throw(std::invalid_argument( "You need to specify an element type if " "requesting history variables for the reason, " "that history vars differ between the " "element types. Don't blame us, we didn't screw this up!")); constexpr auto default_value = 0.; size_t offset = 0; auto tensor = std::make_shared<Tensor<float>>(); // get the number of history vars ... little bit complicated auto elements = get_elements(element_type); const auto nComponents = elements.size() != 0 ? elements[0]->get_history_vars().size() : 0; // resize (nElems x nTimesteps x nStrain) const auto nTimesteps = get_femfile()->get_nTimesteps(); tensor->resize( { this->get_nElements(element_type), nTimesteps, nComponents }); auto& data = tensor->get_data(); const auto element_offset = nTimesteps * nComponents; for (auto& element : elements) { auto result = element->get_history_vars(); if (result.size() != 0) { #ifdef QD_DEBUG if (result.size() != nTimesteps) throw(std::runtime_error( "element timeseries has a wrong number of timesteps.")); #endif for (auto& vec : result) { #ifdef QD_DEBUG if (vec.size() != nComponents) throw(std::runtime_error("vector has wrong number of components:" + std::to_string(vec.size()) + " != " + std::to_string(nComponents))); #endif std::copy(vec.begin(), vec.end(), data.begin() + offset); offset += vec.size(); } } else { std::fill(data.begin() + offset, data.begin() + offset + element_offset, default_value); offset += element_offset; } } return tensor; } } // namespace qd
29.00813
79
0.640014
martinventer
1caec02ccb4ba824ff1e2d75823f90c070b3d911
1,362
hpp
C++
need to install for velocity smothor/ecl_time_lite/include/ecl/time_lite/macros.hpp
michaelczhou/control
c5ee58bf65c7d8e7517659a52169cea3e4e81d46
[ "MIT" ]
1
2022-03-11T03:31:15.000Z
2022-03-11T03:31:15.000Z
RasPi_Dev/ros_ws/src/third_packages/ecl/ecl_time_lite/include/ecl/time_lite/macros.hpp
bravetree/xtark_driver_dev
1708888161cf20c0d1f45c99d0da4467d69c26c8
[ "BSD-3-Clause" ]
null
null
null
RasPi_Dev/ros_ws/src/third_packages/ecl/ecl_time_lite/include/ecl/time_lite/macros.hpp
bravetree/xtark_driver_dev
1708888161cf20c0d1f45c99d0da4467d69c26c8
[ "BSD-3-Clause" ]
null
null
null
/** * @file /include/ecl/time_lite/macros.hpp * * @brief Macros for error-checking and program termination. * * Macros for error-checking and program termination. * * @date April 2013. **/ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef ECL_TIME_LITE_MACROS_HPP_ #define ECL_TIME_LITE_MACROS_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include <ecl/config/macros.hpp> /***************************************************************************** ** PreProcessing *****************************************************************************/ /* * Import/exports symbols for the library */ #ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries #ifdef ecl_time_lite_EXPORTS // we are building a shared lib/dll #define ecl_time_lite_PUBLIC ECL_HELPER_EXPORT #else // we are using shared lib/dll #define ecl_time_lite_PUBLIC ECL_HELPER_IMPORT #endif #define ecl_time_lite_LOCAL ECL_HELPERS_LOCAL #else // ecl is being built around static libraries #define ecl_time_lite_PUBLIC #define ecl_time_lite_LOCAL #endif #endif /* ECL_TIME_LITE_MACROS_HPP_*/
31.674419
78
0.499266
michaelczhou
1cb37e2cd6062198c9923ef3446250367fbe4e49
802
hpp
C++
include/pipes/override.hpp
LouisCharlesC/pipes
1100066894ceca3aebfc3e2fa12287600ab3a0f6
[ "MIT" ]
null
null
null
include/pipes/override.hpp
LouisCharlesC/pipes
1100066894ceca3aebfc3e2fa12287600ab3a0f6
[ "MIT" ]
null
null
null
include/pipes/override.hpp
LouisCharlesC/pipes
1100066894ceca3aebfc3e2fa12287600ab3a0f6
[ "MIT" ]
null
null
null
#ifndef BEGIN_HPP #define BEGIN_HPP #include "pipes/operator.hpp" #include "pipes/base.hpp" #include <iterator> #include <utility> namespace pipes { template<typename Iterator> class override_pipeline : public pipeline_base<override_pipeline<Iterator>> { public: template<typename T> void onReceive(T&& value) { *iterator_ = FWD(value); ++iterator_; } explicit override_pipeline(Iterator iterator) : iterator_(iterator) {} private: Iterator iterator_; }; template<typename Container> auto override(Container& container) { using std::begin; return override_pipeline<decltype(begin(std::declval<Container&>()))>{begin(container)}; } } #endif /* BEGIN_HPP */
21.675676
96
0.630923
LouisCharlesC
1cb66e935ca49d985104a89158474a839c9f6220
102,717
cpp
C++
Common/MapGuideCommon/Services/ProxyFeatureService.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Common/MapGuideCommon/Services/ProxyFeatureService.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Common/MapGuideCommon/Services/ProxyFeatureService.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // #include "MapGuideCommon.h" #include "ProxyFeatureService.h" #include "ProxyFeatureReader.h" #include "ProxySqlDataReader.h" #include "ProxyDataReader.h" #include "ProxyFeatureTransaction.h" #include "Command.h" #include "Services/SqlResult.h" static const int Feature_Service = (int)MgPacketParser::msiFeature; IMPLEMENT_CREATE_SERVICE(MgProxyFeatureService) ////////////////////////////////////////////////////////////////// /// <summary> /// Construct an MgProxyFeatureService object /// </summary> MgProxyFeatureService::MgProxyFeatureService() : MgFeatureService() { } ////////////////////////////////////////////////////////////////// /// <summary> /// Dispose this object /// </summary> /// <returns> /// Nothing /// </returns> void MgProxyFeatureService::Dispose() { delete this; } ////////////////////////////////////////////////////////////////// /// <summary> /// Sets the warnings if any /// </summary> void MgProxyFeatureService::SetWarning(MgWarnings* warning) { if (warning) { Ptr<MgStringCollection> ptrCol = warning->GetMessages(); this->m_warning->AddMessages(ptrCol); warning->Release(); } } ////////////////////////////////////////////////////////////////// /// <summary> /// This method returns list of all providers, their connection properties /// and (default or enumerated) values for these properties, if any, in XML /// format. /// /// Schema Definition: FeatureProviders.xsd /// Sample XML: FeatureProviders.xml /// </summary> /// <returns>Byte array representing XML (or error status) /// </returns> MgByteReader* MgProxyFeatureService::GetFeatureProviders() { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetFeatureProviders_Id,// Command Code 0, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// <summary> /// This method returns list of all values for the connection property /// specified based on partial connection string. To understand this, let /// us take an example: /// /// Oracle Provider for Fdo has 3 services running on each Machine A, Machine B /// and Machine C. /// /// <table> /// Machine IP Address ServiceName /// --------- ----------- ---------------------- /// Machine A 144.111.1.1 Canada, Europe, Russia /// Machine B 192.111.1.2 Japan, China, India /// Machine C 159.111.2.1 USA, Mexico, Australia /// </table> /// /// List of properties required for connection: /// <table> /// PropertyName Enumerable Values /// ------------ ---------- ------------------------------------------------- /// UserName No /// Password No /// IPAddress Yes 144.111.1.1 /// 192.111.1.2 /// 159.111.2.1 /// ServiceName Yes (This value is dependent on IPAddress /// and therefore value is unknown) /// /// DatabaseName Yes (This value is dependent on IPAddress+ServiceName /// and therefore value is unknown) /// </table> /// /// User builds partial connection string as /// UserName=test{ } Password=test{ } IPAddress=144.111.1.1 /// /// Using this partial connection string user requests values for ServiceName property. /// /// Internally Fdo provider, if it has some dependency on a certain property, it needs /// to look into property dictionary and find out if a dependent property values are already /// set. In this case it is an IPAddress only but there can be more than one property. /// /// If all dependent values are set, it will return the list of values for the dependent /// property values. The result for the above connectionString would be /// /// - Canada, /// - Europe, /// - Russia /// /// In case of SQLServer, we might have more than one database per service. Therefore /// once the list of services are retrieved, user builds another connectionString as /// /// UserName=test{ } Password=test{ } IPAddress=144.111.1.1{ } ServiceName=Canada /// /// and requests property values for "DatabaseName". This would result in list of /// databases available to the users e.g. /// /// - Alberta /// - British Columbia /// - Manitoba /// /// The final connectionString for Open would be /// /// UserName=test{ } Password=test{ } IPAddress=144.111.1.1{ } ServiceName=Canada{ } DatabaseName=Alberta /// </summary> /// /// <param name="propertyName">Input /// Name of property for which values need to be retrieved. (Can not be NULL) /// </param> /// /// <param name="partialConnString">Input /// Partial connection string on which property request is dependent. /// NULL value indicates no dependency. /// </param> /// /// <returns> /// String Collection or NULL if nothing is found /// </returns> MgStringCollection* MgProxyFeatureService::GetConnectionPropertyValues(CREFSTRING providerName, CREFSTRING propertyName, CREFSTRING partialConnString) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetConnectionPropertyValues_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &providerName, // Argument#1 MgCommand::knString, &propertyName, // Argument#1 MgCommand::knString, &partialConnString, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgStringCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// <summary> /// Attempts to connect to the Feature Provider given by the connection string /// </summary> /// <param name="connectionString"> /// Connection string for Feature Provider /// </param> /// <returns> /// True if connection was successful /// </returns> bool MgProxyFeatureService::TestConnection(CREFSTRING providerName, CREFSTRING connectionString) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::TestConnection_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &providerName, // Argument#1 MgCommand::knString, &connectionString, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// /// <summary> /// Attempts to connect to the Feature Provider given by the connection string /// </summary> /// <param name="connectionString"> /// Connection string for Feature Provider /// </param> /// <returns> /// True if connection was successful /// </returns> bool MgProxyFeatureService::TestConnection(MgResourceIdentifier* resource) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::TestConnectionWithResource_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// /// <summary> /// This method returns capabilities of the provider applicable for the /// connection. This would provide details on the following /// capabilities: /// 1. Connection /// 2. Schema /// 3. Command /// 4. Filter /// 5. Expression /// /// Schema Definition: FeatureProviderCapabilities.xsd /// Sample XML: FeatureProviderCapabilities.xml /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <returns> /// Byte array representing XML (or NULL) /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// NOTE: /// Subject to change with FDO R2 MgByteReader* MgProxyFeatureService::GetCapabilities(CREFSTRING providerName) { STRING connectionString = L""; return GetCapabilities(providerName, connectionString); } ////////////////////////////////////////////////////////////////// MgByteReader* MgProxyFeatureService::GetCapabilities(CREFSTRING providerName, CREFSTRING connectionString) { Ptr<MgUserInformation> userInfo = m_connProp->GetUserInfo(); MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetCapabilities_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id userInfo->GetApiVersion(), // Operation version MgCommand::knString, &providerName, // Argument#1 MgCommand::knString, &connectionString, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// <summary> /// Creates or updates a feature schema within the specified feature source. /// </summary> /// <param name="resource">Input /// A resource identifier referring to a feature source. /// </param> /// <param name="schema">Input /// Input schema to be created or updated. /// </param> /// <returns> /// Returns nothing. /// </returns> void MgProxyFeatureService::ApplySchema(MgResourceIdentifier* resource, MgFeatureSchema* schema) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knVoid, // Return type expected MgFeatureServiceOpId::ApplySchema_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knObject, schema, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); } /////////////////////////////////////////////////////////////////////////////// /// \brief /// Gets the definitions of one or more schemas contained in the /// feature source for particular classes. If the specified schema name or /// a class name does not exist, this method will throw an exception. /// MgFeatureSchemaCollection* MgProxyFeatureService::DescribeSchema(MgResourceIdentifier* resource, CREFSTRING schemaName, MgStringCollection* classNames) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::DescribeSchema_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knObject, classNames, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgFeatureSchemaCollection*)cmd.GetReturnValue().val.m_obj; } /////////////////////////////////////////////////////////////////////////////// /// This method has been deprecated. Use the above method. /// MgFeatureSchemaCollection* MgProxyFeatureService::DescribeSchema(MgResourceIdentifier* resource, CREFSTRING schemaName) { return DescribeSchema(resource, schemaName, NULL); } /////////////////////////////////////////////////////////////////////////////// /// \brief /// Gets the definitions in XML format of one or more schemas contained in the /// feature source for particular classes. If the specified schema name or /// a class name does not exist, this method will throw an exception. /// STRING MgProxyFeatureService::DescribeSchemaAsXml(MgResourceIdentifier* resource, CREFSTRING schemaName, MgStringCollection* classNames) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knString, // Return type expected MgFeatureServiceOpId::DescribeSchemaAsXml_Id,// Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knObject, classNames, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); STRING retVal = *(cmd.GetReturnValue().val.m_str); delete cmd.GetReturnValue().val.m_str; return retVal; } /////////////////////////////////////////////////////////////////////////////// /// This method has been deprecated. Use the above method. /// STRING MgProxyFeatureService::DescribeSchemaAsXml(MgResourceIdentifier* resource, CREFSTRING schemaName) { return DescribeSchemaAsXml(resource, schemaName, NULL); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method returns the Fdo schema information in XML format /// for the MgFeatureSchemaCollection object provided /// </summary> /// <param name="schema">Input /// A resource identifier referring to connection string /// </param> /// <returns> /// STRING representing XML /// </returns> /// /// EXCEPTIONS: /// MgNullArgumentException STRING MgProxyFeatureService::SchemaToXml(MgFeatureSchemaCollection* schema) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knString, // Return type expected MgFeatureServiceOpId::SchemaToXml_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, schema, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); ///KNN: is this correct? STRING retVal = *(cmd.GetReturnValue().val.m_str); delete cmd.GetReturnValue().val.m_str; return retVal; } ////////////////////////////////////////////////////////////////// /// <summary> /// This method creates MgFeatureSchemaCollection using /// XML schema provided /// </summary> /// <param name="xml">Input /// A string containg xml /// </param> /// <returns> /// MgFeatureSchemaCollection /// </returns> /// /// EXCEPTIONS: /// MgNullArgumentException MgFeatureSchemaCollection* MgProxyFeatureService::XmlToSchema(CREFSTRING xml) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::XmlToSchema_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &xml, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgFeatureSchemaCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// <summary> /// Select features returns feature information from an Fdo Provider. An MgFeatureReader /// object provides one way, read-only iteration over the features. The various properties /// of a feature class are accessed by name using methods of the MgFeatureReader. /// /// The desired feature class is specified by name. A subset of the feature properties /// can be specified using the properties string collection. Futhermore, an Fdo filter text /// can be applied to limit the result set. /// </summary> /// <param name="resource">Input /// A resource identifier referring to feature source /// </param> /// <param name="className">Input /// A valid class name on which select operation needs to be executed. It should not be NULL. /// </param> /// <param name="options">Input /// MgFeatureQueryOptions instance containing all required filters for this select operation /// </param> /// <returns> /// MgFeatureReader which operates on the instance of actual reader returned from the /// FdoProvider. /// </returns> /// EXCEPTIONS: /// MgFeatureSourceException /// MgInvalidArgumentException /// MgFdoException /// NOTE: /// 1. Please refer to Overview section of this document or Fdo provider documents /// for details on connection properties, schema, classes, class proeprties and /// filter text. /// 2. Interrogation of class definition would allow to determine properties of classes /// which can be used for filter text. MgFeatureReader* MgProxyFeatureService::SelectFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgFeatureQueryOptions* options) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::SelectFeatures_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, options, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// Select features returns feature information from an Fdo Provider. An MgFeatureReader /// object provides one way, read-only iteration over the features. The various properties /// of a feature class are accessed by name using methods of the MgFeatureReader. /// /// The desired feature class is specified by name. A subset of the feature properties /// can be specified using the properties string collection. Futhermore, an Fdo filter text /// can be applied to limit the result set. The expected expected coordinate system name can /// be specified. /// </summary> /// <param name="resource">Input /// A resource identifier referring to feature source /// </param> /// <param name="className">Input /// A valid class name on which select operation needs to be executed. It should not be NULL. /// </param> /// <param name="options">Input /// MgFeatureQueryOptions instance containing all required filters for this select operation /// </param> /// <param name="coordinateSystem">Input /// A valid coordinate system name. Retrieved features will be in the specified coordinate system. /// </param> /// <returns> /// MgFeatureReader which operates on the instance of actual reader returned from the /// FdoProvider. /// </returns> /// EXCEPTIONS: /// MgFeatureSourceException /// MgInvalidArgumentException /// MgFdoException /// NOTE: /// 1. Please refer to Overview section of this document or Fdo provider documents /// for details on connection properties, schema, classes, class proeprties and /// filter text. /// 2. Interrogation of class definition would allow to determine properties of classes /// which can be used for filter text. MgFeatureReader* MgProxyFeatureService::SelectFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgFeatureQueryOptions* options, CREFSTRING coordinateSystem) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::SelectFeaturesWithTransform, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, options, // Argument#3 MgCommand::knString, &coordinateSystem, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// This operation allows user to select features and then combine them into a group (means aggregate them). /// Once the features are grouped together into a single set of data, they do not represent features, in other /// words, they do not corresponds to underlying database schema. Therefore, this operation returns MgDataReader. /// Computed properties applied in SelectFeatures would only be applicable per feature. For example, a polygon feature /// can compute its area while retriveal. The area would be computed property for a specific feature instance. /// In SelectAggregate operation, user might want to group all area for a particular zone and sum them to /// find total area based on certain criteria. The total area of a particular zone does not represent a feature instance (row). /// /// To find about aggregate functionalities available, please refer to GetCapabilities document returned by GetCapabilities /// operation. /// </summary> /// <param name="resource">Input /// A resource identifier referring to feature source /// </param> /// <param name="className">Input /// A valid class name on which select operation needs to be executed. It should not be NULL. /// </param> /// <param name="options">Input /// MgFeatureAggregateOptions instance containing all required filters for this select operation /// </param> /// <returns> /// MgDataReader pointer which operates on the instance of actual reader returned from the /// FdoProvider (OR NULL). /// </returns> /// EXCEPTIONS: /// MgFeatureSourceException /// MgInvalidArgumentException /// MgFdoException /// /// NOTE: /// 1. Please refer to Overview section of this document or Fdo provider documents /// for details on connection properties, schema, classes, class proeprties, /// filter text and spatial operations. /// 2. Please refer to Geometry API documentation for Geometry details. /// 3. Interrogation of provider capabilities will inform list of operations supported /// 4. Interrogation of class definition would allow to determine properties of classes /// which can be used for filter text. MgDataReader* MgProxyFeatureService::SelectAggregate(MgResourceIdentifier* resource, CREFSTRING className, MgFeatureAggregateOptions* options) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::SelectAggregate_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, options, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyDataReader> dataReader = (MgProxyDataReader*)cmd.GetReturnValue().val.m_obj; if (dataReader != NULL) dataReader->SetService(this); // Data reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyDataReader*)dataReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// It executes all the commands specified in command collection. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="commands">Input /// Collection of commands to be executed /// </param> /// <param name="useTransaction">Input /// true - all commands will be executed in transaction /// false - not to use transaction /// </param> /// <returns> /// Integer collection referring to result for each command /// Index of commandCollection and index of IntCollection would match the result. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer MgPropertyCollection* MgProxyFeatureService::UpdateFeatures(MgResourceIdentifier* resource, MgFeatureCommandCollection* commands, bool useTransaction) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::UpdateFeatures_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knObject, commands, // Argument#2 MgCommand::knInt8, (INT8)useTransaction, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgPropertyCollection> propCol = (MgPropertyCollection*)cmd.GetReturnValue().val.m_obj; if (propCol != NULL) { INT32 cnt = propCol->GetCount(); for (INT32 i=0; i < cnt; i++) { Ptr<MgProperty> prop = propCol->GetItem(i); INT32 propType = prop->GetPropertyType(); if (propType == MgPropertyType::Feature) { MgFeatureProperty* featProp = ((MgFeatureProperty*)((MgProperty*)prop)); Ptr<MgProxyFeatureReader> reader = (MgProxyFeatureReader*)featProp->GetValue(); if (reader != NULL) { reader->SetService(this); } } } } return SAFE_ADDREF((MgPropertyCollection*)propCol); } ////////////////////////////////////////////////////////////////// /// <summary> /// It executes all the commands specified in command collection /// within the given transaction. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="commands">Input /// Collection of commands to be executed /// </param> /// <param name="transaction">Input /// The MgTransaction instance on which the commands /// will be executed. /// </param> /// <returns> /// Integer collection referring to result for each command /// Index of commandCollection and index of IntCollection would match the result. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer MgPropertyCollection* MgProxyFeatureService::UpdateFeatures(MgResourceIdentifier* resource, MgFeatureCommandCollection* commands, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::UpdateFeaturesWithTransaction_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knObject, commands, // Argument#2 MgCommand::knString, &transactionId, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgPropertyCollection> propCol = (MgPropertyCollection*)cmd.GetReturnValue().val.m_obj; if (propCol != NULL) { INT32 cnt = propCol->GetCount(); for (INT32 i=0; i < cnt; i++) { Ptr<MgProperty> prop = propCol->GetItem(i); INT32 propType = prop->GetPropertyType(); if (propType == MgPropertyType::Feature) { MgFeatureProperty* featProp = ((MgFeatureProperty*)((MgProperty*)prop)); Ptr<MgProxyFeatureReader> reader = (MgProxyFeatureReader*)featProp->GetValue(); if (reader != NULL) { reader->SetService(this); } } } } return SAFE_ADDREF((MgPropertyCollection*)propCol); } //////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets the locked features /// </summary> /// /// <param name="resource">Input /// A resource identifier for the feature source. /// </param> /// <param name="className">Input /// The name of the feature class on which /// the select operation is performed. /// </param> /// <param name="options">Input /// An MgFeatureAggregateOptions instance /// containing all the criteria and filters /// required for this select operation. /// <param> /// <returns> /// Returns an MgFeatureReader containing the locked features. /// </returns> /// /// EXCEPTIONS: /// MgFeatureServiceException /// MgInvalidArgumentException MgFeatureReader* MgProxyFeatureService::GetLockedFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgFeatureQueryOptions* options) { throw new MgNotImplementedException( L"MgProxyFeatureService::GetLockedFeatures", __LINE__, __WFILE__, NULL, L"", NULL); return NULL; // to make some compiler happy } //////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Starts a transaction on the specified feature source /// /// NOTE: /// The returned MgTransaction instance has to be used along with ExecuteSqlQuery(), /// ExecuteSqlNonQuery() or UpdateFeatures() taking MgTransaction as a parameter. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <returns> /// Returns an MgTransaction instance (or NULL). /// </returns> /// /// EXCEPTIONS: /// MgFeatureServiceException /// MgInvalidArgumentException /// MgInvalidOperationException /// MgFdoException MgTransaction* MgProxyFeatureService::BeginTransaction(MgResourceIdentifier* resource) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::BeginFeatureTransaction_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureTransaction> featTransaction = (MgProxyFeatureTransaction*)cmd.GetReturnValue().val.m_obj; if (featTransaction != NULL) featTransaction->SetService(this); // Feature transaction on proxy side would store proxy service to call Commit() or Rollback() return SAFE_ADDREF((MgProxyFeatureTransaction*)featTransaction); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes the SELECT SQL statement specified and returns a pointer to /// SqlDataReader instance. This instance can be used to retrieve column information /// and related values. /// /// NOTE: /// Serialize() method of SqlDataReader would be able to convert data returned /// to AWKFF or XML stream. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="sqlStatement">Input /// This would allow users to specify free format SQL SELECT statement like /// SELECT * FROM CLASSNAME WHERE COLOR = RED. This would return all rows /// from "CLASSNAME" where COLOR column has value RED. /// </param> /// <returns> /// SqlDataReader pointer, an instance of reader pointing to the actual reader /// from FdoProvider (or NULL). /// /// If any statement other than SELECT is passed to this method, it would return failure. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// MgInvalidSqlStatement /// MgSqlNotSupported MgSqlDataReader* MgProxyFeatureService::ExecuteSqlQuery(MgResourceIdentifier* resource, CREFSTRING sqlStatement) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::ExecuteSqlQuery_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &sqlStatement, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxySqlDataReader> sqlReader = (MgProxySqlDataReader*)cmd.GetReturnValue().val.m_obj; if (sqlReader != NULL) sqlReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxySqlDataReader*)sqlReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes the SELECT SQL statement specified within a given transaction /// and returns a pointer to SqlDataReader instance. This instance can be used to /// retrieve column information and related values. /// /// NOTE: /// Serialize() method of SqlDataReader would be able to convert data returned /// to AWKFF or XML stream. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="sqlStatement">Input /// This would allow users to specify free format SQL SELECT statement like /// SELECT * FROM CLASSNAME WHERE COLOR = RED. This would return all rows /// from "CLASSNAME" where COLOR column has value RED. /// </param> /// <param name="params">Input&Output /// Parameters binded to the SQL statement. /// </param> /// <param name="transaction">Input /// The transaction object on which the sql statement will be executed. /// </param> /// <returns> /// SqlDataReader pointer, an instance of reader pointing to the actual reader /// from FdoProvider (or NULL). /// /// If any statement other than SELECT is passed to this method, it would return failure. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// MgInvalidSqlStatement /// MgSqlNotSupported MgSqlDataReader* MgProxyFeatureService::ExecuteSqlQuery(MgResourceIdentifier* resource, CREFSTRING sqlStatement, MgParameterCollection* params, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::ExecuteSqlQueryWithTransaction_Id, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &sqlStatement, // Argument#2 MgCommand::knObject, params, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxySqlDataReader> sqlReader = (MgProxySqlDataReader*)cmd.GetReturnValue().val.m_obj; if (sqlReader != NULL) sqlReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxySqlDataReader*)sqlReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes the SELECT SQL statement specified within a given transaction /// and returns a pointer to SqlDataReader instance. This instance can be used to /// retrieve column information and related values. /// /// NOTE: /// Serialize() method of SqlDataReader would be able to convert data returned /// to AWKFF or XML stream. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="sqlStatement">Input /// This would allow users to specify free format SQL SELECT statement like /// SELECT * FROM CLASSNAME WHERE COLOR = RED. This would return all rows /// from "CLASSNAME" where COLOR column has value RED. /// </param> /// <param name="params">Input&Output /// Parameters binded to the SQL statement. /// </param> /// <param name="transaction">Input /// The transaction object on which the sql statement will be executed. /// </param> /// <param name="fetchSize">Input /// The fetch size of query. This method returns all data of query if /// setting the fetch size to 0. /// </param> /// <returns> /// SqlDataReader pointer, an instance of reader pointing to the actual reader /// from FdoProvider (or NULL). /// /// If any statement other than SELECT is passed to this method, it would return failure. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// MgInvalidSqlStatement /// MgSqlNotSupported MgSqlDataReader* MgProxyFeatureService::ExecuteSqlQuery(MgResourceIdentifier* resource, CREFSTRING sqlStatement, MgParameterCollection* params, MgTransaction* transaction, INT32 fetchSize) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::ExecuteSqlQueryWithTransaction_Id, // Command Code 5, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &sqlStatement, // Argument#2 MgCommand::knObject, params, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knInt32, fetchSize, // Argument#5 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); MgSqlResult * pResult = (MgSqlResult *)cmd.GetReturnValue().val.m_obj; if(params != NULL) { Ptr<MgParameterCollection> retParams = pResult->GetParameters(); for(int i = 0; i < retParams->GetCount(); i++) { Ptr<MgParameter> para = params->GetItem(i); Ptr<MgParameter> newpara = retParams->GetItem(i); Ptr<MgNullableProperty> prop = newpara->GetProperty(); para->SetProperty(prop); } } Ptr<MgProxySqlDataReader> sqlReader = (MgProxySqlDataReader *)pResult->GetReader(); if (sqlReader != NULL) sqlReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxySqlDataReader*)sqlReader); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes all SQL statements supported by providers except SELECT. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="sqlNonSelectStatement">Input /// This would allow users to specify free format SQL statement like INSERT/UPDATE/DELETE/CREATE /// </param> /// <returns> /// An positive integer value indicating how many instances (rows) have been affected. /// /// NOTE: It is possible that only few rows were affected than actually expected. /// In this scenario, warning object will contain the details on the failed records. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer INT32 MgProxyFeatureService::ExecuteSqlNonQuery(MgResourceIdentifier* resource, CREFSTRING sqlNonSelectStatement) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt32, // Return type expected MgFeatureServiceOpId::ExecuteSqlNonQuery_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &sqlNonSelectStatement, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i32; } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes all SQL statements supported by providers except SELECT /// within a given transaction. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="sqlNonSelectStatement">Input /// This would allow users to specify free format SQL statement like INSERT/UPDATE/DELETE/CREATE /// </param> /// <param name="params">Input&Output /// Parameters binded to the SQL statement. /// </param> /// <param name="transaction">Input /// The transaction object on which the sql statement will be executed. /// </param> /// <returns> /// An positive integer value indicating how many instances (rows) have been affected. /// /// NOTE: It is possible that only few rows were affected than actually expected. /// In this scenario, warning object will contain the details on the failed records. /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer INT32 MgProxyFeatureService::ExecuteSqlNonQuery(MgResourceIdentifier* resource, CREFSTRING sqlNonSelectStatement, MgParameterCollection* params, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::ExecuteSqlNonQueryWithTransaction_Id, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &sqlNonSelectStatement, // Argument#2 MgCommand::knObject, params, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); MgSqlResult * pResult = (MgSqlResult *)cmd.GetReturnValue().val.m_obj; if(params != NULL) { Ptr<MgParameterCollection> retParams = pResult->GetParameters(); for(int i = 0; i < retParams->GetCount(); i++) { Ptr<MgParameter> para = params->GetItem(i); Ptr<MgParameter> newpara = retParams->GetItem(i); Ptr<MgNullableProperty> prop = newpara->GetProperty(); para->SetProperty(prop); } } return pResult->GetRowAffected(); } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes the SELECT statement to return all available spatial context /// for the provider. The information for spatial contexts will be retrieved via /// SpatialContextReader instance returned. /// NOTE: /// Serialize() method of SpatialContextReader would be able to convert data returned from /// SpatialContextReader to binary stream for transmission or XML. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="bActiveOnly">Input /// This flag is obsolete and no longer used. /// </param> /// <returns> /// SpatialContextReader pointer, a pointer to the actual instance reader returned from the /// FdoProvider (or NULL). /// /// This reader can be utilized to retrieve the following information /// Name - Spatial Context name /// Description - Brief information about spatial context /// CoordinateSystem - /// ExtentType - Static/Dynamic /// Extent - AWKB/AWKT byte/text array representing the boundary /// of the extent. /// XYTolerance - Double /// ZTolerance - Double /// IsActive Boolean /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// NOTE: /// Subject to change in FDO R2 MgSpatialContextReader* MgProxyFeatureService::GetSpatialContexts(MgResourceIdentifier* resource, bool bActiveOnly) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetSpatialContexts_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knInt8, (INT8)bActiveOnly, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgSpatialContextReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// <summary> /// This method executes the SELECT statement to return all available Long transactions /// for the provider. The information for long transactions will be retrieved via /// MgLongTransactionReader instance returned. /// NOTE: /// Serialize() method of SpatialContextReader would be able to convert data returned from /// SpatialContextReader to XML. /// </summary> /// <param name="resource">Input /// A resource identifier referring to connection string /// </param> /// <param name="bActiveOnly">Input /// This flag would decide whether it should return all or active long transaction. /// True - Only active spatial context /// False - All spatial contexts /// </param> /// <returns> /// MgLongTransactionReader pointer, a pointer to the actual instance reader returned from the /// FdoProvider (or NULL). /// /// This reader can be utilized to retrieve the following information /// Name - Spatial Context name /// Description - Brief information about spatial context /// Owner - Owner of this long transaction /// IsActive Boolean /// IsFrozen - /// </returns> /// /// EXCEPTIONS: /// MgInvalidResourceIdentifer /// NOTE: /// Subject to change in FDO R2 MgLongTransactionReader* MgProxyFeatureService::GetLongTransactions(MgResourceIdentifier* resource, bool bActiveOnly) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetLongTransactions_Id,// Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knInt8, (INT8)bActiveOnly, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgLongTransactionReader*)cmd.GetReturnValue().val.m_obj; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Set the active long transaction name for a feature source. /// /// The long transaction name is associated with the caller's session. If /// no session is set then the method throws an MgSessionNotFoundException. /// </summary> /// <param name="featureSourceId">Input /// A resource identifier identifying a feature source in the repository. /// </param> /// <param name="longTransactionName">Input /// The long transaction name to set. /// </param> /// <returns> /// Returns true if the name was successfully set; otherwise /// returns false. /// </returns> /// /// EXCEPTIONS: /// MgNullArgumentException /// MgInvalidResourceTypeException /// MgSessionNotFoundException bool MgProxyFeatureService::SetLongTransaction(MgResourceIdentifier* featureSourceId, CREFSTRING longTransactionName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::SetLongTransaction_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, featureSourceId, // Argument#1 MgCommand::knString, &longTransactionName, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// // Retrieves WFS schema information for the specified feature classes MgByteReader* MgProxyFeatureService::DescribeWfsFeatureType(MgResourceIdentifier* featureSourceId, MgStringCollection* featureClasses) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::DescribeWfsFeatureType_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, featureSourceId, // Argument#1 MgCommand::knObject, featureClasses, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// // Retrieves WFS schema information for the specified feature classes with specified format MgByteReader* MgProxyFeatureService::DescribeWfsFeatureType(MgResourceIdentifier* featureSourceId, MgStringCollection* featureClasses, CREFSTRING namespacePrefix, CREFSTRING namespaceUrl) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::DescribeWfsFeatureType_Id, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(2,3,0), // Operation version MgCommand::knObject, featureSourceId, // Argument#1 MgCommand::knObject, featureClasses, // Argument#2 MgCommand::knString, &namespacePrefix, // Argument#3 MgCommand::knString, &namespaceUrl, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// // Retrieves feature information in WFS format, based on the specified criteria MgByteReader* MgProxyFeatureService::GetWfsFeature(MgResourceIdentifier* featureSourceId, CREFSTRING featureClass, MgStringCollection* requiredProperties, CREFSTRING srs, CREFSTRING filter, INT32 maxFeatures) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetWfsFeature_Id, // Command Code 6, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, featureSourceId, // Argument#1 MgCommand::knString, &featureClass, // Argument#2 MgCommand::knObject, requiredProperties, // Argument#3 MgCommand::knString, &srs, // Argument#4 MgCommand::knString, &filter, // Argument#5 MgCommand::knInt32, maxFeatures, // Argument#6 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// // Retrieves feature information in with specified WFS format, based on the specified criteria MgByteReader* MgProxyFeatureService::GetWfsFeature(MgResourceIdentifier* featureSourceId, CREFSTRING featureClass, MgStringCollection* requiredProperties, CREFSTRING srs, CREFSTRING filter, INT32 maxFeatures, CREFSTRING wfsVersion, CREFSTRING outputFormat, CREFSTRING sortCriteria, CREFSTRING namespacePrefix, CREFSTRING namespaceUrl) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetWfsFeature_Id, // Command Code 11, // No of arguments Feature_Service, // Service Id BUILD_VERSION(2,3,0), // Operation version MgCommand::knObject, featureSourceId, // Argument#1 MgCommand::knString, &featureClass, // Argument#2 MgCommand::knObject, requiredProperties, // Argument#3 MgCommand::knString, &srs, // Argument#4 MgCommand::knString, &filter, // Argument#5 MgCommand::knInt32, maxFeatures, // Argument#6 MgCommand::knString, &wfsVersion, // Argument#7 MgCommand::knString, &outputFormat, // Argument#8 MgCommand::knString, &sortCriteria, // Argument#9 MgCommand::knString, &namespacePrefix, // Argument#10 MgCommand::knString, &namespaceUrl, // Argument#11 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// MgBatchPropertyCollection* MgProxyFeatureService::GetFeatures(CREFSTRING featureReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetFeatures_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &featureReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgBatchPropertyCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::CloseFeatureReader(CREFSTRING featureReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::CloseFeatureReader_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &featureReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// MgBatchPropertyCollection* MgProxyFeatureService::GetSqlRows(CREFSTRING sqlReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetSqlRows_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &sqlReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgBatchPropertyCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::CloseSqlReader(CREFSTRING sqlReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::CloseSqlReader_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &sqlReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// MgStringCollection* MgProxyFeatureService::GetSchemas(MgResourceIdentifier* resource) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetSchemas_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgStringCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// MgStringCollection* MgProxyFeatureService::GetClasses(MgResourceIdentifier* resource, CREFSTRING schemaName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetClasses_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgStringCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// MgClassDefinition* MgProxyFeatureService::GetClassDefinition(MgResourceIdentifier* resource, CREFSTRING schemaName, CREFSTRING className) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetClassDefinition_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knString, &className, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgClassDefinition*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// MgByteReader* MgProxyFeatureService::GetRaster(CREFSTRING reader, INT32 xSize, INT32 ySize, STRING propName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetRaster_Id, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &reader, // Argument#1 MgCommand::knInt32, xSize, // Argument#2 MgCommand::knInt32, ySize, // Argument#3 MgCommand::knString, &propName, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// MgBatchPropertyCollection* MgProxyFeatureService::GetDataRows(CREFSTRING dataReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetDataRows_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &dataReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgBatchPropertyCollection*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::CloseDataReader(CREFSTRING dataReader) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::CloseDataReader_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &dataReader, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// void MgProxyFeatureService::CreateFeatureSource(MgResourceIdentifier* resource, MgFeatureSourceParams* sourceParams) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knVoid, // Return type expected MgFeatureServiceOpId::CreateFeatureSource_Id,// Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knObject, sourceParams, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); } ////////////////////////////////////////////////////////////////// // Returns the collection of identity properties for the specified class. // If schemaName is empty, then className needs to be fully qualified. MgClassDefinitionCollection* MgProxyFeatureService::GetIdentityProperties(MgResourceIdentifier* resource, CREFSTRING schemaName, MgStringCollection* classNames) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetIdentityProperties_Id, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(2,1,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knObject, classNames, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgClassDefinitionCollection*)cmd.GetReturnValue().val.m_obj; } MgByteReader* MgProxyFeatureService::EnumerateDataStores(CREFSTRING providerName, CREFSTRING partialConnString) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::EnumerateDataStores_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &providerName, // Argument#1 MgCommand::knString, &partialConnString, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } MgByteReader* MgProxyFeatureService::GetSchemaMapping(CREFSTRING providerName, CREFSTRING partialConnString) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetSchemaMapping_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &providerName, // Argument#1 MgCommand::knString, &partialConnString, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgByteReader*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// /// \brief /// Sets the connection properties for the Proxy Service. This /// information tells the proxy object where to connect. /// /// \param connProp /// Connection properties for server /// void MgProxyFeatureService::SetConnectionProperties(MgConnectionProperties* connProp) { m_connProp = SAFE_ADDREF(connProp); } ////////////////////////////////////////////////////////////////// /// <summary> /// Get the FDO cache information. /// </summary> /// <returns> /// The FDO cache information. /// </returns> STRING MgProxyFeatureService::GetFdoCacheInfo() { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knString, // Return type expected MgFeatureServiceOpId::GetFdoCacheInfo_Id, // Command Code 0, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); STRING retVal = *(cmd.GetReturnValue().val.m_str); delete cmd.GetReturnValue().val.m_str; return retVal; } ////////////////////////////////////////////////////////////////// MgClassDefinition* MgProxyFeatureService::GetClassDefinition(MgResourceIdentifier* resource, CREFSTRING schemaName, CREFSTRING className, bool serialize) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::GetClassDefinition2_Id, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &schemaName, // Argument#2 MgCommand::knString, &className, // Argument#3 MgCommand::knInt8, (INT8)serialize, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (MgClassDefinition*)cmd.GetReturnValue().val.m_obj; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::CommitTransaction(CREFSTRING transactionId) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::CommitFeatureTransaction_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &transactionId, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::RollbackTransaction(CREFSTRING transactionId) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::RollbackFeatureTransaction_Id, // Command Code 1, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &transactionId, // Argument#1 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return (bool)cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// STRING MgProxyFeatureService::AddSavePoint(CREFSTRING transactionId, CREFSTRING suggestName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knString, // Return type expected MgFeatureServiceOpId::AddSavePoint_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &transactionId, // Argument#1 MgCommand::knString, &suggestName, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); STRING retVal = *(cmd.GetReturnValue().val.m_str); delete cmd.GetReturnValue().val.m_str; return retVal; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::RollbackSavePoint(CREFSTRING transactionId, CREFSTRING savePointName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::RollbackSavePoint_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &transactionId, // Argument#1 MgCommand::knString, &savePointName, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i8; } ////////////////////////////////////////////////////////////////// bool MgProxyFeatureService::ReleaseSavePoint(CREFSTRING transactionId, CREFSTRING savePointName) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt8, // Return type expected MgFeatureServiceOpId::ReleaseSavePoint_Id, // Command Code 2, // No of arguments Feature_Service, // Service Id BUILD_VERSION(1,0,0), // Operation version MgCommand::knString, &transactionId, // Argument#1 MgCommand::knString, &savePointName, // Argument#2 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i8; } MgFeatureReader* MgProxyFeatureService::InsertFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgPropertyCollection* propertyValues) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::InsertFeatures, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, propertyValues, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } MgFeatureReader* MgProxyFeatureService::InsertFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgPropertyCollection* propertyValues, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::InsertFeatures, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, propertyValues, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } MgFeatureReader* MgProxyFeatureService::InsertFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgBatchPropertyCollection* batchPropertyValues) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::InsertFeatures2, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, batchPropertyValues, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } MgFeatureReader* MgProxyFeatureService::InsertFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgBatchPropertyCollection* batchPropertyValues, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knObject, // Return type expected MgFeatureServiceOpId::InsertFeatures2, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, batchPropertyValues, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); Ptr<MgProxyFeatureReader> featReader = (MgProxyFeatureReader*)cmd.GetReturnValue().val.m_obj; if (featReader != NULL) featReader->SetService(this); // Feature reader on proxy side would store proxy service to call GetFeatures() return SAFE_ADDREF((MgProxyFeatureReader*)featReader); } INT32 MgProxyFeatureService::UpdateMatchingFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgPropertyCollection* propertyValues, CREFSTRING filter) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt32, // Return type expected MgFeatureServiceOpId::UpdateMatchingFeatures,// Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, propertyValues, // Argument#3 MgCommand::knString, &filter, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i32; } INT32 MgProxyFeatureService::UpdateMatchingFeatures(MgResourceIdentifier* resource, CREFSTRING className, MgPropertyCollection* propertyValues, CREFSTRING filter, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt32, // Return type expected MgFeatureServiceOpId::UpdateMatchingFeatures,// Command Code 5, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knObject, propertyValues, // Argument#3 MgCommand::knString, &filter, // Argument#4 MgCommand::knString, &transactionId, // Argument#5 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i32; } INT32 MgProxyFeatureService::DeleteFeatures(MgResourceIdentifier* resource, CREFSTRING className, CREFSTRING filter) { MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt32, // Return type expected MgFeatureServiceOpId::DeleteFeatures, // Command Code 3, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knString, &filter, // Argument#3 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i32; } INT32 MgProxyFeatureService::DeleteFeatures(MgResourceIdentifier* resource, CREFSTRING className, CREFSTRING filter, MgTransaction* transaction) { STRING transactionId = L""; MgProxyFeatureTransaction* proxyTransaction = dynamic_cast<MgProxyFeatureTransaction*>(transaction); if (NULL != proxyTransaction) { transactionId = proxyTransaction->GetTransactionId(); } MgCommand cmd; cmd.ExecuteCommand(m_connProp, // Connection MgCommand::knInt32, // Return type expected MgFeatureServiceOpId::DeleteFeatures, // Command Code 4, // No of arguments Feature_Service, // Service Id BUILD_VERSION(3,0,0), // Operation version MgCommand::knObject, resource, // Argument#1 MgCommand::knString, &className, // Argument#2 MgCommand::knString, &filter, // Argument#3 MgCommand::knString, &transactionId, // Argument#4 MgCommand::knNone); // End of argument SetWarning(cmd.GetWarningObject()); return cmd.GetReturnValue().val.m_i32; }
47.998598
136
0.511259
achilex
1cb99fd40fc6812f6632aa8a1ff51529c4cc4960
254
hpp
C++
PythonModule/icp_matcher/icp_matcher.hpp
JooseRajamaeki/ICP
a4fb25efd6f2c128cc643f62b9dd90758872b842
[ "MIT" ]
4
2017-11-20T06:05:08.000Z
2018-11-28T10:21:39.000Z
PythonModule/icp_matcher/icp_matcher.hpp
JooseRajamaeki/ICP
a4fb25efd6f2c128cc643f62b9dd90758872b842
[ "MIT" ]
null
null
null
PythonModule/icp_matcher/icp_matcher.hpp
JooseRajamaeki/ICP
a4fb25efd6f2c128cc643f62b9dd90758872b842
[ "MIT" ]
1
2019-10-30T12:49:36.000Z
2019-10-30T12:49:36.000Z
#ifndef ICP_MATCHER_HPP #define ICP_MATCHER_HPP #include "Eigen\Dense" #include <algorithm> #include <vector> std::vector<int> alternating_icp_matching(std::vector<std::vector<float>> predictions, std::vector<std::vector<float>> true_outputs); #endif
25.4
133
0.779528
JooseRajamaeki
1cbb247d98e296b1933ce7cc4988b8bd682a6119
743
hpp
C++
SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DmgType_Trike_Reflected_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass DmgType_Trike_Reflected.DmgType_Trike_Reflected_C // 0x0000 (0x0131 - 0x0131) class UDmgType_Trike_Reflected_C : public UDmgType_Instant_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass DmgType_Trike_Reflected.DmgType_Trike_Reflected_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
20.081081
116
0.621803
2bite
1cbd40bcb66fa97295d9aa8d00ca9c9fbcd3c811
1,163
hpp
C++
higan/sfc/controller/controller.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/sfc/controller/controller.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/sfc/controller/controller.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
// SNES controller port pinout: // ------------------------------- // | (1) (2) (3) (4) | (5) (6) (7) ) // ------------------------------- // pin name port1 port2 // 1: +5v // 2: clock $4016 read $4017 read // 3: latch $4016.d0 write $4016.d0 write // 4: data1 $4016.d0 read $4017.d0 read // 5: data2 $4016.d1 read $4017.d1 read // 6: iobit $4201.d6 write; $4213.d6 read $4201.d7 write; $4213.d7 read // 7: gnd struct Controller : Thread { enum : bool { Port1 = 0, Port2 = 1 }; Controller(bool port); static auto Enter() -> void; virtual auto enter() -> void; auto step(unsigned clocks) -> void; auto synchronizeCPU() -> void; auto iobit() -> bool; auto iobit(bool data) -> void; virtual auto data() -> uint2 { return 0; } virtual auto latch(bool data) -> void {} const bool port; }; #include "gamepad/gamepad.hpp" #include "multitap/multitap.hpp" #include "mouse/mouse.hpp" #include "superscope/superscope.hpp" #include "justifier/justifier.hpp" #include "usart/usart.hpp"
29.820513
81
0.517627
ameer-bauer
1cc82d801b9f1424e65d621a3e0e8fc020dc0117
882
cpp
C++
C++/problem1464.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem1464.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem1464.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
// class Solution { // public: // static bool cmp(int a, int b) // { // return a > b; // } // int maxProduct(vector<int>& nums) { // sort(nums.begin(), nums.end(), cmp); // return (nums[0] - 1) * (nums[1] - 1); // } // }; class Solution { public: int maxProduct(vector<int>& nums) { int max = nums[0], submax = 1; // vector<int>::iterator test = nums.begin() + 2; for (vector<int>::iterator it = ++nums.begin(); it < nums.end(); ++it) //有些迭代器不能做加法的原因是不支持,底层数据结构不支持那样的操作(这些数据结构不是实现在内存中不是连续的,所以不是RA[随机访问]的),可能并不是类型尺寸的问题; { if (*it > max) { submax = max; max = *it; } else if (*it <= max && *it > submax) { submax = *it; } } return (max - 1) * (submax - 1); } };
25.941176
162
0.441043
1050669722
1cc857d7109c3a2fb6533f74f35509711c370f64
1,598
cc
C++
VisionSLAM14/ch3/UsingGeometry/using_geometry.cc
DLonng/Go
a67ac6d6501f9fadadec6a6cf766d4b4a356d572
[ "MIT" ]
23
2020-04-10T01:53:46.000Z
2021-12-31T03:43:10.000Z
VisionSLAM14/ch3/UsingGeometry/using_geometry.cc
DLonng/Go
a67ac6d6501f9fadadec6a6cf766d4b4a356d572
[ "MIT" ]
1
2020-12-10T07:08:37.000Z
2021-04-14T07:47:01.000Z
VisionSLAM14/ch3/UsingGeometry/using_geometry.cc
DLonng/Go
a67ac6d6501f9fadadec6a6cf766d4b4a356d572
[ "MIT" ]
9
2020-04-05T11:49:22.000Z
2021-11-04T10:23:37.000Z
#include <iostream> #include <cmath> #include <Eigen/Core> #include <Eigen/Geometry> int main() { Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity(); Eigen::AngleAxisd rotation_vector(M_PI / 4, Eigen::Vector3d(0, 0, 1)); std::cout << "rotation_matrix = \n" << rotation_vector.matrix() << std::endl << std::endl; rotation_matrix = rotation_vector.toRotationMatrix(); Eigen::Vector3d v(1, 0, 0); Eigen::Vector3d v_rotated = rotation_vector * v; std::cout << "(1, 0, 0) after rotation = " << v_rotated.transpose() << std::endl << std::endl; v_rotated = rotation_matrix * v; std::cout << "(1, 0, 0) after rotation = " << v_rotated.transpose() << std::endl << std::endl; Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0); std::cout << "yaw pitch roll = " << euler_angles.transpose() << std::endl << std::endl; Eigen::Isometry3d t = Eigen::Isometry3d::Identity(); t.rotate(rotation_vector); t.pretranslate(Eigen::Vector3d(1, 3, 4)); std::cout << "Transform matrix = \n" << t.matrix() << std::endl << std::endl; Eigen::Vector3d v_transformed = t * v; std::cout << "v transformed = " << v_transformed.transpose() << std::endl << std::endl; Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector); std::cout << "quaternion = \n" << q.coeffs() << std::endl << std::endl; q = Eigen::Quaterniond(rotation_matrix); std::cout << "quaternion = \n" << q.coeffs() << std::endl << std::endl; v_rotated = q * v; std::cout << "(1, 0, 0) after rotation = " << v_rotated.transpose() << std::endl << std::endl; return 0; }
32.612245
96
0.638298
DLonng
1cc928e75a74953ba64f61bca33b3fc73614c19f
162
cpp
C++
src/classwork/01_assign/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean
9e2f45a1d9682f5c9391a594e1284c6beffd9f58
[ "MIT" ]
null
null
null
src/classwork/01_assign/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean
9e2f45a1d9682f5c9391a594e1284c6beffd9f58
[ "MIT" ]
null
null
null
src/classwork/01_assign/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean
9e2f45a1d9682f5c9391a594e1284c6beffd9f58
[ "MIT" ]
null
null
null
#include"output.h"//use file code that I created #include<iostream>// use standard library using std::cout; int main() { cout<<"Hello World!"; return 0; }
12.461538
48
0.679012
acc-cosc-1337-spring-2020
1cc9ecac8d616fb6f3838d8d373d5c39896fb602
1,277
cpp
C++
examples/ftqc_qrt/repeat-until-success.cpp
ausbin/qcor
e9e0624a0e14b1b980ce9265b71c9b394abc60a8
[ "BSD-3-Clause" ]
59
2019-08-22T18:40:38.000Z
2022-03-09T04:12:42.000Z
examples/ftqc_qrt/repeat-until-success.cpp
ausbin/qcor
e9e0624a0e14b1b980ce9265b71c9b394abc60a8
[ "BSD-3-Clause" ]
137
2019-09-13T15:50:18.000Z
2021-12-06T14:19:46.000Z
examples/ftqc_qrt/repeat-until-success.cpp
ausbin/qcor
e9e0624a0e14b1b980ce9265b71c9b394abc60a8
[ "BSD-3-Clause" ]
26
2019-07-08T17:30:35.000Z
2021-12-03T16:24:12.000Z
#include <qalloc> // Compile with: qcor -qpu qpp -qrt ftqc repeat-until-success.cpp // Execute: ./a.out // We should get the print out conditioned by the measurement. // If not using the "ftqc" QRT, this will cause errors since the Measure results // are not available yet. // Using Repeat-Until-Success pattern to prepare a quantum state. // https://docs.microsoft.com/en-us/quantum/user-guide/using-qsharp/control-flow#rus-to-prepare-a-quantum-state __qpu__ void PrepareStateUsingRUS(qreg q, int maxIter) { using qcor::xasm; // Note: target = q[0], aux = q[1] H(q[1]); // We limit the max number of RUS iterations. for (int i = 0; i < maxIter; ++i) { std::cout << "Iter: " << i << "\n"; Tdg(q[1]); CNOT(q[0], q[1]); T(q[1]); // In order to measure in the PauliX basis, changes the basis. H(q[1]); if (!Measure(q[1])) { // Success (until (outcome == Zero)) std::cout << "Success after " << i + 1 << " iterations.\n"; break; } else { // Measure 1: |1> state // Fix up: Bring the auxiliary and target qubits back to |+> state. X(q[1]); H(q[1]); X(q[0]); H(q[0]); } } } int main() { // qcor::set_verbose(true); auto q = qalloc(2); PrepareStateUsingRUS(q, 100); }
29.022727
111
0.595928
ausbin
1ccac54f5a92974a050a80140b1d77874ae85e8d
7,700
cpp
C++
Classes/C2DXShareSDK/Android/ShareSDKUtils.cpp
rhzx3519/C2DXShareSDKSample
98630665c8d6b8ad0625e4c12bf6a542985aca07
[ "MIT" ]
null
null
null
Classes/C2DXShareSDK/Android/ShareSDKUtils.cpp
rhzx3519/C2DXShareSDKSample
98630665c8d6b8ad0625e4c12bf6a542985aca07
[ "MIT" ]
null
null
null
Classes/C2DXShareSDK/Android/ShareSDKUtils.cpp
rhzx3519/C2DXShareSDKSample
98630665c8d6b8ad0625e4c12bf6a542985aca07
[ "MIT" ]
null
null
null
#include "ShareSDKUtils.h" #if 1 #define LOG_TAG "ShareSDKUtils" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) #endif #ifdef __cplusplus extern "C" { #endif C2DXAuthResultEvent authCb; C2DXGetUserInfoResultEvent infoCb; C2DXShareResultEvent shareCb; JNIEXPORT void JNICALL Java_cn_sharesdk_ShareSDKUtils_onJavaCallback (JNIEnv * env, jclass thiz, jstring resp) { CCJSONConverter* json = CCJSONConverter::sharedConverter(); const char* ccResp = env->GetStringUTFChars(resp, JNI_FALSE); CCLog("ccResp = %s", ccResp); CCDictionary* dic = json->dictionaryFrom(ccResp); env->ReleaseStringUTFChars(resp, ccResp); CCNumber* status = (CCNumber*) dic->objectForKey("status"); // Success = 1, Fail = 2, Cancel = 3 CCNumber* action = (CCNumber*) dic->objectForKey("action"); // 1 = ACTION_AUTHORIZING, 8 = ACTION_USER_INFOR,9 = ACTION_SHARE CCNumber* platform = (CCNumber*) dic->objectForKey("platform"); CCDictionary* res = (CCDictionary*) dic->objectForKey("res"); // TODO add codes here if(1 == status->getIntValue()){ callBackComplete(action->getIntValue(), platform->getIntValue(), res); }else if(2 == status->getIntValue()){ callBackError(action->getIntValue(), platform->getIntValue(), res); }else{ callBackCancel(action->getIntValue(), platform->getIntValue(), res); } dic->release(); } void callBackComplete(int action, int platformId, CCDictionary* res){ if (action == 1 && NULL != authCb) { // 1 = ACTION_AUTHORIZING authCb(C2DXResponseStateSuccess, (C2DXPlatType) platformId, NULL); } else if (action == 8 && NULL != infoCb) { // 8 = ACTION_USER_INFOR infoCb(C2DXResponseStateSuccess, (C2DXPlatType) platformId, res, NULL); } else if (action == 9 && NULL != shareCb) { // 9 = ACTION_SHARE shareCb(C2DXResponseStateSuccess, (C2DXPlatType) platformId, res, NULL); } } void callBackError(int action, int platformId, CCDictionary* res){ if (action == 1 && NULL != authCb) { // 1 = ACTION_AUTHORIZING authCb(C2DXResponseStateFail, (C2DXPlatType) platformId, NULL); } else if (action == 8 && NULL != infoCb) { // 8 = ACTION_USER_INFOR infoCb(C2DXResponseStateFail, (C2DXPlatType) platformId, res, NULL); } else if (action == 9 && NULL != shareCb) { // 9 = ACTION_SHARE shareCb(C2DXResponseStateFail, (C2DXPlatType) platformId, res, NULL); } } void callBackCancel(int action, int platformId, CCDictionary* res){ if (action == 1 && NULL != authCb) { // 1 = ACTION_AUTHORIZING authCb(C2DXResponseStateCancel, (C2DXPlatType) platformId, NULL); } else if (action == 8 && NULL != infoCb) { // 8 = ACTION_USER_INFOR infoCb(C2DXResponseStateCancel, (C2DXPlatType) platformId, res, NULL); } else if (action == 9 && NULL != shareCb) { // 9 = ACTION_SHARE shareCb(C2DXResponseStateCancel, (C2DXPlatType) platformId, res, NULL); } } bool initShareSDK(const char* appKey, bool useAppTrusteeship) { JniMethodInfo mi; bool isHave = getMethod(mi, "initSDK", "(Ljava/lang/String;Z)V"); if (!isHave) { return false; } jstring appKeyStr = mi.env->NewStringUTF(appKey); mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, appKeyStr, useAppTrusteeship); releaseMethod(mi); return true; } bool getMethod(JniMethodInfo &mi, const char *methodName, const char *paramCode) { return JniHelper::getStaticMethodInfo(mi, "cn/sharesdk/ShareSDKUtils", methodName, paramCode); } void releaseMethod(JniMethodInfo &mi) { mi.env->DeleteLocalRef(mi.classID); } bool stopSDK() { JniMethodInfo mi; bool isHave = getMethod(mi, "stopSDK", "()V"); if (!isHave) { return false; } mi.env->CallStaticVoidMethod(mi.classID, mi.methodID); releaseMethod(mi); return true; } bool setPlatformDevInfo(int platformId, CCDictionary *info) { JniMethodInfo mi; bool isHave = getMethod(mi, "setPlatformConfig", "(ILjava/lang/String;)V"); if (!isHave) { return false; } CCJSONConverter* json = CCJSONConverter::sharedConverter(); const char* ccInfo = json->strFrom(info); jstring jInfo = mi.env->NewStringUTF(ccInfo); // free(ccInfo); mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId, jInfo); releaseMethod(mi); return true; } bool doAuthorize(int platformId, C2DXAuthResultEvent callback) { JniMethodInfo mi; bool isHave = getMethod(mi, "authorize", "(I)V"); if (!isHave) { return false; } mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId); releaseMethod(mi); authCb = callback; return true; } bool removeAccount(int platformId) { JniMethodInfo mi; bool isHave = getMethod(mi, "removeAccount", "(I)V"); if (!isHave) { return false; } mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId); releaseMethod(mi); return true; } bool isValid(int platformId) { JniMethodInfo mi; bool isHave = getMethod(mi, "isValid", "(I)Z"); if (!isHave) { return false; } jboolean valid = mi.env->CallStaticBooleanMethod(mi.classID, mi.methodID, platformId); releaseMethod(mi); return valid == JNI_TRUE; } CCDictionary* getAuthInfo(int platformId){ JniMethodInfo mi; CCDictionary* dic; bool isHave = getMethod(mi, "getAuthInfo", "(I)Ljava/lang/String;"); CCJSONConverter* json = CCJSONConverter::sharedConverter(); jstring userInfo = (jstring) mi.env->CallStaticObjectMethod(mi.classID, mi.methodID, platformId); const char* ccResp = mi.env->GetStringUTFChars(userInfo, JNI_FALSE); CCLog("userInfo = %s", ccResp); dic = json->dictionaryFrom(ccResp); releaseMethod(mi); return dic; } bool showUser(int platformId, C2DXGetUserInfoResultEvent callback){ JniMethodInfo mi; bool isHave = getMethod(mi, "showUser", "(I)V"); if (!isHave) { return false; } mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId); releaseMethod(mi); infoCb = callback; return true; } bool doShare(int platformId, CCDictionary *content, C2DXShareResultEvent callback){ JniMethodInfo mi; bool isHave = getMethod(mi, "share", "(ILjava/lang/String;)V"); if (!isHave) { return false; } CCJSONConverter* json = CCJSONConverter::sharedConverter(); const char* ccContent = json->strFrom(content); jstring jContent = mi.env->NewStringUTF(ccContent); // free(ccContent); mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId, jContent); releaseMethod(mi); shareCb = callback; return true; } bool multiShare(CCArray *platTypes, CCDictionary *content, C2DXShareResultEvent callback) { int index = 0; int count = platTypes->count(); while(index < count) { CCInteger* item = (CCInteger*) platTypes->objectAtIndex(index); int platformId = item->getValue(); doShare(platformId, content, callback); index++; } return true; } bool onekeyShare(int platformId, CCDictionary *content, C2DXShareResultEvent callback) { JniMethodInfo mi; if (platformId > 0) { bool isHave = getMethod(mi, "onekeyShare", "(ILjava/lang/String;)V"); if (!isHave) { return false; } } else { bool isHave = getMethod(mi, "onekeyShare", "(Ljava/lang/String;)V"); if (!isHave) { return false; } } CCJSONConverter* json = CCJSONConverter::sharedConverter(); const char* ccContent = json->strFrom(content); jstring jContent = mi.env->NewStringUTF(ccContent); // free(ccContent); if (platformId > 0) { mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, platformId, jContent); } else { mi.env->CallStaticVoidMethod(mi.classID, mi.methodID, jContent); } releaseMethod(mi); shareCb = callback; return true; } #ifdef __cplusplus } #endif
31.174089
129
0.697403
rhzx3519
1ccd7bf9ca6d81ebe9e0d75b43440091ed17433c
13,814
cxx
C++
main/sfx2/source/doc/iframe.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sfx2/source/doc/iframe.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sfx2/source/doc/iframe.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include "iframe.hxx" #include <sfx2/sfxdlg.hxx> #include <sfx2/sfxsids.hrc> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XFramesSupplier.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <tools/urlobj.hxx> #include <tools/debug.hxx> #include <rtl/ustring.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <svtools/miscopt.hxx> #include <vcl/window.hxx> using namespace ::com::sun::star; namespace sfx2 { class IFrameWindow_Impl : public Window { uno::Reference < frame::XFrame > mxFrame; sal_Bool bActive; sal_Bool bBorder; public: IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits = 0 ); public: void SetBorder( sal_Bool bNewBorder = sal_True ); sal_Bool HasBorder() const { return bBorder; } }; IFrameWindow_Impl::IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits ) : Window( pParent, nWinBits | WB_CLIPCHILDREN | WB_NODIALOGCONTROL | WB_DOCKBORDER ) , bActive(sal_False) , bBorder(bHasBorder) { if ( !bHasBorder ) SetBorderStyle( WINDOW_BORDER_NOBORDER ); else SetBorderStyle( WINDOW_BORDER_NORMAL ); //SetActivateMode( ACTIVATE_MODE_GRABFOCUS ); } void IFrameWindow_Impl::SetBorder( sal_Bool bNewBorder ) { if ( bBorder != bNewBorder ) { Size aSize = GetSizePixel(); bBorder = bNewBorder; if ( bBorder ) SetBorderStyle( WINDOW_BORDER_NORMAL ); else SetBorderStyle( WINDOW_BORDER_NOBORDER ); if ( GetSizePixel() != aSize ) SetSizePixel( aSize ); } } #define PROPERTY_UNBOUND 0 #define WID_FRAME_URL 1 #define WID_FRAME_NAME 2 #define WID_FRAME_IS_AUTO_SCROLL 3 #define WID_FRAME_IS_SCROLLING_MODE 4 #define WID_FRAME_IS_BORDER 5 #define WID_FRAME_IS_AUTO_BORDER 6 #define WID_FRAME_MARGIN_WIDTH 7 #define WID_FRAME_MARGIN_HEIGHT 8 const SfxItemPropertyMapEntry* lcl_GetIFramePropertyMap_Impl() { static SfxItemPropertyMapEntry aIFramePropertyMap_Impl[] = { { MAP_CHAR_LEN("FrameIsAutoBorder"), WID_FRAME_IS_AUTO_BORDER, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameIsAutoScroll"), WID_FRAME_IS_AUTO_SCROLL, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameIsBorder"), WID_FRAME_IS_BORDER, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameIsScrollingMode"), WID_FRAME_IS_SCROLLING_MODE, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameMarginHeight"), WID_FRAME_MARGIN_HEIGHT, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameMarginWidth"), WID_FRAME_MARGIN_WIDTH, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameName"), WID_FRAME_NAME, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 }, { MAP_CHAR_LEN("FrameURL"), WID_FRAME_URL, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 }, {0,0,0,0,0,0} }; return aIFramePropertyMap_Impl; } SFX_IMPL_XSERVICEINFO( IFrameObject, "com.sun.star.embed.SpecialEmbeddedObject", "com.sun.star.comp.sfx2.IFrameObject" ) SFX_IMPL_SINGLEFACTORY( IFrameObject ); IFrameObject::IFrameObject( const uno::Reference < lang::XMultiServiceFactory >& rFact ) : mxFact( rFact ) , maPropMap( lcl_GetIFramePropertyMap_Impl() ) { } IFrameObject::~IFrameObject() { } void SAL_CALL IFrameObject::initialize( const uno::Sequence< uno::Any >& aArguments ) throw ( uno::Exception, uno::RuntimeException ) { if ( aArguments.getLength() ) aArguments[0] >>= mxObj; } sal_Bool SAL_CALL IFrameObject::load( const uno::Sequence < com::sun::star::beans::PropertyValue >& /*lDescriptor*/, const uno::Reference < frame::XFrame >& xFrame ) throw( uno::RuntimeException ) { if ( SvtMiscOptions().IsPluginsEnabled() ) { DBG_ASSERT( !mxFrame.is(), "Frame already existing!" ); Window* pParent = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() ); IFrameWindow_Impl* pWin = new IFrameWindow_Impl( pParent, maFrmDescr.IsFrameBorderOn() ); pWin->SetSizePixel( pParent->GetOutputSizePixel() ); pWin->SetBackground(); pWin->Show(); uno::Reference < awt::XWindow > xWindow( pWin->GetComponentInterface(), uno::UNO_QUERY ); xFrame->setComponent( xWindow, uno::Reference < frame::XController >() ); // we must destroy the IFrame before the parent is destroyed xWindow->addEventListener( this ); mxFrame = uno::Reference< frame::XFrame >( mxFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Frame" ) ), uno::UNO_QUERY ); uno::Reference < awt::XWindow > xWin( pWin->GetComponentInterface(), uno::UNO_QUERY ); mxFrame->initialize( xWin ); mxFrame->setName( maFrmDescr.GetName() ); uno::Reference < frame::XFramesSupplier > xFramesSupplier( xFrame, uno::UNO_QUERY ); if ( xFramesSupplier.is() ) mxFrame->setCreator( xFramesSupplier ); uno::Reference< frame::XDispatchProvider > xProv( mxFrame, uno::UNO_QUERY ); util::URL aTargetURL; aTargetURL.Complete = ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) ); uno::Reference < util::XURLTransformer > xTrans( mxFact->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), uno::UNO_QUERY ); xTrans->parseStrict( aTargetURL ); uno::Sequence < beans::PropertyValue > aProps(2); aProps[0].Name = ::rtl::OUString::createFromAscii("PluginMode"); aProps[0].Value <<= (sal_Int16) 2; aProps[1].Name = ::rtl::OUString::createFromAscii("ReadOnly"); aProps[1].Value <<= (sal_Bool) sal_True; uno::Reference < frame::XDispatch > xDisp = xProv->queryDispatch( aTargetURL, ::rtl::OUString::createFromAscii("_self"), 0 ); if ( xDisp.is() ) xDisp->dispatch( aTargetURL, aProps ); return sal_True; } return sal_False; } void SAL_CALL IFrameObject::cancel() throw( com::sun::star::uno::RuntimeException ) { try { uno::Reference < util::XCloseable > xClose( mxFrame, uno::UNO_QUERY ); if ( xClose.is() ) xClose->close( sal_True ); mxFrame = 0; } catch ( uno::Exception& ) {} } void SAL_CALL IFrameObject::close( sal_Bool /*bDeliverOwnership*/ ) throw( com::sun::star::util::CloseVetoException, com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::addCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::removeCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::disposing( const com::sun::star::lang::EventObject& ) throw (com::sun::star::uno::RuntimeException) { cancel(); } uno::Reference< beans::XPropertySetInfo > SAL_CALL IFrameObject::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException ) { static uno::Reference< beans::XPropertySetInfo > xInfo = new SfxItemPropertySetInfo( &maPropMap ); return xInfo; } void SAL_CALL IFrameObject::setPropertyValue(const ::rtl::OUString& aPropertyName, const uno::Any& aAny) throw ( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException) { const SfxItemPropertySimpleEntry* pEntry = maPropMap.getByName( aPropertyName ); if( !pEntry ) throw beans::UnknownPropertyException(); switch( pEntry->nWID ) { case WID_FRAME_URL: { ::rtl::OUString aURL; aAny >>= aURL; maFrmDescr.SetURL( String(aURL) ); } break; case WID_FRAME_NAME: { ::rtl::OUString aName; if ( aAny >>= aName ) maFrmDescr.SetName( aName ); } break; case WID_FRAME_IS_AUTO_SCROLL: { sal_Bool bIsAutoScroll = sal_Bool(); if ( (aAny >>= bIsAutoScroll) && bIsAutoScroll ) maFrmDescr.SetScrollingMode( ScrollingAuto ); } break; case WID_FRAME_IS_SCROLLING_MODE: { sal_Bool bIsScroll = sal_Bool(); if ( aAny >>= bIsScroll ) maFrmDescr.SetScrollingMode( bIsScroll ? ScrollingYes : ScrollingNo ); } break; case WID_FRAME_IS_BORDER: { sal_Bool bIsBorder = sal_Bool(); if ( aAny >>= bIsBorder ) maFrmDescr.SetFrameBorder( bIsBorder ); } break; case WID_FRAME_IS_AUTO_BORDER: { sal_Bool bIsAutoBorder = sal_Bool(); if ( (aAny >>= bIsAutoBorder) ) { sal_Bool bBorder = maFrmDescr.IsFrameBorderOn(); maFrmDescr.ResetBorder(); if ( bIsAutoBorder ) maFrmDescr.SetFrameBorder( bBorder ); } } break; case WID_FRAME_MARGIN_WIDTH: { sal_Int32 nMargin = 0; Size aSize = maFrmDescr.GetMargin(); if ( aAny >>= nMargin ) { aSize.Width() = nMargin; maFrmDescr.SetMargin( aSize ); } } break; case WID_FRAME_MARGIN_HEIGHT: { sal_Int32 nMargin = 0; Size aSize = maFrmDescr.GetMargin(); if ( aAny >>= nMargin ) { aSize.Height() = nMargin; maFrmDescr.SetMargin( aSize ); } } break; default: ; } } uno::Any SAL_CALL IFrameObject::getPropertyValue(const ::rtl::OUString& aPropertyName) throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { const SfxItemPropertySimpleEntry* pEntry = maPropMap.getByName( aPropertyName ); if( !pEntry ) throw beans::UnknownPropertyException(); uno::Any aAny; switch( pEntry->nWID ) { case WID_FRAME_URL: { aAny <<= ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) ); } break; case WID_FRAME_NAME: { aAny <<= ::rtl::OUString( maFrmDescr.GetName() ); } break; case WID_FRAME_IS_AUTO_SCROLL: { sal_Bool bIsAutoScroll = ( maFrmDescr.GetScrollingMode() == ScrollingAuto ); aAny <<= bIsAutoScroll; } break; case WID_FRAME_IS_SCROLLING_MODE: { sal_Bool bIsScroll = ( maFrmDescr.GetScrollingMode() == ScrollingYes ); aAny <<= bIsScroll; } break; case WID_FRAME_IS_BORDER: { sal_Bool bIsBorder = maFrmDescr.IsFrameBorderOn(); aAny <<= bIsBorder; } break; case WID_FRAME_IS_AUTO_BORDER: { sal_Bool bIsAutoBorder = !maFrmDescr.IsFrameBorderSet(); aAny <<= bIsAutoBorder; } break; case WID_FRAME_MARGIN_WIDTH: { aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Width(); } break; case WID_FRAME_MARGIN_HEIGHT: { aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Height(); } default: ; } return aAny; } void SAL_CALL IFrameObject::addPropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::removePropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::addVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL IFrameObject::removeVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException ) { } ::sal_Int16 SAL_CALL IFrameObject::execute() throw (::com::sun::star::uno::RuntimeException) { SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); VclAbstractDialog* pDlg = pFact->CreateEditObjectDialog( NULL, rtl::OUString::createFromAscii(".uno:InsertObjectFloatingFrame"), mxObj ); if ( pDlg ) pDlg->Execute(); return 0; } void SAL_CALL IFrameObject::setTitle( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException) { } }
35.060914
224
0.655929
Grosskopf
1cce7151dbb70ffb24ff24d4371c453a2d454913
3,333
cpp
C++
src/core/Input.cpp
pixelsquare/atom-engine
763ed2446107f4baccb4a652effdd58303852ae4
[ "MIT" ]
null
null
null
src/core/Input.cpp
pixelsquare/atom-engine
763ed2446107f4baccb4a652effdd58303852ae4
[ "MIT" ]
null
null
null
src/core/Input.cpp
pixelsquare/atom-engine
763ed2446107f4baccb4a652effdd58303852ae4
[ "MIT" ]
null
null
null
/* * Copyright (C) 2012 PixelSquareLabs - All Rights Reserved * * Created: 06/05/2018 * Author: Anthony Ganzon * Email: pixelsquarelabs@yahoo.com * pixelsquarelabs@gmail.com */ #include "Input.h" #include "StdC.h" #include "PlatformGL.h" ATOM_BEGIN void (*mousePtr)(int x, int y); void (*mouseDownPtr)(int x, int y); void (*mousePassivePtr)(int x, int y); bool keyHold[256]; bool mouseButton[3]; bool Input::GetKey(unsigned char key) { return keyHold[key]; } bool Input::GetSpecialKey(SpecialKey type) { return specialKeyHold[static_cast<int>(type)]; } bool Input::GetKeyDown(unsigned char key) { return keyDown[key]; } /* Private Functions */ void atomOnKeyDown(unsigned char key, int x, int y) { keyHold[key] = true; specialKeyHold[key] = false; inputKey = key; if(!isPressed) { keyDown[key] = true; } if(key == 27) { std::exit(1); } } void atomOnKeyHold(unsigned char key, int x, int y) { keyHold[key] = false; specialKeyHold[key] = false; isPressed = false; specialPressed = false; } void atomOnSpecialKey(int key, int x, int y) { if(!specialPressed) { specialKeyHold[key] = true; } inputSpecialKey = key; } void atomOnMouseButton(int button, int state, int x, int y) { bool pressed = (state == GLUT_DOWN) ? true : false; switch(button) { case GLUT_LEFT_BUTTON: { //editMode.mouseClick[0] = pressed; mouseButton[0] = pressed; break; } case GLUT_MIDDLE_BUTTON: { //editMode.mouseClick[1] = pressed; mouseButton[1] = pressed; break; } case GLUT_RIGHT_BUTTON: { //editMode.mouseClick[2] = pressed; mouseButton[2] = pressed; break; } default: break; } if(pressed && mouseDownPtr != NULL) { mouseDownPtr(x, y); } //if(pressed) //{ // RayPick(x, y); //} //if(inEditMode) // { // editMode.lastX = x; // editMode.lastY = y; //} } void atomOnMouseMove(int x, int y) { if(mousePtr != NULL) { mousePtr(x, y); } //if(inEditMode) // { // int diffX = x - editMode.lastX; // int diffY = y - editMode.lastY; // editMode.lastX = x; // editMode.lastY = y; // if(editMode.mouseClick[0]) // { // editMode.rotation.x += (float) 0.5f * diffY; // editMode.rotation.y += (float) 0.5f * diffX; // } // if(editMode.mouseClick[1]) // { // editMode.position.z -= (float) 0.5f * diffX; // } // if(editMode.mouseClick[2]) // { // editMode.position.x += (float) 0.05f * diffX; // editMode.position.y -= (float) 0.05f * diffY; // } //} } void atomOnPassiveMouse(int x, int y) { if(mousePassivePtr != NULL) { mousePassivePtr(x, y); } } /* End of Private functions*/ void atomMouseFunc( void(*func)(int x, int y) ) { mousePtr = func; } void atomMouseDownFunc( void(*func)(int x, int y) ) { mouseDownPtr = func; } void atomPassiveMouseFunc( void(*func)(int x, int y) ) { mousePassivePtr = func; } bool GetMouseDown(MouseType type) { return mouseButton[static_cast<int>(type)]; } ATOM_END
18.414365
61
0.563756
pixelsquare
1cd134969c6b8998180c25147ea56a350991b341
2,758
cpp
C++
chromium/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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 "modules/serviceworkers/InstallEvent.h" #include "core/dom/ExceptionCode.h" #include "modules/serviceworkers/ServiceWorkerGlobalScopeClient.h" namespace blink { PassRefPtrWillBeRawPtr<InstallEvent> InstallEvent::create() { return adoptRefWillBeNoop(new InstallEvent()); } PassRefPtrWillBeRawPtr<InstallEvent> InstallEvent::create(const AtomicString& type, const ExtendableEventInit& eventInit) { return adoptRefWillBeNoop(new InstallEvent(type, eventInit)); } PassRefPtrWillBeRawPtr<InstallEvent> InstallEvent::create(const AtomicString& type, const ExtendableEventInit& eventInit, WaitUntilObserver* observer) { return adoptRefWillBeNoop(new InstallEvent(type, eventInit, observer)); } InstallEvent::~InstallEvent() { } void InstallEvent::registerForeignFetchScopes(ExecutionContext* executionContext, const Vector<String>& subScopes, ExceptionState& exceptionState) { if (!isBeingDispatched()) { exceptionState.throwDOMException(InvalidStateError, "The event handler is already finished."); return; } ServiceWorkerGlobalScopeClient* client = ServiceWorkerGlobalScopeClient::from(executionContext); String scopePath = static_cast<KURL>(client->scope()).path(); RefPtr<SecurityOrigin> origin = executionContext->securityOrigin(); Vector<KURL> subScopeURLs(subScopes.size()); for (size_t i = 0; i < subScopes.size(); ++i) { subScopeURLs[i] = executionContext->completeURL(subScopes[i]); if (!subScopeURLs[i].isValid()) { exceptionState.throwTypeError("Invalid URL: " + subScopes[i]); return; } subScopeURLs[i].removeFragmentIdentifier(); if (!origin->canRequest(subScopeURLs[i])) { exceptionState.throwTypeError("URL is not within scope: " + subScopes[i]); return; } String subScopePath = subScopeURLs[i].path(); if (!subScopePath.startsWith(scopePath)) { exceptionState.throwTypeError("URL is not within scope: " + subScopes[i]); return; } } client->registerForeignFetchScopes(subScopeURLs); } const AtomicString& InstallEvent::interfaceName() const { return EventNames::InstallEvent; } InstallEvent::InstallEvent() { } InstallEvent::InstallEvent(const AtomicString& type, const ExtendableEventInit& initializer) : ExtendableEvent(type, initializer) { } InstallEvent::InstallEvent(const AtomicString& type, const ExtendableEventInit& initializer, WaitUntilObserver* observer) : ExtendableEvent(type, initializer, observer) { } } // namespace blink
32.833333
150
0.728789
wedataintelligence
1cd240e2bc97c431a30e18912baccb00632fab33
6,452
cpp
C++
src/ui/WaterfallDialog.cpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
6
2020-07-11T11:16:18.000Z
2021-12-17T23:30:36.000Z
src/ui/WaterfallDialog.cpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
9
2020-07-03T21:23:50.000Z
2022-02-15T12:56:16.000Z
src/ui/WaterfallDialog.cpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
null
null
null
/* BSD 2-Clause License Copyright (c) 2020, Till Mayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #include "WaterfallDialog.hpp" #include <Drtd.hpp> #include <sstream> #include <ui/MainGui.hpp> #include <util/Singleton.hpp> #include <util/Util.hpp> using namespace Ui; const std::array s_bins { "1024", "2048", "4096", "8192", "16384", "32768", "65536" }; WaterfallDialog::WaterfallDialog() : Fl_Window(100, 100, 360, 204, "Waterfall settings") , m_window(85, 4, 0, 25, "Window:") , m_zoom(m_window.x(), m_window.y() + m_window.h() + 4, w() - m_window.x() - 24, 25, "Zoom:") , m_reset_zoom(m_zoom.x() + m_zoom.w() + 4, m_zoom.y(), 15, m_zoom.h(), "R") , m_bin_offset(m_window.x(), m_zoom.y() + m_zoom.h() + 4, 150, 25, "Offset (Hz):") , m_speed_multiplier(m_window.x(), m_bin_offset.y() + m_bin_offset.h() + 4, w() - m_window.x() - 4, 25, "Speed:") , m_bins(m_window.x(), m_speed_multiplier.y() + m_speed_multiplier.h() + 4, 150, 25, "Bins:") , m_palette(m_window.x(), m_bins.y() + m_bins.h() + 4, 0, 25, "Palette:") , m_power_spectrum(m_window.x(), m_palette.y() + m_palette.h() + 4, 180, 25, "Show power spectrum") { double max_width = 0; for (auto& window : Dsp::Window::s_windows) { m_window.add(window.name().c_str()); max_width = std::max(fl_width(window.name().c_str()), max_width); } m_window.size(static_cast<int>(max_width + 40), m_window.h()); m_window.align(FL_ALIGN_LEFT); m_window.callback(save_to_waterfall); m_zoom.type(FL_HOR_NICE_SLIDER); m_zoom.selection_color(Util::s_amber_color); m_zoom.align(FL_ALIGN_LEFT); m_zoom.bounds(s_min_zoom, s_max_zoom); m_zoom.callback(save_to_waterfall); m_reset_zoom.callback([](Fl_Widget*, void*) { s_waterfall_dialog->m_zoom.value(0); save_to_waterfall(nullptr, nullptr); }); m_bin_offset.align(FL_ALIGN_LEFT); m_bin_offset.callback(save_to_waterfall); m_speed_multiplier.type(FL_HOR_NICE_SLIDER); m_speed_multiplier.selection_color(Util::s_amber_color); m_speed_multiplier.align(FL_ALIGN_LEFT); m_speed_multiplier.callback(save_to_waterfall); m_speed_multiplier.bounds(0, 10); m_bins.align(FL_ALIGN_LEFT); for (auto bins : s_bins) m_bins.add(bins); m_bins.callback(save_to_waterfall); max_width = 0; for (auto& palette : Ui::Palette::palettes()) { m_palette.add(palette.name); max_width = std::max(fl_width(palette.name), max_width); } m_palette.size(static_cast<int>(max_width + 40), m_palette.h()); m_palette.callback(save_to_waterfall); m_power_spectrum.callback(save_to_waterfall); } void WaterfallDialog::show_dialog() { auto& main_gui = Drtd::main_gui(); s_waterfall_dialog->position( main_gui.x() + Util::center(main_gui.w(), s_waterfall_dialog->w()), main_gui.y() + Util::center(main_gui.h(), s_waterfall_dialog->h())); s_waterfall_dialog->load_from_waterfall(Drtd::main_gui().waterfall().settings()); s_waterfall_dialog->set_non_modal(); s_waterfall_dialog->show(); } void WaterfallDialog::save_to_waterfall(Fl_Widget*, void*) { Waterfall::Settings new_settings; auto& waterfall = Drtd::main_gui().waterfall(); new_settings.zoom = static_cast<float>(s_waterfall_dialog->m_zoom.value()); new_settings.speed_multiplier = static_cast<u8>(s_waterfall_dialog->m_speed_multiplier.value()); new_settings.bins = std::atoi(s_bins[static_cast<u32>(s_waterfall_dialog->m_bins.value())]); new_settings.power_spectrum = static_cast<bool>(s_waterfall_dialog->m_power_spectrum.value()); s_waterfall_dialog->update_offset_spinner_limits(new_settings); new_settings.bin_offset = static_cast<u32>(Waterfall::translate_hz_to_x(new_settings, static_cast<Hertz>(s_waterfall_dialog->m_bin_offset.value()), waterfall.sample_rate())); waterfall.set_window_index(static_cast<u8>(s_waterfall_dialog->m_window.value())); waterfall.set_palette_index(static_cast<u8>(s_waterfall_dialog->m_palette.value())); waterfall.update_settings_later(new_settings); } void WaterfallDialog::update_offset_spinner_limits(const Waterfall::Settings& settings) { auto& waterfall = Drtd::main_gui().waterfall(); m_bin_offset.step(Waterfall::hz_per_bin(settings, waterfall.sample_rate())); m_bin_offset.range(0, waterfall.sample_rate() / 2); } void WaterfallDialog::load_from_waterfall(const Waterfall::Settings& settings) { if (!s_waterfall_dialog.has_instance()) return; auto& waterfall = Drtd::main_gui().waterfall(); s_waterfall_dialog->m_window.value(waterfall.window_index()); s_waterfall_dialog->m_zoom.value(settings.zoom); s_waterfall_dialog->m_speed_multiplier.value(settings.speed_multiplier); s_waterfall_dialog->update_offset_spinner_limits(settings); s_waterfall_dialog->m_bin_offset.value(Waterfall::translate_x_to_hz(settings, settings.bin_offset, waterfall.sample_rate())); s_waterfall_dialog->m_bins.value(s_waterfall_dialog->m_bins.find_item(std::to_string(settings.bins).c_str())); s_waterfall_dialog->m_palette.value(waterfall.palette_index()); s_waterfall_dialog->m_power_spectrum.value(settings.power_spectrum); }
44.496552
178
0.734656
tlmrgvf
1cd3cb26a4adf887f1c2097296d3436f242fe359
2,320
cpp
C++
HRtoSQLite_tests/g.tests/src/Integral_Test.cpp
victorkryz/HRtoSQLite
4eda35cacf5fde897646baf2acb795b8aefef3da
[ "MIT" ]
null
null
null
HRtoSQLite_tests/g.tests/src/Integral_Test.cpp
victorkryz/HRtoSQLite
4eda35cacf5fde897646baf2acb795b8aefef3da
[ "MIT" ]
null
null
null
HRtoSQLite_tests/g.tests/src/Integral_Test.cpp
victorkryz/HRtoSQLite
4eda35cacf5fde897646baf2acb795b8aefef3da
[ "MIT" ]
null
null
null
/** * HRtoSQLite_tests * * @author Victor Kryzhanivskyi */ #include "Ora/Connection.h" #include "Ora/Utils.h" #include "Ora/Selector.h" #include "Ora/Reader.h" #include "TestCommon.h" #include "Sqlt/DbsWriter.h" #include "Ora/ConnectionHelper.h" class IntegralTest : public ::testing::Test, ConnectionHelper { using CH = ConnectionHelper; class RowsCounter : public IdleCallback { public: RowsCounter(int& counter) : counter_(counter) { } virtual void onIdle() { counter_++; } private: int& counter_; }; public: IntegralTest() { } virtual ~IntegralTest() { } protected: void exportTable(const std::string strTableName) { bool bSucceeded(true); int iteratedRowsCounter(0); try { //& Do a whole table export procedure //& with calculating of inserted rows: TableExporter tbe(spConn_(), strDbFile_, std::make_shared<RowsCounter>(iteratedRowsCounter)); tbe.proceed(strTableName); //& Get rows number from the target SQLite table: Sqlt::Session session(strDbFile_); const int realRowCounter = session.getRowCount(strTableName); //& Check expectations: EXPECT_TRUE(iteratedRowsCounter==realRowCounter); std::cout << std::endl << "Table \"" << strTableName << "\" exported" << " (" << iteratedRowsCounter << " rows)." << std::endl; } catch (const std::exception& e) { bSucceeded = false; std::cerr << "Table " << strTableName << ", exception occured: " << e.what() << std::endl; } ASSERT_TRUE(bSucceeded); } protected: void SetUp() override { CH::SetUp(); Sqlt::StructWriter sqltWriter(strStructFile_, strDbFile_); sqltWriter.initStructure(true); } void TearDown() override { CH::TearDown(); } Ora::ConnectionSp& spConn_() { return CH::spConn_; }; protected: std::string strDbFile_ = glTestParams.strOutputSqltDbFile_; std::string strStructFile_ = glTestParams.strSqltDDLFile_; }; TEST_F(IntegralTest, Export_ALL) { exportTable("REGIONS"); exportTable("COUNTRIES"); exportTable("LOCATIONS"); exportTable("DEPARTMENTS"); exportTable("EMPLOYEES"); exportTable("JOBS"); exportTable("JOB_HISTORY"); }
22.095238
132
0.63319
victorkryz
1cd433e8fb746b8fff90e2cf62bb81df29035495
3,222
cpp
C++
libs/libsmlibraries/src/collection.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
libs/libsmlibraries/src/collection.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
libs/libsmlibraries/src/collection.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
/* Copyright 2020 Simon Meaden 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 "qyamlcpp/collection.h" //template<class T> //YAML::Node YAML::convert<QList<T>>::encode(const QList<T>& rhs) //{ // Node node(NodeType::Sequence); // std::list<T> slist = rhs.toStdList(); // node = slist; // return node; //} //template<class T> //bool YAML::convert<QList<T>>::decode(const YAML::Node& node, QList<T>& rhs) //{ // if (!node.IsSequence()) { // return false; // } // std::list<T> slist = node.as<std::list<T>>(); // rhs = QList<T>::fromStdList(slist); // return true; //} //template<class K, class V> //YAML::Node YAML::convert<QMap<K, V>>::encode(const QMap<K, V>& rhs) //{ // Node node(NodeType::Map); // std::map<K, V> smap = rhs.toStdMap(); // node = smap; // return node; //} //template<class K, class V> //bool YAML::convert<QMap<K, V>>::decode(const YAML::Node& node, QMap<K, V>& rhs) //{ // if (!node.IsMap()) { // return false; // } // std::map<K, V> smap = node.as<std::map<K, V>>(); // rhs = QMap<K, V>(smap); // return true; //} //template<class T> //YAML::Node YAML::convert<QVector<T>>::encode(const QVector<T>& rhs) //{ // Node node(NodeType::Sequence); // std::vector<T> svector = rhs.toStdVector(); // node = svector; // return node; //} //template<class T> //bool YAML::convert<QVector<T>>::decode(const YAML::Node& node, QVector<T>& rhs) //{ // if (!node.IsSequence()) { // return false; // } // std::vector<T> svector = node.as<std::vector<T>>(); // rhs = QVector<T>::fromStdVector(svector); // return true; //} //template<class T> //YAML::Node YAML::convert<QSet<T>>::encode(const QSet<T>& rhs) //{ // Node node(NodeType::Sequence); // std::list<T> slist = rhs.toList(); // node = slist; // return node; //} //template<class T> //bool YAML::convert<QSet<T>>::decode(const YAML::Node& node, QSet<T>& rhs) //{ // if (!node.IsSequence()) { // return false; // } // std::list<T> slist = node.as<std::list<T>>(); // rhs = QSet<T>::fromList(QList<T>::fromStdList(slist)); // return true; //}
27.538462
161
0.629423
simonmeaden
1cd43a448911fbd04fe83949b42db9d78d125efa
816
cpp
C++
LeetCodeSolutions/LeetCode_0340.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
24
2020-03-28T06:10:25.000Z
2021-11-23T05:01:29.000Z
LeetCodeSolutions/LeetCode_0340.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
null
null
null
LeetCodeSolutions/LeetCode_0340.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
8
2020-05-18T02:43:16.000Z
2021-05-24T18:11:38.000Z
class Solution { public: int lengthOfLongestSubstringKDistinct(string s, int k) { unordered_map<char, int> counter; int ret = 0; int tmp = 0; for(int i = 0; i < s.size(); ++i){ char &c = s[i]; ++counter[c]; ++tmp; if(counter.size() <= k){ ret = max(ret, tmp); } if(counter.size() == k + 1){ int st = i - tmp + 1; while(counter.size() > k){ char key = s[st]; --counter[key]; --tmp; if(counter[key] == 0){ counter.erase(counter.find(key)); } ++st; } } } return ret; } };
28.137931
60
0.344363
lih627
1cd7513293e95c643e2ada032f4d77d64a5b82e3
2,244
cpp
C++
src/pal/tests/palsuite/c_runtime/_mbsdec/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
159
2020-06-17T01:01:55.000Z
2022-03-28T10:33:37.000Z
src/pal/tests/palsuite/c_runtime/_mbsdec/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-06-27T01:16:35.000Z
2022-02-06T20:33:24.000Z
src/pal/tests/palsuite/c_runtime/_mbsdec/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-05-21T08:18:20.000Z
2021-06-29T01:13:13.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================ ** ** Source: test1.c ** ** Purpose: ** Ensure that this function moves the string pointer back one character. ** First do a basic test to check that the pointer gets moved back the one ** character, given str1 and str+1 as params. Then try with both ** params being the same pointer, which should return NULL. Also test ** when the first pointer is past the second pointer, which should ** return null. Finally try this function on an array of single bytes, ** which it assumes are characters and should work in the same fashion. ** ** **==========================================================================*/ #include <palsuite.h> /* * Note: it seems like these functions would only be useful if they * didn't assume a character was equivalent to a single byte. Be that * as it may, I haven't seen a way to get it to behave otherwise. */ int __cdecl main(int argc, char *argv[]) { unsigned char *str1 = (unsigned char*) "foo"; unsigned char str2[] = {0xC0, 0x80, 0xC0, 0x80, 0}; unsigned char str3[] = {0}; unsigned char *ret = NULL; /* * Initialize the PAL and return FAIL if this fails */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } ret = _mbsdec(str1,str1+1); if (ret != str1) { Fail ("ERROR: _mbsdec returned %p. Expected %p\n", ret, str1); } ret = _mbsdec(str1,str1); if (ret != NULL) { Fail ("ERROR: _mbsdec returned %p. Expected %p\n", ret, NULL); } ret = _mbsdec(str1+100,str1); if (ret != NULL) { Fail ("ERROR: _mbsdec returned %p. Expected %p\n", ret, NULL); } ret = _mbsdec(str2,str2+1); if (ret != str2) { Fail ("ERROR: _mbsdec returned %p. Expected %p\n", ret, str2+1); } ret = _mbsdec(str3,str3+10); if (ret != str3+9) { Fail ("ERROR: _mbsdec returned %p. Expected %p\n", ret, str3+9); } PAL_Terminate(); return PASS; }
28.769231
78
0.581105
elinor-fung
1cd76b72dd753f1e5cca7d97c06545594d848357
18,429
cpp
C++
core/evolution.cpp
Siddhant-K-code/darwin
86781c9dabeceda7f8666bb1bb4b5ca7d725d81d
[ "Apache-2.0" ]
94
2018-11-24T20:07:07.000Z
2022-03-13T01:34:45.000Z
core/evolution.cpp
JJ/darwin
d5519b6d542c179cbc0f6575dcfce25e68e2f1df
[ "Apache-2.0" ]
3
2020-11-21T04:49:43.000Z
2021-02-09T18:15:23.000Z
core/evolution.cpp
JJ/darwin
d5519b6d542c179cbc0f6575dcfce25e68e2f1df
[ "Apache-2.0" ]
18
2018-11-24T20:07:21.000Z
2021-12-19T10:48:57.000Z
// Copyright 2018 The Darwin Neuroevolution Framework Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "evolution.h" #include "logging.h" #include "scope_guard.h" #include <assert.h> #include <math.h> #include <time.h> #include <algorithm> #include <fstream> #include <limits> #include <memory> #include <sstream> #include <system_error> #include <thread> using namespace std; namespace darwin { ProgressMonitor* ProgressManager::progress_monitor_ = nullptr; GenerationSummary::GenerationSummary(const Population* population, shared_ptr<core::PropertySet> calibration_fitness) : calibration_fitness(calibration_fitness) { const size_t size = population->size(); CHECK(size > 0); const auto& ranking_index = population->rankingIndex(); generation = population->generation(); best_fitness = population->genotype(ranking_index[0])->fitness; median_fitness = population->genotype(ranking_index[size / 2])->fitness; worst_fitness = population->genotype(ranking_index[size - 1])->fitness; champion = population->genotype(ranking_index[0])->clone(); } EvolutionTrace::EvolutionTrace(shared_ptr<const Experiment> experiment, const EvolutionConfig& config) : experiment_(experiment) { CHECK(experiment_); config_.copyFrom(config); auto universe = experiment_->universe(); auto evolution_config = config_.toJson().dump(2); db_trace_ = universe->newTrace(experiment_->dbVariationId(), evolution_config); } int EvolutionTrace::size() const { unique_lock<mutex> guard(lock_); return int(generations_.size()); } GenerationSummary EvolutionTrace::generationSummary(int generation) const { unique_lock<mutex> guard(lock_); if (generation < 0 || generation >= int(generations_.size())) throw core::Exception("Generation %d is not available", generation); return generations_[generation]; } vector<CompressedFitnessValue> compressFitness(const Population* population) { // max allowed relative deviation from the actual value constexpr float kMaxDeviation = 0.01f; vector<CompressedFitnessValue> compressed_values; const auto& ranking_index = population->rankingIndex(); auto rankedGenotype = [&](size_t index) { return population->genotype(ranking_index[index]); }; const int raw_size = int(ranking_index.size()); CHECK(raw_size > 0); int last_sample_index = 0; float last_sample_value = rankedGenotype(last_sample_index)->fitness; compressed_values.emplace_back(last_sample_index, last_sample_value); for (int i = 2; i < raw_size; ++i) { const float value = rankedGenotype(i)->fitness; // can we extend the current compressed set with the new value? // (only if the straight line between it and the last sample is a valid // aproximation of all the intermediate values) const int prev_index = i - 1; const float prev_value = rankedGenotype(prev_index)->fitness; const float m = float(value - last_sample_value) / (i - last_sample_index); CHECK(m <= 0); const float aprox_value = (prev_index - last_sample_index) * m + last_sample_value; const float relative_dev = fabs((aprox_value - prev_value) / prev_value); if (relative_dev > kMaxDeviation) { CHECK(prev_index > last_sample_index); last_sample_index = prev_index; last_sample_value = prev_value; compressed_values.emplace_back(last_sample_index, last_sample_value); } } if (raw_size > 1) { // append the last real value last_sample_index = raw_size - 1; last_sample_value = rankedGenotype(last_sample_index)->fitness; compressed_values.emplace_back(last_sample_index, last_sample_value); } CHECK(!compressed_values.empty()); return compressed_values; } GenerationSummary EvolutionTrace::addGeneration( const Population* population, shared_ptr<core::PropertySet> calibration_fitness, const EvolutionStage& top_stage) { GenerationSummary summary(population, calibration_fitness); // record the generation summary { unique_lock<mutex> guard(lock_); CHECK(summary.generation == int(generations_.size())); generations_.push_back(summary); } // save the generation results DbGeneration db_generation; db_generation.trace_id = db_trace_->id; db_generation.generation = summary.generation; json json_summary; json json_details; json_summary["best_fitness"] = summary.best_fitness; json_summary["median_fitness"] = summary.median_fitness; json_summary["worst_fitness"] = summary.worst_fitness; if (summary.calibration_fitness) { json json_calibration; for (auto property : summary.calibration_fitness->properties()) json_calibration[property->name()] = property->nativeValue<float>(); json_summary["calibration_fitness"] = json_calibration; } // detailed fitness information switch (config_.fitness_information) { case FitnessInfoKind::SamplesOnly: // nothing to do, we always save the samples break; case FitnessInfoKind::FullCompressed: { // compressed fitness json json_compressed_fitness; for (const auto& compressed_value : compressFitness(population)) { json_compressed_fitness.push_back( { compressed_value.index, compressed_value.value }); } json_details["compressed_fitness"] = json_compressed_fitness; } break; case FitnessInfoKind::FullRaw: { // capture all fitness values (ranked) json json_full_fitness; for (auto genotype_index : population->rankingIndex()) { json_full_fitness.push_back(population->genotype(genotype_index)->fitness); } json_details["full_fitness"] = json_full_fitness; } break; default: FATAL("Unexpected fitness information kind"); } // capture genealogy information if (config_.save_genealogy) { json json_full_genealogy; for (size_t i = 0; i < population->size(); ++i) { const auto& genealogy = population->genotype(i)->genealogy; json json_genealogy_entry; if (!genealogy.genetic_operator.empty()) json_genealogy_entry[genealogy.genetic_operator] = genealogy.parents; json_full_genealogy.push_back(json_genealogy_entry); } json_details["genealogy"] = json_full_genealogy; } // champion genotype if (config_.save_champion_genotype) { json json_genotypes; json_genotypes["champion"] = summary.champion->save(); db_generation.genotypes = json_genotypes.dump(); } // generation runtime profile json json_profile; json_profile["elapsed"] = top_stage.elapsed(); switch (config_.profile_information) { case ProfileInfoKind::GenerationOnly: break; case ProfileInfoKind::AllStages: json_profile["stages"] = top_stage; break; default: FATAL("unexpected profile kind"); } db_generation.profile = json_profile.dump(); // summary CHECK(!json_summary.empty()); db_generation.summary = json_summary.dump(); // details if (!json_details.empty()) { db_generation.details = json_details.dump(); } // save the new generation to the universe database experiment_->universe()->newGeneration(db_generation); return summary; } void Evolution::init() { new std::thread(&Evolution::mainThread, evolution()); } bool Evolution::newExperiment(shared_ptr<Experiment> experiment, const EvolutionConfig& config) { core::log("New experiment (population size = %d)\n\n", experiment->setup()->population_size); CHECK(config.max_generations >= 0); { unique_lock<mutex> guard(lock_); if (state_ != State::Initializing) { core::log("Invalid state, can't start a new experiment\n\n"); return false; } // sanity checks (make sure we have a clean state) CHECK(stage_stack_.empty()); // setup the shared ANN library ann::g_config.copyFrom(*experiment->coreConfig()); try { // setup the domain auto domain_factory = experiment->domainFactory(); auto domain = domain_factory->create(*experiment->domainConfig()); // setup the population auto population_factory = experiment->populationFactory(); auto population = population_factory->create(*experiment->populationConfig(), *domain); domain_ = std::move(domain); population_ = std::move(population); } catch (const std::exception& e) { core::log("Failed to create the domain or the population: %s\n", e.what()); throw; } config_.copyFrom(config); CHECK(experiment_ == nullptr); experiment_ = experiment; experiment_->prepareForEvolution(); trace_ = make_shared<EvolutionTrace>(experiment_, config_); state_ = State::Paused; state_cv_.notify_all(); } events.publish(EventFlag::ProgressUpdate | EventFlag::StateChanged | EventFlag::NewExperiment); return true; } void Evolution::mainThread() { { unique_lock<mutex> guard(lock_); CHECK(main_thread_id_ == thread::id()); main_thread_id_ = std::this_thread::get_id(); } // the "evolution as a service" loop for (;;) { bool canceled = false; try { evolutionCycle(); core::log("\nEvolution complete.\n\n"); } catch (const pp::CanceledException&) { core::log("\nRestarting the evolution lifecycle...\n\n"); canceled = true; } // stop the evolution { unique_lock<mutex> guard(lock_); CHECK(!canceled || state_ == State::Canceling); state_ = State::Stopped; state_cv_.notify_all(); } uint32_t event_flags = EventFlag::StateChanged; if (!canceled) { event_flags |= EventFlag::EndEvolution; } events.publish(event_flags); } } void Evolution::evolutionCycle() { checkpoint(); CHECK(experiment_ != nullptr); CHECK(domain_); CHECK(population_); EvolutionStage last_top_stage; // TODO: this is an awkward way to capture the top stage, revisit auto stages_subscription = top_stages.subscribe([&](const EvolutionStage& stage) { last_top_stage = stage; }); SCOPE_EXIT { top_stages.unsubscribe(stages_subscription); }; core::log("\nEvolution started:\n\n"); // main evolution loop for (int generation = 0; generation < config_.max_generations; ++generation) { // explicit scope for the top generation stage { StageScope stage( "Evolve one generation", 0, EvolutionStage::Annotation::Generation); // create the generation's genotypes if (generation == 0) { population_->createPrimordialGeneration(experiment_->setup()->population_size); } else { population_->createNextGeneration(); } // TODO: remove generation tracking from darwin::Population? CHECK(population_->generation() == generation); // domain specific evaluation of the genotypes if (domain_->evaluatePopulation(population_.get())) break; } // validate the fitness values const auto& ranking_index = population_->rankingIndex(); for (size_t i = 0; i < ranking_index.size(); ++i) { const float fitness_value = population_->genotype(ranking_index[i])->fitness; CHECK(isfinite(fitness_value)); if (i > 0) { // values should be ranked in descending fitness order const float prev_value = population_->genotype(ranking_index[i - 1])->fitness; CHECK(fitness_value <= prev_value); } } // extra fitness values (optional) const auto champion_index = ranking_index[0]; const Genotype* champion = population_->genotype(champion_index); shared_ptr<core::PropertySet> calibration_fitness = domain_->calibrateGenotype(champion); // record the generation auto summary = trace_->addGeneration(population_.get(), calibration_fitness, last_top_stage); // publish the generation results generation_summary.publish(summary); events.publish(EventFlag::EndGeneration); checkpoint(); } } void Evolution::checkpoint() { unique_lock<mutex> guard(lock_); while (state_ != State::Running) { // handle pause requests (Pausing -> Paused) if (state_ == State::Pausing) { state_ = State::Paused; state_cv_.notify_all(); // annotate the current stage, if any if (!stage_stack_.empty()) stage_stack_.back().addAnnotations(EvolutionStage::Annotation::Paused); guard.unlock(); events.publish(EventFlag::StateChanged); guard.lock(); continue; } else if (state_ == State::Canceling) { // annotate the current stage, if any if (!stage_stack_.empty()) stage_stack_.back().addAnnotations(EvolutionStage::Annotation::Canceled); throw pp::CanceledException(); } state_cv_.wait(guard); } } void Evolution::beginStage(const string& name, size_t size, uint32_t annotations) { // must be called on the main thread CHECK(main_thread_id_ == std::this_thread::get_id()); { unique_lock<mutex> guard(lock_); stage_stack_.emplace_back(name, size, annotations); stage_stack_.back().start(); } events.publish(EventFlag::StateChanged); } void Evolution::finishStage(const string& name) { // must be called on the main thread CHECK(main_thread_id_ == std::this_thread::get_id()); EvolutionStage stage; bool top_stage = false; { unique_lock<mutex> guard(lock_); CHECK(!stage_stack_.empty()); stage = stage_stack_.back(); CHECK(stage.name() == name); stage.finish(); stage_stack_.pop_back(); if (!stage_stack_.empty()) stage_stack_.back().recordSubStage(stage); else top_stage = true; } if ((stage.annotations() & EvolutionStage::Annotation::Canceled) == 0) { core::log("Stage complete: %s, %.4f sec\n", stage.name(), stage.elapsed()); } if (top_stage) { top_stages.publish(stage); } events.publish(EventFlag::StateChanged); } void Evolution::reportProgress(size_t increment) { bool progress_notification = false; { unique_lock<mutex> guard(lock_); CHECK(!stage_stack_.empty()); auto& current_stage = stage_stack_.back(); int prev_progress_percent = current_stage.progressPercent(); current_stage.advanceProgress(increment); progress_notification = current_stage.progressPercent() != prev_progress_percent; } if (progress_notification) events.publish(EventFlag::ProgressUpdate); } Evolution::Snapshot Evolution::snapshot() const { unique_lock<mutex> guard(lock_); Snapshot s; s.experiment = experiment_; s.trace = trace_; s.generation = population_ ? population_->generation() : 0; s.stage = stage_stack_.empty() ? EvolutionStage() : stage_stack_.back(); s.state = state_; s.population = population_.get(); s.domain = domain_.get(); return s; } // TODO: consider callback for the pause completition? void Evolution::pause() { bool update = false; { unique_lock<mutex> guard(lock_); if (state_ == State::Running) { state_ = State::Pausing; state_cv_.notify_all(); update = true; } } if (update) events.publish(EventFlag::StateChanged); } void Evolution::run() { CHECK(experiment_ != nullptr); bool update = false; { unique_lock<mutex> guard(lock_); if (state_ == State::Paused) { state_ = State::Running; state_cv_.notify_all(); update = true; } else { CHECK(state_ == State::Running); } } if (update) events.publish(EventFlag::StateChanged); } // TODO: consider callback for the reset completition? bool Evolution::reset() { { unique_lock<mutex> guard(lock_); switch (state_) { case State::Initializing: // nothing to reset return true; case State::Paused: // requesting cancelation state_ = State::Canceling; state_cv_.notify_all(); break; case State::Stopped: // already stopped break; default: // the evolution must be paused/stopped before it can be reset return false; } // waiting for the cancelation confirmation while (state_ != State::Stopped) state_cv_.wait(guard); // reset the evolution state stage_stack_.clear(); experiment_.reset(); trace_.reset(); population_.reset(); domain_.reset(); state_ = State::Initializing; state_cv_.notify_all(); } core::log("\nThe evolution was reset.\n"); events.publish(EventFlag::StateChanged | EventFlag::Reset); return true; } void Evolution::waitForState(Evolution::State target_state) const { unique_lock<mutex> guard(lock_); while (state_ != target_state) state_cv_.wait(guard); } EvolutionStage::EvolutionStage(const string& name, size_t size, uint32_t annotations) : name_(name), size_(size), annotations_(annotations) { CHECK(!name.empty()); } void EvolutionStage::recordSubStage(const EvolutionStage& stage) { annotations_ |= stage.annotations_; sub_stages_.push_back(stage); } int EvolutionStage::progressPercent() const { assert(progress_ <= size_); return size_ > 0 ? int(double(progress_) / size_ * 100.0) : 0; } void EvolutionStage::advanceProgress(size_t increment) { CHECK(increment > 0); progress_ += increment; CHECK(progress_ <= size_); } double EvolutionStage::elapsed() const { CHECK(finish_timestamp_ >= start_timestamp_); chrono::duration<double> seconds = finish_timestamp_ - start_timestamp_; return seconds.count(); } void EvolutionStage::addAnnotations(uint32_t annotations) { annotations_ |= annotations; } void to_json(json& json_obj, const EvolutionStage& stage) { // TODO: track start/finish timestamps instead of elapsed json_obj["name"] = stage.name(); json_obj["elapsed"] = stage.elapsed(); const auto& sub_stages = stage.subStages(); if (!sub_stages.empty()) { json_obj["substages"] = sub_stages; } } } // namespace darwin
29.022047
89
0.689348
Siddhant-K-code
1cd8988875fbb32d3d262aa03d8f50ce0797f1f3
5,336
cpp
C++
moos-ivp/ivp/src/lib_geometry/XYCommsPulse.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/lib_geometry/XYCommsPulse.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/lib_geometry/XYCommsPulse.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
/*****************************************************************/ /* NAME: Michael Benjamin */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: XYCommsPulse.cpp */ /* DATE: Dec 5th 2011 */ /* */ /* This file is part of IvP Helm Core Libs */ /* */ /* IvP Helm Core Libs is free software: you can redistribute it */ /* and/or modify it under the terms of the Lesser GNU General */ /* Public License as published by the Free Software Foundation, */ /* either version 3 of the License, or (at your option) any */ /* later version. */ /* */ /* IvP Helm Core Libs 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 Lesser GNU General Public License for more */ /* details. */ /* */ /* You should have received a copy of the Lesser GNU General */ /* Public License along with MOOS-IvP. If not, see */ /* <http://www.gnu.org/licenses/>. */ /*****************************************************************/ #include <iostream> #include "XYCommsPulse.h" #include "GeomUtils.h" #include "ColorPack.h" #include "AngleUtils.h" using namespace std; //------------------------------------------------------------- // Constructor XYCommsPulse::XYCommsPulse() { initialize(); } XYCommsPulse::XYCommsPulse(double sx, double sy, double tx, double ty) { initialize(); m_sx = sx; m_sy = sy; m_tx = tx; m_ty = ty; m_sx_set = true; m_sy_set = true; m_tx_set = true; m_ty_set = true; } //------------------------------------------------------------- // Procedure: initialize void XYCommsPulse::initialize() { // Superclass member variables set_edge_size(0); set_color("fill", "green"); // Local member variables m_sx = 0; m_sy = 0; m_tx = 0; m_ty = 0; m_beam_width = 10; m_sx_set = false; m_sy_set = false; m_tx_set = false; m_ty_set = false; m_duration = 3; m_fill = 0.35; } //------------------------------------------------------------- // Procedure: get_triangle() vector<double> XYCommsPulse::get_triangle(double timestamp) const { vector<double> vpts; if(!m_sx_set || !m_sy_set || !m_tx_set || !m_ty_set) return(vpts); double elapsed_time = timestamp - m_time; if((elapsed_time < 0) || (elapsed_time > m_duration)) return(vpts); // First point is the source vpts.push_back(m_sx); vpts.push_back(m_sy); // Calculate the 2nd and 3rd points double angle = relAng(m_sx, m_sy, m_tx, m_ty); double ax, ay, angle_a = angle360(angle + 90); projectPoint(angle_a, (m_beam_width/2), m_tx, m_ty, ax, ay); vpts.push_back(ax); vpts.push_back(ay); double bx, by, angle_b = angle360(angle + 270); projectPoint(angle_b, (m_beam_width/2), m_tx, m_ty, bx, by); vpts.push_back(bx); vpts.push_back(by); return(vpts); } //------------------------------------------------------------- // Procedure: set_beam_width() void XYCommsPulse::set_beam_width(double val) { m_beam_width = val; if(m_beam_width < 0) m_beam_width = 0; } //------------------------------------------------------------- // Procedure: set_duration() void XYCommsPulse::set_duration(double val) { m_duration = val; if(m_duration < 0) m_duration = 0; } //------------------------------------------------------------- // Procedure: set_fill() void XYCommsPulse::set_fill(double val) { if(val < 0) val = 0; if(val > 1) val = 1; m_fill = val; } //------------------------------------------------------------- // Procedure: get_fill() double XYCommsPulse::get_fill(double timestamp) const { double elapsed_time = timestamp - m_time; if(elapsed_time <= 0) return(m_fill); if(elapsed_time >= m_duration) return(0); double pct = 1.0; if(m_duration > 0) pct = (1-(elapsed_time / m_duration)); double rval = pct * m_fill; return(rval); } //------------------------------------------------------------- // Procedure: valid() bool XYCommsPulse::valid() const { return(m_sx_set && m_sy_set && m_tx_set && m_ty_set); } //------------------------------------------------------------- // Procedure: get_spec() string XYCommsPulse::get_spec(string param) const { string spec = "sx="; spec += doubleToStringX(m_sx); spec += ",sy="; spec += doubleToStringX(m_sy); spec += ",tx="; spec += doubleToStringX(m_tx); spec += ",ty="; spec += doubleToStringX(m_ty); spec += ",beam_width="; spec += doubleToStringX(m_beam_width); spec += ",duration="; spec += doubleToStringX(m_duration); spec += ",fill="; spec += doubleToStringX(m_fill); string obj_spec = XYObject::get_spec(param); if(obj_spec != "") spec += ("," + obj_spec); return(spec); }
25.409524
70
0.498501
EasternEdgeRobotics
1cdb022200e0341dfef07f4b2cafc079b8f72fc0
90
cpp
C++
Source/FSD/Private/PLSEncounterComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/PLSEncounterComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/PLSEncounterComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#include "PLSEncounterComponent.h" UPLSEncounterComponent::UPLSEncounterComponent() { }
15
50
0.811111
trumank
1cde9554045fac17fee74ce98256b8f38e00a5f0
1,779
cpp
C++
src/owlVulkan/core/descriptor_set_layout.cpp
auperes/owl_engine
6da8b48b1caf6cf9f224f1a1d5df59461e83ce9a
[ "MIT" ]
null
null
null
src/owlVulkan/core/descriptor_set_layout.cpp
auperes/owl_engine
6da8b48b1caf6cf9f224f1a1d5df59461e83ce9a
[ "MIT" ]
null
null
null
src/owlVulkan/core/descriptor_set_layout.cpp
auperes/owl_engine
6da8b48b1caf6cf9f224f1a1d5df59461e83ce9a
[ "MIT" ]
null
null
null
#include "descriptor_set_layout.h" #include <array> #include "vulkan_helpers.h" namespace owl::vulkan::core { descriptor_set_layout::descriptor_set_layout(const std::shared_ptr<logical_device>& logical_device) : _logical_device(logical_device) { VkDescriptorSetLayoutBinding uniform_layout_binding{}; uniform_layout_binding.binding = 0; uniform_layout_binding.descriptorCount = 1; uniform_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uniform_layout_binding.pImmutableSamplers = nullptr; uniform_layout_binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; VkDescriptorSetLayoutBinding sampler_layout_binding{}; sampler_layout_binding.binding = 1; sampler_layout_binding.descriptorCount = 1; sampler_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; sampler_layout_binding.pImmutableSamplers = nullptr; sampler_layout_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; std::array<VkDescriptorSetLayoutBinding, 2> bindings = {uniform_layout_binding, sampler_layout_binding}; VkDescriptorSetLayoutCreateInfo layout_info{}; layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layout_info.bindingCount = static_cast<uint32_t>(bindings.size()); layout_info.pBindings = bindings.data(); auto result = vkCreateDescriptorSetLayout(_logical_device->get_vk_handle(), &layout_info, nullptr, &_vk_handle); helpers::handle_result(result, "Failed to create descriptor set layout"); } descriptor_set_layout::~descriptor_set_layout() { vkDestroyDescriptorSetLayout(_logical_device->get_vk_handle(), _vk_handle, nullptr); } } // namespace owl::vulkan
46.815789
140
0.767285
auperes
1ce1d9e1c2bc974a6eb73a02948038db7a816bfc
842
cpp
C++
UAlbertaBot/Source/strategies/zerg/ThreeHatchScourge.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
2
2017-07-06T18:27:41.000Z
2018-03-14T06:19:43.000Z
UAlbertaBot/Source/strategies/zerg/ThreeHatchScourge.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
18
2017-10-29T20:37:47.000Z
2019-08-25T16:01:28.000Z
UAlbertaBot/Source/strategies/zerg/ThreeHatchScourge.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
1
2017-09-13T07:02:23.000Z
2017-09-13T07:02:23.000Z
#include "ThreeHatchScourge.h" #include "..\..\UnitUtil.h" using UAlbertaBot::MetaPairVector; using UAlbertaBot::MetaPair; using UAlbertaBot::UnitUtil::GetAllUnitCount; AKBot::ThreeHatchScourge::ThreeHatchScourge(BWAPI::Player self): _self(self) { } void AKBot::ThreeHatchScourge::getBuildOrderGoal(MetaPairVector& goal, int currentFrame) const { int numDrones = GetAllUnitCount(_self, BWAPI::UnitTypes::Zerg_Drone); int numScourge = GetAllUnitCount(_self, BWAPI::UnitTypes::Zerg_Scourge); int numHydras = GetAllUnitCount(_self, BWAPI::UnitTypes::Zerg_Hydralisk); if (numScourge > 40) { goal.push_back(MetaPair(BWAPI::UnitTypes::Zerg_Hydralisk, numHydras + 12)); } else { goal.push_back(MetaPair(BWAPI::UnitTypes::Zerg_Scourge, numScourge + 12)); } goal.push_back(MetaPair(BWAPI::UnitTypes::Zerg_Drone, numDrones + 4)); }
28.066667
94
0.766033
kant2002
1cec3f6a74dc297e4082b3694dede3711fc066db
2,729
cc
C++
source/common/http/conn_pool_base.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
1
2021-12-10T23:58:57.000Z
2021-12-10T23:58:57.000Z
source/common/http/conn_pool_base.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
30
2022-02-17T02:28:37.000Z
2022-03-31T02:31:02.000Z
source/common/http/conn_pool_base.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
1
2019-11-03T03:46:51.000Z
2019-11-03T03:46:51.000Z
#include "common/http/conn_pool_base.h" namespace Envoy { namespace Http { ConnPoolImplBase::PendingRequest::PendingRequest(ConnPoolImplBase& parent, StreamDecoder& decoder, ConnectionPool::Callbacks& callbacks) : parent_(parent), decoder_(decoder), callbacks_(callbacks) { parent_.host_->cluster().stats().upstream_rq_pending_total_.inc(); parent_.host_->cluster().stats().upstream_rq_pending_active_.inc(); parent_.host_->cluster().resourceManager(parent_.priority_).pendingRequests().inc(); } ConnPoolImplBase::PendingRequest::~PendingRequest() { parent_.host_->cluster().stats().upstream_rq_pending_active_.dec(); parent_.host_->cluster().resourceManager(parent_.priority_).pendingRequests().dec(); } ConnectionPool::Cancellable* ConnPoolImplBase::newPendingRequest(StreamDecoder& decoder, ConnectionPool::Callbacks& callbacks) { ENVOY_LOG(debug, "queueing request due to no available connections"); PendingRequestPtr pending_request(new PendingRequest(*this, decoder, callbacks)); pending_request->moveIntoList(std::move(pending_request), pending_requests_); return pending_requests_.front().get(); } void ConnPoolImplBase::purgePendingRequests( const Upstream::HostDescriptionConstSharedPtr& host_description, absl::string_view failure_reason) { // NOTE: We move the existing pending requests to a temporary list. This is done so that // if retry logic submits a new request to the pool, we don't fail it inline. pending_requests_to_purge_ = std::move(pending_requests_); while (!pending_requests_to_purge_.empty()) { PendingRequestPtr request = pending_requests_to_purge_.front()->removeFromList(pending_requests_to_purge_); host_->cluster().stats().upstream_rq_pending_failure_eject_.inc(); request->callbacks_.onPoolFailure(ConnectionPool::PoolFailureReason::ConnectionFailure, failure_reason, host_description); } } void ConnPoolImplBase::onPendingRequestCancel(PendingRequest& request) { ENVOY_LOG(debug, "cancelling pending request"); if (!pending_requests_to_purge_.empty()) { // If pending_requests_to_purge_ is not empty, it means that we are called from // with-in a onPoolFailure callback invoked in purgePendingRequests (i.e. purgePendingRequests // is down in the call stack). Remove this request from the list as it is cancelled, // and there is no need to call its onPoolFailure callback. request.removeFromList(pending_requests_to_purge_); } else { request.removeFromList(pending_requests_); } host_->cluster().stats().upstream_rq_cancelled_.inc(); checkForDrained(); } } // namespace Http } // namespace Envoy
46.254237
99
0.751557
jaricftw
1cec87866a9ada7ac611ed3a82cc35c828bd8104
7,002
cpp
C++
YorozuyaGSLib/source/_dh_mission_mgrDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_dh_mission_mgrDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_dh_mission_mgrDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_dh_mission_mgrDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::_dh_mission_mgrGetLimMSecTime2_ptr _dh_mission_mgrGetLimMSecTime2_next(nullptr); Info::_dh_mission_mgrGetLimMSecTime2_clbk _dh_mission_mgrGetLimMSecTime2_user(nullptr); Info::_dh_mission_mgrGetMissionCont4_ptr _dh_mission_mgrGetMissionCont4_next(nullptr); Info::_dh_mission_mgrGetMissionCont4_clbk _dh_mission_mgrGetMissionCont4_user(nullptr); Info::_dh_mission_mgrInit6_ptr _dh_mission_mgrInit6_next(nullptr); Info::_dh_mission_mgrInit6_clbk _dh_mission_mgrInit6_user(nullptr); Info::_dh_mission_mgrIsOpenPortal8_ptr _dh_mission_mgrIsOpenPortal8_next(nullptr); Info::_dh_mission_mgrIsOpenPortal8_clbk _dh_mission_mgrIsOpenPortal8_user(nullptr); Info::_dh_mission_mgrNextMission10_ptr _dh_mission_mgrNextMission10_next(nullptr); Info::_dh_mission_mgrNextMission10_clbk _dh_mission_mgrNextMission10_user(nullptr); Info::_dh_mission_mgrOpenPortal12_ptr _dh_mission_mgrOpenPortal12_next(nullptr); Info::_dh_mission_mgrOpenPortal12_clbk _dh_mission_mgrOpenPortal12_user(nullptr); Info::_dh_mission_mgrSearchCurMissionCont14_ptr _dh_mission_mgrSearchCurMissionCont14_next(nullptr); Info::_dh_mission_mgrSearchCurMissionCont14_clbk _dh_mission_mgrSearchCurMissionCont14_user(nullptr); Info::_dh_mission_mgrctor__dh_mission_mgr16_ptr _dh_mission_mgrctor__dh_mission_mgr16_next(nullptr); Info::_dh_mission_mgrctor__dh_mission_mgr16_clbk _dh_mission_mgrctor__dh_mission_mgr16_user(nullptr); unsigned int _dh_mission_mgrGetLimMSecTime2_wrapper(struct _dh_mission_mgr* _this) { return _dh_mission_mgrGetLimMSecTime2_user(_this, _dh_mission_mgrGetLimMSecTime2_next); }; struct _dh_mission_mgr::_if_change* _dh_mission_mgrGetMissionCont4_wrapper(struct _dh_mission_mgr* _this, struct _dh_mission_setup* pMsSetup) { return _dh_mission_mgrGetMissionCont4_user(_this, pMsSetup, _dh_mission_mgrGetMissionCont4_next); }; void _dh_mission_mgrInit6_wrapper(struct _dh_mission_mgr* _this) { _dh_mission_mgrInit6_user(_this, _dh_mission_mgrInit6_next); }; bool _dh_mission_mgrIsOpenPortal8_wrapper(struct _dh_mission_mgr* _this, int nIndex) { return _dh_mission_mgrIsOpenPortal8_user(_this, nIndex, _dh_mission_mgrIsOpenPortal8_next); }; void _dh_mission_mgrNextMission10_wrapper(struct _dh_mission_mgr* _this, struct _dh_mission_setup* pNextMssionPtr) { _dh_mission_mgrNextMission10_user(_this, pNextMssionPtr, _dh_mission_mgrNextMission10_next); }; void _dh_mission_mgrOpenPortal12_wrapper(struct _dh_mission_mgr* _this, int nIndex) { _dh_mission_mgrOpenPortal12_user(_this, nIndex, _dh_mission_mgrOpenPortal12_next); }; struct _dh_mission_mgr::_if_change* _dh_mission_mgrSearchCurMissionCont14_wrapper(struct _dh_mission_mgr* _this) { return _dh_mission_mgrSearchCurMissionCont14_user(_this, _dh_mission_mgrSearchCurMissionCont14_next); }; void _dh_mission_mgrctor__dh_mission_mgr16_wrapper(struct _dh_mission_mgr* _this) { _dh_mission_mgrctor__dh_mission_mgr16_user(_this, _dh_mission_mgrctor__dh_mission_mgr16_next); }; ::std::array<hook_record, 8> _dh_mission_mgr_functions = { _hook_record { (LPVOID)0x14026ef40L, (LPVOID *)&_dh_mission_mgrGetLimMSecTime2_user, (LPVOID *)&_dh_mission_mgrGetLimMSecTime2_next, (LPVOID)cast_pointer_function(_dh_mission_mgrGetLimMSecTime2_wrapper), (LPVOID)cast_pointer_function((unsigned int(_dh_mission_mgr::*)())&_dh_mission_mgr::GetLimMSecTime) }, _hook_record { (LPVOID)0x14026f220L, (LPVOID *)&_dh_mission_mgrGetMissionCont4_user, (LPVOID *)&_dh_mission_mgrGetMissionCont4_next, (LPVOID)cast_pointer_function(_dh_mission_mgrGetMissionCont4_wrapper), (LPVOID)cast_pointer_function((struct _dh_mission_mgr::_if_change*(_dh_mission_mgr::*)(struct _dh_mission_setup*))&_dh_mission_mgr::GetMissionCont) }, _hook_record { (LPVOID)0x14026ed50L, (LPVOID *)&_dh_mission_mgrInit6_user, (LPVOID *)&_dh_mission_mgrInit6_next, (LPVOID)cast_pointer_function(_dh_mission_mgrInit6_wrapper), (LPVOID)cast_pointer_function((void(_dh_mission_mgr::*)())&_dh_mission_mgr::Init) }, _hook_record { (LPVOID)0x14026f4a0L, (LPVOID *)&_dh_mission_mgrIsOpenPortal8_user, (LPVOID *)&_dh_mission_mgrIsOpenPortal8_next, (LPVOID)cast_pointer_function(_dh_mission_mgrIsOpenPortal8_wrapper), (LPVOID)cast_pointer_function((bool(_dh_mission_mgr::*)(int))&_dh_mission_mgr::IsOpenPortal) }, _hook_record { (LPVOID)0x14026efc0L, (LPVOID *)&_dh_mission_mgrNextMission10_user, (LPVOID *)&_dh_mission_mgrNextMission10_next, (LPVOID)cast_pointer_function(_dh_mission_mgrNextMission10_wrapper), (LPVOID)cast_pointer_function((void(_dh_mission_mgr::*)(struct _dh_mission_setup*))&_dh_mission_mgr::NextMission) }, _hook_record { (LPVOID)0x1400c2d10L, (LPVOID *)&_dh_mission_mgrOpenPortal12_user, (LPVOID *)&_dh_mission_mgrOpenPortal12_next, (LPVOID)cast_pointer_function(_dh_mission_mgrOpenPortal12_wrapper), (LPVOID)cast_pointer_function((void(_dh_mission_mgr::*)(int))&_dh_mission_mgr::OpenPortal) }, _hook_record { (LPVOID)0x14026f580L, (LPVOID *)&_dh_mission_mgrSearchCurMissionCont14_user, (LPVOID *)&_dh_mission_mgrSearchCurMissionCont14_next, (LPVOID)cast_pointer_function(_dh_mission_mgrSearchCurMissionCont14_wrapper), (LPVOID)cast_pointer_function((struct _dh_mission_mgr::_if_change*(_dh_mission_mgr::*)())&_dh_mission_mgr::SearchCurMissionCont) }, _hook_record { (LPVOID)0x14026eb70L, (LPVOID *)&_dh_mission_mgrctor__dh_mission_mgr16_user, (LPVOID *)&_dh_mission_mgrctor__dh_mission_mgr16_next, (LPVOID)cast_pointer_function(_dh_mission_mgrctor__dh_mission_mgr16_wrapper), (LPVOID)cast_pointer_function((void(_dh_mission_mgr::*)())&_dh_mission_mgr::ctor__dh_mission_mgr) }, }; }; // end namespace Detail END_ATF_NAMESPACE
54.703125
163
0.699372
lemkova
1ced9b79f8b3dd329e525472b67c8ebea77b2953
32,862
cpp
C++
plugins/CaptureTheFlag.cpp
PsychoLogicAu/GPUSteer
99c23f0e27468b964207d65758612ade7d7c4892
[ "MIT" ]
null
null
null
plugins/CaptureTheFlag.cpp
PsychoLogicAu/GPUSteer
99c23f0e27468b964207d65758612ade7d7c4892
[ "MIT" ]
null
null
null
plugins/CaptureTheFlag.cpp
PsychoLogicAu/GPUSteer
99c23f0e27468b964207d65758612ade7d7c4892
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // // // OpenSteer -- Steering Behaviors for Autonomous Characters // // Copyright (c) 2002-2003, Sony Computer Entertainment America // Original author: Craig Reynolds <craig_reynolds@playstation.sony.com> // // 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. // // // ---------------------------------------------------------------------------- // // // Capture the Flag (a portion of the traditional game) // // The "Capture the Flag" sample steering problem, proposed by Marcin // Chady of the Working Group on Steering of the IGDA's AI Interface // Standards Committee (http://www.igda.org/Committees/ai.htm) in this // message (http://sourceforge.net/forum/message.php?msg_id=1642243): // // "An agent is trying to reach a physical location while trying // to stay clear of a group of enemies who are actively seeking // him. The environment is littered with obstacles, so collision // avoidance is also necessary." // // Note that the enemies do not make use of their knowledge of the // seeker's goal by "guarding" it. // // XXX hmm, rename them "attacker" and "defender"? // // 08-12-02 cwr: created // // // ---------------------------------------------------------------------------- #include <iomanip> #include <sstream> #include "OpenSteer/SimpleVehicle.h" #include "OpenSteer/OpenSteerDemo.h" using namespace OpenSteer; // ---------------------------------------------------------------------------- // short names for STL vectors (iterators) of SphericalObstacle pointers typedef std::vector<SphericalObstacle*> SOG; // spherical obstacle group typedef SOG::const_iterator SOI; // spherical obstacle iterator // ---------------------------------------------------------------------------- // This PlugIn uses two vehicle types: CtfSeeker and CtfEnemy. They have a // common base class: CtfBase which is a specialization of SimpleVehicle. class CtfBase : public SimpleVehicle { public: // constructor CtfBase () {reset ();} // reset state void reset (void); // draw this character/vehicle into the scene void draw (void); // annotate when actively avoiding obstacles void annotateAvoidObstacle (const float minDistanceToCollision); void drawHomeBase (void); void randomizeStartingPositionAndHeading (void); enum seekerState {running, tagged, atGoal}; // for draw method float3 bodyColor; // xxx store steer sub-state for anotation bool avoiding; // dynamic obstacle registry static void initializeObstacles (void); static void addOneObstacle (void); static void removeOneObstacle (void); float minDistanceToObstacle (const float3 point); static int obstacleCount; static const int maxObstacleCount; static SOG allObstacles; }; class CtfSeeker : public CtfBase { public: // constructor CtfSeeker () {reset ();} // reset state void reset (void); // per frame simulation update void update (const float currentTime, const float elapsedTime); // is there a clear path to the goal? bool clearPathToGoal (void); float3 steeringForSeeker (void); void updateState (const float currentTime); void draw (void); float3 steerToEvadeAllDefenders (void); float3 XXXsteerToEvadeAllDefenders (void); void adjustObstacleAvoidanceLookAhead (const bool clearPath); void clearPathAnnotation (const float threshold, const float behindcThreshold, const float3& goalDirection); seekerState state; bool evading; // xxx store steer sub-state for anotation float lastRunningTime; // for auto-reset }; class CtfEnemy : public CtfBase { public: // constructor CtfEnemy () {reset ();} // reset state void reset (void); // per frame simulation update void update (const float currentTime, const float elapsedTime); }; // ---------------------------------------------------------------------------- // globals // (perhaps these should be member variables of a Vehicle or PlugIn class) const int CtfBase::maxObstacleCount = 100; const float3 gHomeBaseCenter = make_float3(0, 0, 0); const float gHomeBaseRadius = 1.5; const float gMinStartRadius = 30; const float gMaxStartRadius = 40; const float gBrakingRate = 0.75; const float3 evadeColor = make_float3(0.6f, 0.6f, 0.3f); // annotation const float3 seekColor = make_float3(0.3f, 0.6f, 0.6f); // annotation const float3 clearPathColor = make_float3(0.3f, 0.6f, 0.3f); // annotation const float gAvoidancePredictTimeMin = 0.9f; const float gAvoidancePredictTimeMax = 2; float gAvoidancePredictTime = gAvoidancePredictTimeMin; bool enableAttackSeek = true; // for testing (perhaps retain for UI control?) bool enableAttackEvade = true; // for testing (perhaps retain for UI control?) CtfSeeker* gSeeker = NULL; // count the number of times the simulation has reset (e.g. for overnight runs) int resetCount = 0; // ---------------------------------------------------------------------------- // state for OpenSteerDemo PlugIn // // XXX consider moving this inside CtfPlugIn // XXX consider using STL (any advantage? consistency?) CtfSeeker* ctfSeeker; const int ctfEnemyCount = 1000; CtfEnemy* ctfEnemies [ctfEnemyCount]; // ---------------------------------------------------------------------------- // reset state void CtfBase::reset (void) { SimpleVehicle::reset (); // reset the vehicle setSpeed (3); // speed along Forward direction. setMaxForce (3.0); // steering force is clipped to this magnitude setMaxSpeed (3.0); // velocity is clipped to this magnitude avoiding = false; // not actively avoiding randomizeStartingPositionAndHeading (); // new starting position clearTrailHistory (); // prevent long streaks due to teleportation } void CtfSeeker::reset (void) { CtfBase::reset (); bodyColor = make_float3(0.4f, 0.4f, 0.6f); // blueish gSeeker = this; state = running; evading = false; setPosition(float3_scalar_multiply(position(), 2.0f)); } void CtfEnemy::reset (void) { CtfBase::reset (); bodyColor = make_float3(0.6f, 0.4f, 0.4f); // redish } // ---------------------------------------------------------------------------- // draw this character/vehicle into the scene void CtfBase::draw (void) { drawBasic2dCircularVehicle (*this, bodyColor); drawTrail (); } // ---------------------------------------------------------------------------- void CtfBase::randomizeStartingPositionAndHeading (void) { // randomize position on a ring between inner and outer radii // centered around the home base const float rRadius = frandom2 (gMinStartRadius, gMaxStartRadius); const float3 randomOnRing = float3_scalar_multiply(float3_RandomUnitVectorOnXZPlane (), rRadius); setPosition (float3_add(gHomeBaseCenter, randomOnRing)); // are we are too close to an obstacle? if (minDistanceToObstacle (position()) < radius()*5) { // if so, retry the randomization (this recursive call may not return // if there is too little free space) randomizeStartingPositionAndHeading (); } else { // otherwise, if the position is OK, randomize 2D heading randomizeHeadingOnXZPlane (); } } // ---------------------------------------------------------------------------- void CtfEnemy::update (const float currentTime, const float elapsedTime) { // determine upper bound for pursuit prediction time const float seekerToGoalDist = float3_distance(gHomeBaseCenter, gSeeker->position()); const float adjustedDistance = seekerToGoalDist - radius()-gHomeBaseRadius; const float seekerToGoalTime = ((adjustedDistance < 0 ) ? 0 : (adjustedDistance/gSeeker->speed())); const float maxPredictionTime = seekerToGoalTime * 0.9f; // determine steering (pursuit, obstacle avoidance, or braking) float3 steer = make_float3(0, 0, 0); if (gSeeker->state == running) { const float3 avoidance = steerToAvoidObstacles (*this, gAvoidancePredictTimeMin, (ObstacleGroup&) allObstacles); // saved for annotation avoiding = float3_equals(avoidance, float3_zero()); if (avoiding) steer = steerForPursuit (*this, *gSeeker, maxPredictionTime); else steer = avoidance; } else { applyBrakingForce (gBrakingRate, elapsedTime); } applySteeringForce (steer, elapsedTime); // annotation annotationVelocityAcceleration (); recordTrailVertex (currentTime, position()); // detect and record interceptions ("tags") of seeker const float seekerToMeDist = float3_distance (position(), gSeeker->position()); const float sumOfRadii = radius() + gSeeker->radius(); if (seekerToMeDist < sumOfRadii) { if (gSeeker->state == running) gSeeker->state = tagged; // annotation: if (gSeeker->state == tagged) { const float3 color = make_float3(0.8f, 0.5f, 0.5f); annotationXZDisk (sumOfRadii, float3_scalar_divide(float3_add(position(), gSeeker->position()), 2), color, 20); } } } // ---------------------------------------------------------------------------- // are there any enemies along the corridor between us and the goal? bool CtfSeeker::clearPathToGoal (void) { const float sideThreshold = radius() * 8.0f; const float behindThreshold = radius() * 2.0f; const float3 goalOffset = float3_subtract(gHomeBaseCenter, position()); const float goalDistance = float3_length(goalOffset); const float3 goalDirection = float3_scalar_divide(goalOffset, goalDistance); const bool goalIsAside = isAside (*this, gHomeBaseCenter, 0.5); // for annotation: loop over all and save result, instead of early return bool xxxReturn = true; // loop over enemies for (int i = 0; i < ctfEnemyCount; i++) { // short name for this enemy const CtfEnemy& e = *ctfEnemies[i]; const float eDistance = float3_distance (position(), e.position()); const float timeEstimate = 0.3f * eDistance / e.speed(); //xxx const float3 eFuture = e.predictFuturePosition (timeEstimate); const float3 eOffset = float3_subtract(eFuture, position()); const float alongCorridor = float3_dot(goalDirection, eOffset); const bool inCorridor = ((alongCorridor > -behindThreshold) && (alongCorridor < goalDistance)); const float eForwardDistance = float3_dot(forward(), eOffset); // xxx temp move this up before the conditionals annotationXZCircle (e.radius(), eFuture, clearPathColor, 20); //xxx // consider as potential blocker if within the corridor if (inCorridor) { const float3 perp = float3_subtract(eOffset, float3_scalar_multiply(goalDirection, alongCorridor)); const float acrossCorridor = float3_length(perp); if (acrossCorridor < sideThreshold) { // not a blocker if behind us and we are perp to corridor const float eFront = eForwardDistance + e.radius (); //annotationLine (position, forward*eFront, gGreen); // xxx //annotationLine (e.position, forward*eFront, gGreen); // xxx // xxx // std::ostringstream message; // message << "eFront = " << std::setprecision(2) // << std::setiosflags(std::ios::fixed) << eFront << std::ends; // draw2dTextAt3dLocation (*message.str(), eFuture, gWhite); const bool eIsBehind = eFront < -behindThreshold; const bool eIsWayBehind = eFront < (-2 * behindThreshold); const bool safeToTurnTowardsGoal = ((eIsBehind && goalIsAside) || eIsWayBehind); if (! safeToTurnTowardsGoal) { // this enemy blocks the path to the goal, so return false annotationLine (position(), e.position(), clearPathColor); // return false; xxxReturn = false; } } } } // no enemies found along path, return true to indicate path is clear // clearPathAnnotation (sideThreshold, behindThreshold, goalDirection); // return true; if (xxxReturn) clearPathAnnotation (sideThreshold, behindThreshold, goalDirection); return xxxReturn; } // ---------------------------------------------------------------------------- void CtfSeeker::clearPathAnnotation (const float sideThreshold, const float behindThreshold, const float3& goalDirection) { const float3 behindSide = float3_scalar_multiply(side(), sideThreshold); const float3 behindBack = float3_scalar_multiply(forward(), -behindThreshold); const float3 pbb = float3_add(position(), behindBack); const float3 gun = localRotateForwardToSide (goalDirection); const float3 gn = float3_scalar_multiply(gun, sideThreshold); const float3 hbc = gHomeBaseCenter; annotationLine (float3_add(pbb, gn), float3_add(hbc, gn), clearPathColor); annotationLine (float3_subtract(pbb, gn), float3_subtract(hbc, gn), clearPathColor); annotationLine (float3_subtract(hbc, gn), float3_add(hbc, gn), clearPathColor); annotationLine (float3_subtract(pbb, behindSide), float3_add(pbb, behindSide), clearPathColor); } // ---------------------------------------------------------------------------- // xxx perhaps this should be a call to a general purpose annotation // xxx for "local xxx axis aligned box in XZ plane" -- same code in in // xxx Pedestrian.cpp void CtfBase::annotateAvoidObstacle (const float minDistanceToCollision) { const float3 boxSide = float3_scalar_multiply(side(), radius()); const float3 boxFront = float3_scalar_multiply(forward(), minDistanceToCollision); const float3 FR = float3_subtract(float3_add(position(), boxFront), boxSide); const float3 FL = float3_add(float3_add(position(), boxFront), boxSide); const float3 BR = float3_subtract(position(), boxSide); const float3 BL = float3_add(position(), boxSide); const float3 white = make_float3(1,1,1); annotationLine (FR, FL, white); annotationLine (FL, BL, white); annotationLine (BL, BR, white); annotationLine (BR, FR, white); } // ---------------------------------------------------------------------------- float3 CtfSeeker::steerToEvadeAllDefenders (void) { float3 evade = float3_zero(); const float goalDistance = float3_distance(gHomeBaseCenter, position()); // sum up weighted evasion for (int i = 0; i < ctfEnemyCount; i++) { const CtfEnemy& e = *ctfEnemies[i]; const float3 eOffset = float3_subtract(e.position(), position()); const float eDistance = float3_length(eOffset); const float eForwardDistance = float3_dot(forward(), eOffset); const float behindThreshold = radius() * 2; const bool behind = eForwardDistance < behindThreshold; if ((!behind) || (eDistance < 5)) { if (eDistance < (goalDistance * 1.2)) //xxx { const float timeEstimate = 0.5f * eDistance / e.speed();//xxx //const float timeEstimate = 0.15f * eDistance / e.speed();//xxx const float3 future = e.predictFuturePosition (timeEstimate); annotationXZCircle (e.radius(), future, evadeColor, 20); // xxx const float3 offset = float3_subtract(future, position()); const float3 lateral = float3_perpendicularComponent(offset, forward()); const float d = float3_length(lateral); const float weight = -1000 / (d * d); evade = float3_add(evade, float3_scalar_multiply(float3_scalar_divide(lateral, d), weight)); } } } return evade; } float3 CtfSeeker::XXXsteerToEvadeAllDefenders (void) { // sum up weighted evasion float3 evade = float3_zero(); for (int i = 0; i < ctfEnemyCount; i++) { const CtfEnemy& e = *ctfEnemies[i]; const float3 eOffset = float3_subtract(e.position(), position()); const float eDistance = float3_length(eOffset); // xxx maybe this should take into account e's heading? xxx // TODO: just that :) const float timeEstimate = 0.5f * eDistance / e.speed(); //xxx const float3 eFuture = e.predictFuturePosition (timeEstimate); // annotation annotationXZCircle (e.radius(), eFuture, evadeColor, 20); // steering to flee from eFuture (enemy's future position) const float3 flee = xxxsteerForFlee (*this, eFuture); const float eForwardDistance = float3_dot(forward(), eOffset); const float behindThreshold = radius() * -2; const float distanceWeight = 4 / eDistance; const float forwardWeight = ((eForwardDistance > behindThreshold) ? 1.0f : 0.5f); const float3 adjustedFlee = float3_scalar_multiply(flee, distanceWeight * forwardWeight); evade = float3_add(evade, adjustedFlee); } return evade; } // ---------------------------------------------------------------------------- float3 CtfSeeker::steeringForSeeker (void) { // determine if obstacle avodiance is needed const bool clearPath = clearPathToGoal (); adjustObstacleAvoidanceLookAhead (clearPath); const float3 obstacleAvoidance = steerToAvoidObstacles (*this, gAvoidancePredictTime, (ObstacleGroup&) allObstacles); // saved for annotation avoiding = !float3_equals(obstacleAvoidance, float3_zero()); if (avoiding) { // use pure obstacle avoidance if needed return obstacleAvoidance; } else { // otherwise seek home base and perhaps evade defenders const float3 seek = xxxsteerForSeek (*this, gHomeBaseCenter); if (clearPath) { // we have a clear path (defender-free corridor), use pure seek // xxx experiment 9-16-02 float3 s = limitMaxDeviationAngle (seek, 0.707f, forward()); annotationLine (position(), float3_add(position(), float3_scalar_multiply(s, 0.2f)), seekColor); return s; } else { if (1) // xxx testing new evade code xxx { // combine seek and (forward facing portion of) evasion const float3 evade = steerToEvadeAllDefenders (); const float3 steer = float3_add(seek, limitMaxDeviationAngle (evade, 0.5f, forward())); // annotation: show evasion steering force annotationLine (position(), float3_add(position(), float3_scalar_multiply(steer, 0.2f)), evadeColor); return steer; } else { const float3 evade = XXXsteerToEvadeAllDefenders (); const float3 steer = limitMaxDeviationAngle (float3_add(seek, evade), 0.707f, forward()); annotationLine (position(),float3_add(position(),seek), gRed); annotationLine (position(),float3_add(position(),evade), gGreen); // annotation: show evasion steering force annotationLine (position(),float3_add(position(),float3_scalar_multiply(steer,0.2f)),evadeColor); return steer; } } } } // ---------------------------------------------------------------------------- // adjust obstacle avoidance look ahead time: make it large when we are far // from the goal and heading directly towards it, make it small otherwise. void CtfSeeker::adjustObstacleAvoidanceLookAhead (const bool clearPath) { if (clearPath) { evading = false; const float goalDistance = float3_distance(gHomeBaseCenter,position()); const bool headingTowardGoal = isAhead (*this, gHomeBaseCenter, 0.98f); const bool isNear = (goalDistance/speed()) < gAvoidancePredictTimeMax; const bool useMax = headingTowardGoal && !isNear; gAvoidancePredictTime = (useMax ? gAvoidancePredictTimeMax : gAvoidancePredictTimeMin); } else { evading = true; gAvoidancePredictTime = gAvoidancePredictTimeMin; } } // ---------------------------------------------------------------------------- void CtfSeeker::updateState (const float currentTime) { // if we reach the goal before being tagged, switch to atGoal state if (state == running) { const float baseDistance = float3_distance(position(),gHomeBaseCenter); if (baseDistance < (radius() + gHomeBaseRadius)) state = atGoal; } // update lastRunningTime (holds off reset time) if (state == running) { lastRunningTime = currentTime; } else { const float resetDelay = 4; const float resetTime = lastRunningTime + resetDelay; if (currentTime > resetTime) { // xxx a royal hack (should do this internal to CTF): OpenSteerDemo::queueDelayedResetPlugInXXX (); } } } // ---------------------------------------------------------------------------- void CtfSeeker::draw (void) { // first call the draw method in the base class CtfBase::draw(); // select string describing current seeker state char* seekerStateString = ""; switch (state) { case running: if (avoiding) seekerStateString = "avoid obstacle"; else if (evading) seekerStateString = "seek and evade"; else seekerStateString = "seek goal"; break; case tagged: seekerStateString = "tagged"; break; case atGoal: seekerStateString = "reached goal"; break; } // annote seeker with its state as text const float3 textOrigin = float3_add(position(), make_float3(0, 0.25, 0)); std::ostringstream annote; annote << seekerStateString << std::endl; annote << std::setprecision(2) << std::setiosflags(std::ios::fixed) << speed() << std::ends; draw2dTextAt3dLocation (annote, textOrigin, gWhite); // display status in the upper left corner of the window std::ostringstream status; status << seekerStateString << std::endl; status << obstacleCount << " obstacles [F1/F2]" << std::endl; status << "position: " << position().x << ", " << position().z << std::endl; status << resetCount << " restarts" << std::ends; const float h = drawGetWindowHeight (); const float3 screenLocation = make_float3(10, h-50, 0); draw2dTextAt2dLocation (status, screenLocation, gGray80); } // ---------------------------------------------------------------------------- // update method for goal seeker void CtfSeeker::update (const float currentTime, const float elapsedTime) { // do behavioral state transitions, as needed updateState (currentTime); // determine and apply steering/braking forces float3 steer = make_float3(0, 0, 0); if (state == running) { steer = steeringForSeeker (); } else { applyBrakingForce (gBrakingRate, elapsedTime); } applySteeringForce (steer, elapsedTime); // annotation annotationVelocityAcceleration (); recordTrailVertex (currentTime, position()); } // ---------------------------------------------------------------------------- // dynamic obstacle registry // // xxx need to combine guts of addOneObstacle and minDistanceToObstacle, // xxx perhaps by having the former call the latter, or change the latter to // xxx be "nearestObstacle": give it a position, it finds the nearest obstacle // xxx (but remember: obstacles a not necessarilty spheres!) int CtfBase::obstacleCount = -1; // this value means "uninitialized" SOG CtfBase::allObstacles; #define testOneObstacleOverlap(radius, center) \ { \ float d = float3_distance (c, center); \ float clearance = d - (r + (radius)); \ if (minClearance > clearance) minClearance = clearance; \ } void CtfBase::initializeObstacles (void) { // start with 40% of possible obstacles if (obstacleCount == -1) { obstacleCount = 0; for (int i = 0; i < (maxObstacleCount * 0.4); i++) addOneObstacle (); } } void CtfBase::addOneObstacle (void) { if (obstacleCount < maxObstacleCount) { // pick a random center and radius, // loop until no overlap with other obstacles and the home base float r; float3 c; float minClearance; const float requiredClearance = gSeeker->radius() * 4; // 2 x diameter do { r = frandom2 (1.5, 4); c = float3_scalar_multiply(float3_randomVectorOnUnitRadiusXZDisk(), gMaxStartRadius * 1.1f); minClearance = FLT_MAX; for (SOI so = allObstacles.begin(); so != allObstacles.end(); so++) { testOneObstacleOverlap ((**so).radius, (**so).center); } testOneObstacleOverlap (gHomeBaseRadius - requiredClearance, gHomeBaseCenter); } while (minClearance < requiredClearance); // add new non-overlapping obstacle to registry allObstacles.push_back (new SphericalObstacle (r, c)); obstacleCount++; } } float CtfBase::minDistanceToObstacle (const float3 point) { float r = 0; float3 c = point; float minClearance = FLT_MAX; for (SOI so = allObstacles.begin(); so != allObstacles.end(); so++) { testOneObstacleOverlap ((**so).radius, (**so).center); } return minClearance; } void CtfBase::removeOneObstacle (void) { if (obstacleCount > 0) { obstacleCount--; allObstacles.pop_back(); } } // ---------------------------------------------------------------------------- // PlugIn for OpenSteerDemo class CtfPlugIn : public PlugIn { public: const char* name (void) {return "Capture the Flag";} float selectionOrderSortKey (void) {return 0.01f;} virtual ~CtfPlugIn() {} // be more "nice" to avoid a compiler warning void open (void) { // create the seeker ("hero"/"attacker") ctfSeeker = new CtfSeeker; all.push_back (ctfSeeker); // create the specified number of enemies, // storing pointers to them in an array. for (int i = 0; i<ctfEnemyCount; i++) { ctfEnemies[i] = new CtfEnemy; all.push_back (ctfEnemies[i]); } // initialize camera OpenSteerDemo::init2dCamera (*ctfSeeker); OpenSteerDemo::camera.mode = Camera::cmFixedDistanceOffset; OpenSteerDemo::camera.fixedTarget = make_float3(15, 0, 0); OpenSteerDemo::camera.fixedPosition = make_float3(80, 60, 0); CtfBase::initializeObstacles (); } void update (const float currentTime, const float elapsedTime) { // update the seeker ctfSeeker->update (currentTime, elapsedTime); // update each enemy for (int i = 0; i < ctfEnemyCount; i++) { ctfEnemies[i]->update (currentTime, elapsedTime); } } void redraw (const float currentTime, const float elapsedTime) { // selected vehicle (user can mouse click to select another) AbstractVehicle& selected = *OpenSteerDemo::selectedVehicle; // vehicle nearest mouse (to be highlighted) AbstractVehicle& nearMouse = *OpenSteerDemo::vehicleNearestToMouse (); // update camera OpenSteerDemo::updateCamera (currentTime, elapsedTime, selected); // draw "ground plane" centered between base and selected vehicle const float3 goalOffset = float3_subtract(gHomeBaseCenter, OpenSteerDemo::camera.position()); const float3 goalDirection = float3_normalize(goalOffset); const float3 cameraForward = OpenSteerDemo::camera.xxxls().forward(); const float goalDot = float3_dot(cameraForward, goalDirection); const float blend = remapIntervalClip (goalDot, 1, 0, 0.5, 0); const float3 gridCenter = interpolate (blend, selected.position(), gHomeBaseCenter); OpenSteerDemo::gridUtility (gridCenter); // draw the seeker, obstacles and home base ctfSeeker->draw(); drawObstacles (); drawHomeBase(); // draw each enemy for (int i = 0; i < ctfEnemyCount; i++) ctfEnemies[i]->draw (); // highlight vehicle nearest mouse OpenSteerDemo::highlightVehicleUtility (nearMouse); } void close (void) { // delete seeker delete (ctfSeeker); ctfSeeker = NULL; // delete each enemy for (int i = 0; i < ctfEnemyCount; i++) { delete (ctfEnemies[i]); ctfEnemies[i] = NULL; } // clear the group of all vehicles all.clear(); } void reset (void) { // count resets resetCount++; // reset the seeker ("hero"/"attacker") and enemies ctfSeeker->reset (); for (int i = 0; i<ctfEnemyCount; i++) ctfEnemies[i]->reset (); // reset camera position OpenSteerDemo::position2dCamera (*ctfSeeker); // make camera jump immediately to new position OpenSteerDemo::camera.doNotSmoothNextMove (); } void handleFunctionKeys (int keyNumber) { switch (keyNumber) { case 1: CtfBase::addOneObstacle (); break; case 2: CtfBase::removeOneObstacle (); break; } } void printMiniHelpForFunctionKeys (void) { std::ostringstream message; message << "Function keys handled by "; message << '"' << name() << '"' << ':' << std::ends; OpenSteerDemo::printMessage (message); OpenSteerDemo::printMessage (" F1 add one obstacle."); OpenSteerDemo::printMessage (" F2 remove one obstacle."); OpenSteerDemo::printMessage (""); } const AVGroup& allVehicles (void) {return (const AVGroup&) all;} void drawHomeBase (void) { const float3 up = make_float3(0, 0.01f, 0); const float3 atColor = make_float3(0.3f, 0.3f, 0.5f); const float3 noColor = gGray50; const bool reached = ctfSeeker->state == CtfSeeker::atGoal; const float3 baseColor = (reached ? atColor : noColor); drawXZDisk (gHomeBaseRadius, gHomeBaseCenter, baseColor, 40); drawXZDisk (gHomeBaseRadius/15, float3_add(gHomeBaseCenter, up), gBlack, 20); } void drawObstacles (void) { const float3 color = make_float3(0.8f, 0.6f, 0.4f); const SOG& allSO = CtfBase::allObstacles; for (SOI so = allSO.begin(); so != allSO.end(); so++) { drawXZCircle ((**so).radius, (**so).center, color, 40); } } // a group (STL vector) of all vehicles in the PlugIn std::vector<CtfBase*> all; }; CtfPlugIn gCtfPlugIn; // ----------------------------------------------------------------------------
34.124611
121
0.603493
PsychoLogicAu
1cee2ff8ee63ba51aec389c7f3406455fdd7a3e5
892
hpp
C++
SDK/ARKSurvivalEvolved_StructureSettings_BrokenByPlasma_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_StructureSettings_BrokenByPlasma_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_StructureSettings_BrokenByPlasma_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_StructureSettings_BrokenByPlasma_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass StructureSettings_BrokenByPlasma.StructureSettings_BrokenByPlasma_C // 0x0000 (0x0050 - 0x0050) class UStructureSettings_BrokenByPlasma_C : public UStructureSettings_BrokenByExplosives_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass StructureSettings_BrokenByPlasma.StructureSettings_BrokenByPlasma_C"); return ptr; } void ExecuteUbergraph_StructureSettings_BrokenByPlasma(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
22.871795
134
0.676009
2bite
1cee6deb9ddf0e9cbdaa8cd033483d87f792e1e0
500
cpp
C++
acmicpc/1946.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/1946.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/1946.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<pair<int, int>> vec; int t, n, a, b; cin >> t; while (t--) { cin >> n; for (int i=0; i<n; ++i) { cin >> a >> b; vec.push_back({a, b}); } sort(vec.begin(), vec.end()); int ans = 1; int prev = vec[0].second; for (int i=1; i<n; ++i) { int cur = vec[i].second; if (prev > cur) { prev = cur; ans++; } } cout << ans << '\n'; vec.clear(); } return 0; }
13.888889
31
0.498
juseongkr
1cf155d7cd0580a126aa817059e5ad5c89fdbcbd
21,127
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimRoot.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimRoot.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimRoot.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimRoot.hxx" namespace schema { namespace simxml { namespace SimModelCore { // SimRoot // const SimRoot::Description_optional& SimRoot:: Description () const { return this->Description_; } SimRoot::Description_optional& SimRoot:: Description () { return this->Description_; } void SimRoot:: Description (const Description_type& x) { this->Description_.set (x); } void SimRoot:: Description (const Description_optional& x) { this->Description_ = x; } void SimRoot:: Description (::std::auto_ptr< Description_type > x) { this->Description_.set (x); } const SimRoot::ObjectOwnerHistory_optional& SimRoot:: ObjectOwnerHistory () const { return this->ObjectOwnerHistory_; } SimRoot::ObjectOwnerHistory_optional& SimRoot:: ObjectOwnerHistory () { return this->ObjectOwnerHistory_; } void SimRoot:: ObjectOwnerHistory (const ObjectOwnerHistory_type& x) { this->ObjectOwnerHistory_.set (x); } void SimRoot:: ObjectOwnerHistory (const ObjectOwnerHistory_optional& x) { this->ObjectOwnerHistory_ = x; } void SimRoot:: ObjectOwnerHistory (::std::auto_ptr< ObjectOwnerHistory_type > x) { this->ObjectOwnerHistory_.set (x); } const SimRoot::IfcGlobalID_optional& SimRoot:: IfcGlobalID () const { return this->IfcGlobalID_; } SimRoot::IfcGlobalID_optional& SimRoot:: IfcGlobalID () { return this->IfcGlobalID_; } void SimRoot:: IfcGlobalID (const IfcGlobalID_type& x) { this->IfcGlobalID_.set (x); } void SimRoot:: IfcGlobalID (const IfcGlobalID_optional& x) { this->IfcGlobalID_ = x; } void SimRoot:: IfcGlobalID (::std::auto_ptr< IfcGlobalID_type > x) { this->IfcGlobalID_.set (x); } const SimRoot::IfcName_optional& SimRoot:: IfcName () const { return this->IfcName_; } SimRoot::IfcName_optional& SimRoot:: IfcName () { return this->IfcName_; } void SimRoot:: IfcName (const IfcName_type& x) { this->IfcName_.set (x); } void SimRoot:: IfcName (const IfcName_optional& x) { this->IfcName_ = x; } void SimRoot:: IfcName (::std::auto_ptr< IfcName_type > x) { this->IfcName_.set (x); } const SimRoot::SimUniqueID_optional& SimRoot:: SimUniqueID () const { return this->SimUniqueID_; } SimRoot::SimUniqueID_optional& SimRoot:: SimUniqueID () { return this->SimUniqueID_; } void SimRoot:: SimUniqueID (const SimUniqueID_type& x) { this->SimUniqueID_.set (x); } void SimRoot:: SimUniqueID (const SimUniqueID_optional& x) { this->SimUniqueID_ = x; } void SimRoot:: SimUniqueID (::std::auto_ptr< SimUniqueID_type > x) { this->SimUniqueID_.set (x); } const SimRoot::SimModelType_optional& SimRoot:: SimModelType () const { return this->SimModelType_; } SimRoot::SimModelType_optional& SimRoot:: SimModelType () { return this->SimModelType_; } void SimRoot:: SimModelType (const SimModelType_type& x) { this->SimModelType_.set (x); } void SimRoot:: SimModelType (const SimModelType_optional& x) { this->SimModelType_ = x; } void SimRoot:: SimModelType (::std::auto_ptr< SimModelType_type > x) { this->SimModelType_.set (x); } const SimRoot::SimModelSubtype_optional& SimRoot:: SimModelSubtype () const { return this->SimModelSubtype_; } SimRoot::SimModelSubtype_optional& SimRoot:: SimModelSubtype () { return this->SimModelSubtype_; } void SimRoot:: SimModelSubtype (const SimModelSubtype_type& x) { this->SimModelSubtype_.set (x); } void SimRoot:: SimModelSubtype (const SimModelSubtype_optional& x) { this->SimModelSubtype_ = x; } void SimRoot:: SimModelSubtype (::std::auto_ptr< SimModelSubtype_type > x) { this->SimModelSubtype_.set (x); } const SimRoot::SimModelName_optional& SimRoot:: SimModelName () const { return this->SimModelName_; } SimRoot::SimModelName_optional& SimRoot:: SimModelName () { return this->SimModelName_; } void SimRoot:: SimModelName (const SimModelName_type& x) { this->SimModelName_.set (x); } void SimRoot:: SimModelName (const SimModelName_optional& x) { this->SimModelName_ = x; } void SimRoot:: SimModelName (::std::auto_ptr< SimModelName_type > x) { this->SimModelName_.set (x); } const SimRoot::SourceModelSchema_optional& SimRoot:: SourceModelSchema () const { return this->SourceModelSchema_; } SimRoot::SourceModelSchema_optional& SimRoot:: SourceModelSchema () { return this->SourceModelSchema_; } void SimRoot:: SourceModelSchema (const SourceModelSchema_type& x) { this->SourceModelSchema_.set (x); } void SimRoot:: SourceModelSchema (const SourceModelSchema_optional& x) { this->SourceModelSchema_ = x; } void SimRoot:: SourceModelSchema (::std::auto_ptr< SourceModelSchema_type > x) { this->SourceModelSchema_.set (x); } const SimRoot::SourceModelObjectType_optional& SimRoot:: SourceModelObjectType () const { return this->SourceModelObjectType_; } SimRoot::SourceModelObjectType_optional& SimRoot:: SourceModelObjectType () { return this->SourceModelObjectType_; } void SimRoot:: SourceModelObjectType (const SourceModelObjectType_type& x) { this->SourceModelObjectType_.set (x); } void SimRoot:: SourceModelObjectType (const SourceModelObjectType_optional& x) { this->SourceModelObjectType_ = x; } void SimRoot:: SourceModelObjectType (::std::auto_ptr< SourceModelObjectType_type > x) { this->SourceModelObjectType_.set (x); } const SimRoot::SourceLibraryEntryID_optional& SimRoot:: SourceLibraryEntryID () const { return this->SourceLibraryEntryID_; } SimRoot::SourceLibraryEntryID_optional& SimRoot:: SourceLibraryEntryID () { return this->SourceLibraryEntryID_; } void SimRoot:: SourceLibraryEntryID (const SourceLibraryEntryID_type& x) { this->SourceLibraryEntryID_.set (x); } void SimRoot:: SourceLibraryEntryID (const SourceLibraryEntryID_optional& x) { this->SourceLibraryEntryID_ = x; } void SimRoot:: SourceLibraryEntryID (::std::auto_ptr< SourceLibraryEntryID_type > x) { this->SourceLibraryEntryID_.set (x); } const SimRoot::SourceLibraryEntryRef_optional& SimRoot:: SourceLibraryEntryRef () const { return this->SourceLibraryEntryRef_; } SimRoot::SourceLibraryEntryRef_optional& SimRoot:: SourceLibraryEntryRef () { return this->SourceLibraryEntryRef_; } void SimRoot:: SourceLibraryEntryRef (const SourceLibraryEntryRef_type& x) { this->SourceLibraryEntryRef_.set (x); } void SimRoot:: SourceLibraryEntryRef (const SourceLibraryEntryRef_optional& x) { this->SourceLibraryEntryRef_ = x; } void SimRoot:: SourceLibraryEntryRef (::std::auto_ptr< SourceLibraryEntryRef_type > x) { this->SourceLibraryEntryRef_.set (x); } //const SimRoot::RefId_type& SimRoot:: const std::string SimRoot:: RefId () const { return this->RefId_.get (); } //SimRoot::RefId_type& SimRoot:: std::string SimRoot:: RefId () { return this->RefId_.get (); } void SimRoot:: RefId (const RefId_type& x) { this->RefId_.set (x); } void SimRoot:: RefId (::std::auto_ptr< RefId_type > x) { this->RefId_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace SimModelCore { // SimRoot // SimRoot:: SimRoot () : ::xml_schema::type (), Description_ (this), ObjectOwnerHistory_ (this), IfcGlobalID_ (this), IfcName_ (this), SimUniqueID_ (this), SimModelType_ (this), SimModelSubtype_ (this), SimModelName_ (this), SourceModelSchema_ (this), SourceModelObjectType_ (this), SourceLibraryEntryID_ (this), SourceLibraryEntryRef_ (this), RefId_ (this) { } SimRoot:: SimRoot (const RefId_type& RefId) : ::xml_schema::type (), Description_ (this), ObjectOwnerHistory_ (this), IfcGlobalID_ (this), IfcName_ (this), SimUniqueID_ (this), SimModelType_ (this), SimModelSubtype_ (this), SimModelName_ (this), SourceModelSchema_ (this), SourceModelObjectType_ (this), SourceLibraryEntryID_ (this), SourceLibraryEntryRef_ (this), RefId_ (RefId, this) { } SimRoot:: SimRoot (const SimRoot& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::xml_schema::type (x, f, c), Description_ (x.Description_, f, this), ObjectOwnerHistory_ (x.ObjectOwnerHistory_, f, this), IfcGlobalID_ (x.IfcGlobalID_, f, this), IfcName_ (x.IfcName_, f, this), SimUniqueID_ (x.SimUniqueID_, f, this), SimModelType_ (x.SimModelType_, f, this), SimModelSubtype_ (x.SimModelSubtype_, f, this), SimModelName_ (x.SimModelName_, f, this), SourceModelSchema_ (x.SourceModelSchema_, f, this), SourceModelObjectType_ (x.SourceModelObjectType_, f, this), SourceLibraryEntryID_ (x.SourceLibraryEntryID_, f, this), SourceLibraryEntryRef_ (x.SourceLibraryEntryRef_, f, this), RefId_ (x.RefId_, f, this) { } SimRoot:: SimRoot (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::xml_schema::type (e, f | ::xml_schema::flags::base, c), Description_ (this), ObjectOwnerHistory_ (this), IfcGlobalID_ (this), IfcName_ (this), SimUniqueID_ (this), SimModelType_ (this), SimModelSubtype_ (this), SimModelName_ (this), SourceModelSchema_ (this), SourceModelObjectType_ (this), SourceLibraryEntryID_ (this), SourceLibraryEntryRef_ (this), RefId_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimRoot:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // Description // if (n.name () == "Description" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< Description_type > r ( Description_traits::create (i, f, this)); if (!this->Description_) { this->Description_.set (r); continue; } } // ObjectOwnerHistory // if (n.name () == "ObjectOwnerHistory" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< ObjectOwnerHistory_type > r ( ObjectOwnerHistory_traits::create (i, f, this)); if (!this->ObjectOwnerHistory_) { this->ObjectOwnerHistory_.set (r); continue; } } // IfcGlobalID // if (n.name () == "IfcGlobalID" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< IfcGlobalID_type > r ( IfcGlobalID_traits::create (i, f, this)); if (!this->IfcGlobalID_) { this->IfcGlobalID_.set (r); continue; } } // IfcName // if (n.name () == "IfcName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< IfcName_type > r ( IfcName_traits::create (i, f, this)); if (!this->IfcName_) { this->IfcName_.set (r); continue; } } // SimUniqueID // if (n.name () == "SimUniqueID" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SimUniqueID_type > r ( SimUniqueID_traits::create (i, f, this)); if (!this->SimUniqueID_) { this->SimUniqueID_.set (r); continue; } } // SimModelType // if (n.name () == "SimModelType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SimModelType_type > r ( SimModelType_traits::create (i, f, this)); if (!this->SimModelType_) { this->SimModelType_.set (r); continue; } } // SimModelSubtype // if (n.name () == "SimModelSubtype" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SimModelSubtype_type > r ( SimModelSubtype_traits::create (i, f, this)); if (!this->SimModelSubtype_) { this->SimModelSubtype_.set (r); continue; } } // SimModelName // if (n.name () == "SimModelName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SimModelName_type > r ( SimModelName_traits::create (i, f, this)); if (!this->SimModelName_) { this->SimModelName_.set (r); continue; } } // SourceModelSchema // if (n.name () == "SourceModelSchema" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SourceModelSchema_type > r ( SourceModelSchema_traits::create (i, f, this)); if (!this->SourceModelSchema_) { this->SourceModelSchema_.set (r); continue; } } // SourceModelObjectType // if (n.name () == "SourceModelObjectType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SourceModelObjectType_type > r ( SourceModelObjectType_traits::create (i, f, this)); if (!this->SourceModelObjectType_) { this->SourceModelObjectType_.set (r); continue; } } // SourceLibraryEntryID // if (n.name () == "SourceLibraryEntryID" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SourceLibraryEntryID_type > r ( SourceLibraryEntryID_traits::create (i, f, this)); if (!this->SourceLibraryEntryID_) { this->SourceLibraryEntryID_.set (r); continue; } } // SourceLibraryEntryRef // if (n.name () == "SourceLibraryEntryRef" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/SimModelCore") { ::std::auto_ptr< SourceLibraryEntryRef_type > r ( SourceLibraryEntryRef_traits::create (i, f, this)); if (!this->SourceLibraryEntryRef_) { this->SourceLibraryEntryRef_.set (r); continue; } } break; } while (p.more_attributes ()) { const ::xercesc::DOMAttr& i (p.next_attribute ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); if (n.name () == "RefId" && n.namespace_ ().empty ()) { this->RefId_.set (RefId_traits::create (i, f, this)); continue; } } if (!RefId_.present ()) { throw ::xsd::cxx::tree::expected_attribute< char > ( "RefId", ""); } } SimRoot* SimRoot:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimRoot (*this, f, c); } SimRoot& SimRoot:: operator= (const SimRoot& x) { if (this != &x) { static_cast< ::xml_schema::type& > (*this) = x; this->Description_ = x.Description_; this->ObjectOwnerHistory_ = x.ObjectOwnerHistory_; this->IfcGlobalID_ = x.IfcGlobalID_; this->IfcName_ = x.IfcName_; this->SimUniqueID_ = x.SimUniqueID_; this->SimModelType_ = x.SimModelType_; this->SimModelSubtype_ = x.SimModelSubtype_; this->SimModelName_ = x.SimModelName_; this->SourceModelSchema_ = x.SourceModelSchema_; this->SourceModelObjectType_ = x.SourceModelObjectType_; this->SourceLibraryEntryID_ = x.SourceLibraryEntryID_; this->SourceLibraryEntryRef_ = x.SourceLibraryEntryRef_; this->RefId_ = x.RefId_; } return *this; } SimRoot:: ~SimRoot () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace SimModelCore { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
26.147277
123
0.558432
EnEff-BIM
1cf2697aa4fa44c82a42f2d8a0aaab20c26c2d3a
10,661
hpp
C++
source/housys/include/hou/sys/pixel.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/housys/include/hou/sys/pixel.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/housys/include/hou/sys/pixel.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_SYS_PIXEL_HPP #define HOU_SYS_PIXEL_HPP #include "hou/sys/color.hpp" #include "hou/sys/pixel_fwd.hpp" #include "hou/sys/sys_config.hpp" #include "hou/cor/pragmas.hpp" #include <array> namespace hou { HOU_PRAGMA_PACK_PUSH(1) /** * Represents a pixel. * * Note: all possible class instances (one for each possible pixel_format value) * are already explicitly instantiated and exported in the library. * * \tparam PF the pixel format. */ template <pixel_format PF> class pixel { public: /** * The pixel format. */ static constexpr pixel_format format = PF; /** * The number of bits in a pixel. */ static constexpr size_t bit_count = get_bits_per_pixel(PF); /** * The number of bytes in a pixel. */ static constexpr size_t byte_count = get_bytes_per_pixel(PF); public: /** * Retrieves the format of the pixel. * * \return the format of the pixel. */ static pixel_format get_format() noexcept; /** * Retrieves the amount of bytes used by the pixel. * * \return the amomunt of bytes used by the pixel. */ static uint get_byte_count() noexcept; public: /** * default constructor. * * Initializes all channels to 0. */ pixel() noexcept; /** * Channel constructor. * * Initializes the pixel with the given channel values. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::r>> pixel(uint8_t r) noexcept; /** * Channel constructor. * * Initializes the pixel with the given channel values. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rg>> pixel(uint8_t r, uint8_t g) noexcept; /** * Channel constructor. * * Initializes the pixel with the given channel values. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. * * \param b the blue channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgb>> pixel(uint8_t r, uint8_t g, uint8_t b) noexcept; /** * Channel constructor. * * Initializes the pixel with the given channel values. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. * * \param b the blue channel value. * * \param a the alpha channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgba>> pixel(uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept; /** * color constructor. * * Initializes the pixel with the given color. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param c the color. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgba>> pixel(const color& c) noexcept; /** * Format conversion constructor. * * Initializes the pixel with the channel values of a pixel with a different * format. * * The following rules are applied: * * * When converting from rg or rgba to r or rgb, the last input channel (the * transparency channel) is ignored. * * * When converting from r or rgb to rg or rgba the last output channel (the * transparency channel) is set to 255. * * * When converting from r or rg to rgb or rgba, the r, g and b output * hannels are set to the value of the r input channel. * * * When converting from rgb or rgba to r or rg, the r output channel * (the value channel) is set to a weighted average of the r, g, and b input * channels: Rout = (77 * Rin + 150 * Gin + 29 * Bin) / 256. * * \tparam otherFormat the other pixel_format. * * \tparam Enable enabling template parameter. * * \param other the other pixel. */ template <pixel_format otherFormat, typename Enable = std::enable_if_t<otherFormat != PF>> pixel(const pixel<otherFormat>& other) noexcept; /** * Retrieves the value of the red channel of the pixel. * * \return the value of the channel. */ uint8_t get_r() const noexcept; /** * Sets the value of the red channel of the pixel. * * \param value the value. */ void set_r(uint8_t value) noexcept; /** * Retrieves the value of the green channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \return the value of the channel. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 1u)>> uint8_t get_g() const noexcept; /** * Sets the value of the green channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param value the value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 1u)>> void set_g(uint8_t value) noexcept; /** * Retrieves the value of the blue channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \return the value of the channel. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 2u)>> uint8_t get_b() const noexcept; /** * Sets the value of the blue channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param value the value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 1u)>> void set_b(uint8_t value) noexcept; /** * Retrieves the value of the alpha channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \return the value of the channel. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 3u)>> uint8_t get_a() const noexcept; /** * Sets the value of the alpha channel of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param value the value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<(get_bytes_per_pixel(PF2) > 1u)>> void set_a(uint8_t value) noexcept; /** * Retrieves the color of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \return the color of the pixel. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgba>> color get_color() const noexcept; /** * Sets the color of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param c the color of the pixel. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgba>> void set_color(const color& c) noexcept; /** * Sets the channels of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::r>> void set(uint8_t r) noexcept; /** * Sets the channels of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rg>> void set(uint8_t r, uint8_t g) noexcept; /** * Sets the channels of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. * * \param b the blue channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgb>> void set(uint8_t r, uint8_t g, uint8_t b) noexcept; /** * Sets the channels of the pixel. * * \tparam PF2 dummy template parameter. * * \tparam Enable enabling template parameter. * * \param r the red channel value. * * \param g the green channel value. * * \param b the blue channel value. * * \param a the alpha channel value. */ template <pixel_format PF2 = PF, typename Enable = std::enable_if_t<PF2 == pixel_format::rgba>> void set(uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept; #ifndef HOU_DOXYGEN public: template <pixel_format PF2> friend constexpr bool operator==( const pixel<PF2>& lhs, const pixel<PF2>& rhs) noexcept; template <pixel_format PF2> friend constexpr bool operator!=( const pixel<PF2>& lhs, const pixel<PF2>& rhs) noexcept; #endif private: std::array<uint8_t, get_bytes_per_pixel(PF)> m_channels; }; HOU_PRAGMA_PACK_POP() /** * Checks if two pixel objects are equal. * * \tparam PF the pixel format. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ template <pixel_format PF> constexpr bool operator==( const pixel<PF>& lhs, const pixel<PF>& rhs) noexcept; /** * Checks if two pixel objects are not equal. * * \tparam PF the pixel format. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ template <pixel_format PF> constexpr bool operator!=( const pixel<PF>& lhs, const pixel<PF>& rhs) noexcept; /** * Writes the object into a stream. * * \tparam PF the pixel format. * * \param os the stream. * * \param pixel the pixel. * * \return a reference to os. */ template <pixel_format PF> std::ostream& operator<<(std::ostream& os, const pixel<PF>& pixel); } // namespace hou #include "hou/sys/pixel.inl" #endif
24.395881
80
0.658381
DavideCorradiDev
1cf3f12450e1339a4385eab14590f24f95726ca8
1,298
cpp
C++
src/CefView/CefBrowserApp/CefViewBrowserClient_KeyboardHandler.cpp
daiming/CefViewCore
89837575e8d5f50aa16a91ef19b0ad7ddbff205e
[ "MIT" ]
null
null
null
src/CefView/CefBrowserApp/CefViewBrowserClient_KeyboardHandler.cpp
daiming/CefViewCore
89837575e8d5f50aa16a91ef19b0ad7ddbff205e
[ "MIT" ]
null
null
null
src/CefView/CefBrowserApp/CefViewBrowserClient_KeyboardHandler.cpp
daiming/CefViewCore
89837575e8d5f50aa16a91ef19b0ad7ddbff205e
[ "MIT" ]
null
null
null
#include <CefViewBrowserClient.h> #pragma region std_headers #include <sstream> #include <string> #include <algorithm> #pragma endregion std_headers #pragma region cef_headers #include <include/cef_app.h> #pragma endregion cef_headers #include <Common/CefViewCoreLog.h> CefRefPtr<CefKeyboardHandler> CefViewBrowserClient::GetKeyboardHandler() { return this; } bool CefViewBrowserClient::OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event, bool* is_keyboard_shortcut) { CEF_REQUIRE_UI_THREAD(); // 增加按键事件,处理F5刷新和F10调用调试工具 // TODO 禁用devtools中的F5和F10响应 if (event.type == KEYEVENT_RAWKEYDOWN) { if (event.windows_key_code == VK_F5) { // 刷新 browser->Reload(); return true; } else if (event.windows_key_code == VK_F10) { // 调试控制台 if (browser->GetHost()->HasDevTools()) { browser->GetHost()->CloseDevTools(); } else { CefWindowInfo windowInfo; #if defined(OS_WIN) windowInfo.SetAsPopup(NULL, "DevTools"); #endif CefBrowserSettings settings; browser->GetHost()->ShowDevTools(windowInfo, this, settings, CefPoint()); } } } return false; }
24.490566
81
0.645609
daiming
1cf4a0b3678f6ac840485a14f35105d2cfcb4e71
702
cpp
C++
Dataset/Leetcode/train/56/22.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/56/22.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/56/22.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> XXX(vector<vector<int>>& intervals) { vector<vector<int>> res; mer(intervals,res); return res; } void mer(vector<vector<int>>& intervals,vector<vector<int>> &res) { int ed = -2e9,st = -2e9; sort(intervals.begin(),intervals.end()); for(int i=0;i<intervals.size();i++) { if(intervals[i][0]>ed) { if(st!=-2e9)res.push_back({st,ed}); st = intervals[i][0]; ed = intervals[i][1]; } else ed = max(intervals[i][1],ed); } if(st!=-2e9)res.push_back({st,ed}); } };
25.071429
69
0.465812
kkcookies99