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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1555c4ca153eb26fdd031e40311cced5b70ceaac | 405 | cpp | C++ | C++/0739-Daily-Temperatures/soln-1.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0739-Daily-Temperatures/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0739-Daily-Temperatures/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> st;
const int n = T.size();
vector<int> ans(n, 0);
for(int i = 0; i < n; ++i) {
while (!st.empty() && T[i] > T[st.top()]) {
ans[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return ans;
}
};
| 23.823529 | 55 | 0.392593 | wyaadarsh |
155fa02032a320e9d3cb6fd3537c6d2d5d9a129f | 11,141 | cc | C++ | algorithms/map-optimization-legacy/src/ba-optimization-options.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 1,936 | 2017-11-27T23:11:37.000Z | 2022-03-30T14:24:14.000Z | algorithms/map-optimization-legacy/src/ba-optimization-options.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 353 | 2017-11-29T18:40:39.000Z | 2022-03-30T15:53:46.000Z | algorithms/map-optimization-legacy/src/ba-optimization-options.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 661 | 2017-11-28T07:20:08.000Z | 2022-03-28T08:06:29.000Z | #include "map-optimization-legacy/ba-optimization-options.h"
#include <glog/logging.h>
#include <maplab-common/conversions.h>
#include <maplab-common/gravity-provider.h>
DEFINE_bool(
lba_fix_ncamera_intrinsics, true,
"Whether or not to fix the intrinsics of the ncamera(s).");
DEFINE_bool(
lba_fix_ncamera_extrinsics_rotation, true,
"Whether or not to fix the rotation extrinsics of the ncamera(s).");
DEFINE_bool(
lba_fix_ncamera_extrinsics_translation, true,
"Whether or not to fix the translation extrinsics of the ncamera(s).");
DEFINE_bool(
lba_fix_landmark_positions, false,
"Whether or not to fix the positions of the landmarks.");
DEFINE_bool(
lba_fix_vertex_poses, false,
"Whether or not to fix the positions of the vertices.");
DEFINE_bool(
lba_fix_accel_bias, false,
"Whether or not to fix the bias of the IMU accelerometer.");
DEFINE_bool(
lba_fix_gyro_bias, false,
"Whether or not to fix the bias of the IMU gyroscope.");
DEFINE_bool(
lba_fix_velocity, false,
"Whether or not to fix the velocity of the vertices.");
DEFINE_bool(
lba_add_pose_prior_for_fixed_vertices, false,
"Whether or not to add a pose prior error-term for all fixed vertices.");
DEFINE_bool(
lba_remove_behind_camera_landmarks, true,
"Whether or not to remove landmarks located behind the camera.");
DEFINE_bool(
lba_fix_landmark_positions_of_fixed_vertices, false,
"Whether or "
"not to fix the positions of landmarks based at fixed vertices.");
DEFINE_bool(
lba_include_wheel_odometry, false,
"Whether or not to include wheel-odometry error-terms.");
DEFINE_bool(
lba_include_gps, false, "Whether or not to include GPS error-terms.");
DEFINE_bool(
lba_position_only_gps, false,
"Whether or not to add GPS error-terms as constraints on the position only "
"(3DoF)or as constrains on both position and orientation (6DoF)");
DEFINE_bool(
lba_include_visual, true, "Whether or not to include visual error-terms.");
DEFINE_bool(
lba_include_inertial, true, "Whether or not to include IMU error-terms.");
DEFINE_bool(
lba_fix_wheel_odometry_extrinsics, true,
"Whether or not to fix the extrinsics of the wheel-odometry.");
DEFINE_bool(
lba_visual_outlier_rejection, false,
"If visual outlier rejection "
"should be done in the bundle adjustment.");
DEFINE_bool(
lba_run_custom_post_iteration_callback_on_vi_map, true,
"Whether or not to run a user-defined callback on the VIMap after "
"every optimization iteration.");
DEFINE_bool(lba_show_residual_statistics, false, "Show residual statistics.");
DEFINE_bool(
lba_apply_loss_function_for_residual_stats, false,
"Apply loss function on residuals for the statistics.");
DEFINE_int32(
lba_min_num_visible_landmarks_at_vertex, 5,
"Minimum number of "
"landmarks visible at a vertex for it to be added to the problem.");
DEFINE_int32(
lba_update_visualization_every_n_iterations, 10,
"Update the visualization every n optimization iterations.");
DEFINE_int32(
lba_num_visual_outlier_rejection_loops, 2,
"Number of bundle_adjustment visual outlier rejection loops.");
DEFINE_int32(
lba_min_number_of_landmark_observer_missions, 0,
"Minimum number of "
"missions a landmark must be observed from to have its respective "
"visual error-terms included.");
DEFINE_int32(
lba_num_iterations, 50,
"Maximum number of optimization iterations to perform.");
DEFINE_string(
lba_fix_vertex_poses_except_of_mission, "",
"Fixes all vertex "
"poses except the vertex poses of the mission with the specified "
"id.");
DEFINE_double(
lba_prior_position_std_dev_meters, 0.0316227766,
"Std. dev. in meters used for position priors. Default: sqrt(0.001)");
DEFINE_double(
lba_prior_orientation_std_dev_radians, 0.00174533,
"Std. dev. in radians (default"
" corresponds to 0.1deg.) used for orientation priors.");
DEFINE_double(
lba_prior_velocity_std_dev_meters_seconds, 0.1,
"Std. dev. in meters per second used "
"for priors on velocities.");
DEFINE_double(
lba_gravity_magnitude_meters_seconds_square, -1.0,
"Gravity magnitude in meters per "
"square seconds. If < 0.0, the GravityProvider is used to set "
"the gravity magnitude.");
DEFINE_bool(
lba_add_pose_prior_on_camera_extrinsics, false,
"Adding a prior on the pose of the camera extrinsics.");
DEFINE_double(
lba_camera_extrinsics_position_prior_std_dev_meters, 1.0,
"Std. dev. of the position prior on the camera extrinsics pose [meters].");
DEFINE_double(
lba_camera_extrinsics_orientation_prior_std_dev_degrees, 1.0,
"Std. dev. of the orientation prior on the camera extrinsics pose "
"[meters].");
DEFINE_bool(
lba_add_pose_prior_on_wheel_odometry_extrinsics, false,
"Adding a prior on the pose of the wheel odometry extrinsics.");
DEFINE_double(
lba_wheel_odometry_extrinsics_position_prior_std_dev_meters, 1.0,
"Std. dev. of the position prior on the wheel odometry extrinsics pose "
"[meters].");
DEFINE_double(
lba_wheel_odometry_extrinsics_orientation_prior_std_dev_degrees, 1.0,
"Std. dev. of the orientation prior on the wheel odometry extrinsics pose "
"[meters].");
DEFINE_bool(
lba_fix_wheel_odometry_extrinsics_position, false,
"Fix the position of the wheel odometry extrinsics.");
DEFINE_bool(
lba_include_only_merged_landmarks, false,
"If true, only landmarks with at least two "
"global landmark IDs are included in the optimization.");
DEFINE_bool(
lba_fix_root_vertex, true,
"Fix the root vertex of one of the "
"missions for optimization.");
DEFINE_bool(lba_fix_baseframes, false, "Fix the baseframe transformations.");
DEFINE_bool(
lba_include_loop_closure_edges, false,
"Whether or not to include the loop-closure transformation error "
"terms.");
DEFINE_bool(
lba_use_switchable_constraints_for_loop_closure_edges, true,
"If true, the optimizer may dynamically downweight loop-closure "
"error-terms that are considered outliers by adjusting the switch "
"variable of the error-term.");
DEFINE_double(
lba_loop_closure_error_term_cauchy_loss, 10.0,
"Cauchy loss parameter for the loop-closure error-terms. Note that the "
"Cauchy loss is only used if the parameter is > 0 and the switch "
"variable is not used.");
namespace map_optimization_legacy {
BaOptimizationOptions::BaOptimizationOptions()
: fix_not_selected_missions(false),
fix_ncamera_intrinsics(FLAGS_lba_fix_ncamera_intrinsics),
fix_ncamera_extrinsics_rotation(
FLAGS_lba_fix_ncamera_extrinsics_rotation),
fix_ncamera_extrinsics_translation(
FLAGS_lba_fix_ncamera_extrinsics_translation),
fix_landmark_positions(FLAGS_lba_fix_landmark_positions),
fix_vertex_poses(FLAGS_lba_fix_vertex_poses),
fix_accel_bias(FLAGS_lba_fix_accel_bias),
fix_gyro_bias(FLAGS_lba_fix_gyro_bias),
fix_velocity(FLAGS_lba_fix_velocity),
add_pose_prior_for_fixed_vertices(
FLAGS_lba_add_pose_prior_for_fixed_vertices),
remove_behind_camera_landmarks(FLAGS_lba_remove_behind_camera_landmarks),
fix_landmark_positions_of_fixed_vertices(
FLAGS_lba_fix_landmark_positions_of_fixed_vertices),
include_wheel_odometry(FLAGS_lba_include_wheel_odometry),
include_gps(FLAGS_lba_include_gps),
position_only_gps(FLAGS_lba_position_only_gps),
include_visual(FLAGS_lba_include_visual),
include_inertial(FLAGS_lba_include_inertial),
include_only_merged_landmarks(FLAGS_lba_include_only_merged_landmarks),
fix_wheel_odometry_extrinsics(FLAGS_lba_fix_wheel_odometry_extrinsics),
fix_root_vertex(FLAGS_lba_fix_root_vertex),
fix_baseframes(FLAGS_lba_fix_baseframes),
visual_outlier_rejection(FLAGS_lba_visual_outlier_rejection),
run_custom_post_iteration_callback_on_vi_map(
FLAGS_lba_run_custom_post_iteration_callback_on_vi_map),
min_number_of_visible_landmarks_at_vertex(
static_cast<size_t>(FLAGS_lba_min_num_visible_landmarks_at_vertex)),
num_visual_outlier_rejection_loops(
static_cast<size_t>(FLAGS_lba_num_visual_outlier_rejection_loops)),
min_number_of_landmark_observer_missions(
static_cast<size_t>(
FLAGS_lba_min_number_of_landmark_observer_missions)),
num_iterations(static_cast<size_t>(FLAGS_lba_num_iterations)),
fix_vertex_poses_except_of_mission(
FLAGS_lba_fix_vertex_poses_except_of_mission),
prior_position_std_dev_meters(FLAGS_lba_prior_position_std_dev_meters),
prior_orientation_std_dev_radians(
FLAGS_lba_prior_orientation_std_dev_radians),
prior_velocity_std_dev_meter_seconds(
FLAGS_lba_prior_velocity_std_dev_meters_seconds),
gravity_magnitude(FLAGS_lba_gravity_magnitude_meters_seconds_square),
add_pose_prior_on_camera_extrinsics(
FLAGS_lba_add_pose_prior_on_camera_extrinsics),
camera_extrinsics_position_prior_std_dev_meters(
FLAGS_lba_camera_extrinsics_position_prior_std_dev_meters),
camera_extrinsics_orientation_prior_std_dev_radians(
kDegToRad *
FLAGS_lba_camera_extrinsics_orientation_prior_std_dev_degrees),
add_pose_prior_on_wheel_odometry_extrinsics(
FLAGS_lba_add_pose_prior_on_wheel_odometry_extrinsics),
wheel_odometry_extrinsics_position_prior_std_dev_meters(
FLAGS_lba_wheel_odometry_extrinsics_position_prior_std_dev_meters),
wheel_odometry_extrinsics_orientation_prior_std_dev_radians(
kDegToRad *
FLAGS_lba_wheel_odometry_extrinsics_orientation_prior_std_dev_degrees),
fix_wheel_odometry_extrinsics_position(
FLAGS_lba_fix_wheel_odometry_extrinsics_position),
include_loop_closure_edges(FLAGS_lba_include_loop_closure_edges),
use_switchable_constraints_for_loop_closure_edges(
FLAGS_lba_use_switchable_constraints_for_loop_closure_edges),
loop_closure_error_term_cauchy_loss(
FLAGS_lba_loop_closure_error_term_cauchy_loss) {
CHECK_GE(FLAGS_lba_min_num_visible_landmarks_at_vertex, 0);
CHECK_GE(FLAGS_lba_update_visualization_every_n_iterations, 0);
CHECK_GE(FLAGS_lba_num_visual_outlier_rejection_loops, 0);
CHECK_GE(FLAGS_lba_min_number_of_landmark_observer_missions, 0);
CHECK_GE(FLAGS_lba_num_iterations, 0);
if (gravity_magnitude < 0.0) {
common::GravityProvider gravity_provider(
common::locations::kAltitudeZurichMeters,
common::locations::kLatitudeZurichDegrees);
gravity_magnitude = gravity_provider.getGravityMagnitude();
}
}
BaIterationOptions::BaIterationOptions()
: update_visualization_every_n_iterations(
static_cast<size_t>(
FLAGS_lba_update_visualization_every_n_iterations)),
show_residual_statistics(FLAGS_lba_show_residual_statistics),
apply_loss_function_for_residual_stats(
FLAGS_lba_apply_loss_function_for_residual_stats) {}
} // namespace map_optimization_legacy
| 45.105263 | 81 | 0.776322 | AdronTech |
1560bcd78ff0db310f8831074b2a41881b309ed0 | 991 | hpp | C++ | CaWE/GuiEditor/Commands/Create.hpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/GuiEditor/Commands/Create.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/GuiEditor/Commands/Create.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#ifndef CAFU_GUIEDITOR_COMMAND_CREATE_HPP_INCLUDED
#define CAFU_GUIEDITOR_COMMAND_CREATE_HPP_INCLUDED
#include "../../CommandPattern.hpp"
#include "Templates/Pointer.hpp"
namespace cf { namespace GuiSys { class WindowT; } }
namespace GuiEditor
{
class GuiDocumentT;
class CommandCreateT : public CommandT
{
public:
CommandCreateT(GuiDocumentT* GuiDocument, IntrusivePtrT<cf::GuiSys::WindowT> Parent);
// CommandT implementation.
bool Do();
void Undo();
wxString GetName() const;
private:
GuiDocumentT* m_GuiDocument;
IntrusivePtrT<cf::GuiSys::WindowT> m_Parent;
IntrusivePtrT<cf::GuiSys::WindowT> m_NewWindow;
const ArrayT< IntrusivePtrT<cf::GuiSys::WindowT> > m_OldSelection;
};
}
#endif
| 22.522727 | 93 | 0.67003 | dns |
15656440d6137938d28333ca28fd96f233563a26 | 650 | cpp | C++ | src/base/ev_base.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | 6 | 2018-07-28T08:03:24.000Z | 2022-03-31T08:56:57.000Z | src/base/ev_base.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | null | null | null | src/base/ev_base.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | 2 | 2019-05-21T02:26:36.000Z | 2020-04-13T16:46:20.000Z | /**
* Created by Jian Chen
* @since 2017.02.03
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#include "socket/base/ev_base.hpp"
// -----------------------------------------------------------------------------
// ev_base
const int chen::ev_base::Readable = 1 << 0;
const int chen::ev_base::Writable = 1 << 1;
const int chen::ev_base::Closed = 1 << 2;
void chen::ev_base::onAttach(reactor *loop, int mode, int flag)
{
this->_ev_loop = loop;
this->_ev_mode = mode;
this->_ev_flag = flag;
}
void chen::ev_base::onDetach()
{
this->_ev_loop = nullptr;
this->_ev_mode = 0;
this->_ev_flag = 0;
} | 24.074074 | 80 | 0.556923 | chensoft |
15661111768fbcc964ff4b3df494d70d7904a1d5 | 340 | cpp | C++ | 789.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 789.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 789.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {
int dist = abs(target[0]) + abs(target[1]);
for(int i = 0; i < ghosts.size(); i++){
if (dist >= abs(ghosts[i][0] - target[0]) + abs(ghosts[i][1] - target[1])) return false;
}
return true;
}
};
| 30.909091 | 100 | 0.532353 | zfang399 |
15663e00dc713f393337aa82e12adf2e2ad249e2 | 8,070 | cpp | C++ | dataAQ.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | dataAQ.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | dataAQ.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | #include "dataAQ.h"
#include "demogData.h"
#include "comboDemogData.h"
#include "comboHospitalData.h"
#include "countyDemogData.h"
#include "comboHospitalData.h"
#include "hospitalData.h"
#include "cityHospitalData.h"
#include "parse.h"
#include <iostream>
#include <algorithm>
#include <fstream>
#include <sstream>
#define DEBUG false
using namespace std;
/*
Questions:
What's the deal with region? Why do we need it? Is there a special input for region/county in parse?
What is up with countyDemogData and cityHospitalData?
How are we supposed to store our data in the maps? By region or state? How do we store the data in comboHospData?
*/
//function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map
void dataAQ::createStateDemogData(vector< shared_ptr<demogData> > theData) {
string state = "";
for (shared_ptr<demogData> county : theData) {
state = county->getState();
//if true, key is not found
if (allStateDemogData.count(state) == 0) {
allStateDemogData.insert(make_pair(state, make_shared<comboDemogData>(state, state))); //state and region names are the same
}
allStateDemogData.at(state)->addDemogtoRegion(county);
}
}
void dataAQ::createStateHospData(std::vector<shared_ptr<hospitalData> > theData) {
string state = "";
for (shared_ptr<hospitalData> hosp : theData) {
state = hosp->getState();
//if true, key is not found
if (allStateHospData.count(state) == 0) {
allStateHospData.insert(make_pair(state, make_shared<comboHospitalData>("state", state))); //state and region names are the same
}
allStateHospData.at(state)->addHospitaltoRegion(hosp);
}
}
void dataAQ::createCountyHospData(std::vector<shared_ptr<hospitalData>>& theHospitalData) {
string cityKey = "";
string county = "";
string state = "";
for (shared_ptr<hospitalData> hosp : theHospitalData) {
state = hosp->getState();
cityKey = hosp->getCity() + state;
county = cityToCounty[cityKey];
county += " County"; //added cause the tester tests for the exytra "County"
//if true, key is not found
if (allCountyHData.count(county) == 0) {
allCountyHData.insert(make_pair(county, make_shared<comboHospitalData>(county, state)));
}
allCountyHData.at(county)->addHospitaltoRegion(hosp);
}
}
void dataAQ::sortHospRatingHighLow(vector<comboHospitalData*>& hospHighToLow, string regionType) {
//adding elements from the hashmap to the vector
for (map<string, shared_ptr<comboHospitalData>>::iterator i = allStateHospData.begin(); i != allStateHospData.end(); i++) {
hospHighToLow.push_back(&(*i->second));
}
sort(hospHighToLow.begin(), hospHighToLow.end(), &hospitalData::compareOV);
//reverse
reverse(hospHighToLow.begin(), hospHighToLow.end());
}
void dataAQ::sortHospRatingLowHigh(vector<comboHospitalData*>& hospLowToHigh, string regionType) {
for (map<string, shared_ptr<comboHospitalData>>::iterator i = allStateHospData.begin(); i != allStateHospData.end(); i++) {
hospLowToHigh.push_back(&(*i->second));
}
sort(hospLowToHigh.begin(), hospLowToHigh.end(), &hospitalData::compareOV);
}
void dataAQ::sortDemogPovLevelLowHigh(vector<demogData*>& povLevelLowHigh) {
for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) {
povLevelLowHigh.push_back(&(*i->second));
}
sort(povLevelLowHigh.begin(), povLevelLowHigh.end(), &demogData::compareP);
reverse(povLevelLowHigh.begin(), povLevelLowHigh.end());
}
void dataAQ::sortDemogPovLevelHighLow(vector<demogData*>& povLevelHighLow) {
for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) {
povLevelHighLow.push_back(&(*i->second));
}
sort(povLevelHighLow.begin(), povLevelHighLow.end(), &demogData::compareP);
}
//sorting counties
void dataAQ::sortHospRatingHighLowForState(vector<comboHospitalData*>& hospHighToLow, string state) {
for (map<string, shared_ptr<comboHospitalData>>::iterator i = allCountyHData.begin(); i != allCountyHData.end(); i++) {
if(i->second->getState().compare(state) == 0)
hospHighToLow.push_back(&(*i->second));
}
sort(hospHighToLow.begin(), hospHighToLow.end(), &hospitalData::compareOV);
reverse(hospHighToLow.begin(), hospHighToLow.end());
}
//prints every state with a poverty level above the threshold
void dataAQ::stateReport(double thresh) {
visitorReport VR;
int total = 0;
for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) {
cout << endl;
if (i->second->getBelowPoverty() / i->second->getTotalPop() > thresh / 100) {
cout << "Special report demog Data : \n";
allStateDemogData[i->first]->accept(VR);
cout << "Special report hospital data : \n";
allStateHospData[i->first]->accept(VR);
total++;
}
}
cout << "Generated a report for a total of : " << total << "\n";
//Expected: \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% Bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nGenerated a report for a total of : 1\n
//aActual : \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nGenerated a report for a total of : 1'
//Expected: \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% Bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nSpecial report demog Data : \nDemographics Info(State) : NM\nEducation info : \n(% Bachelor degree or more) : 25.58\n(% high school or more) : 83.39\n % below poverty : 20.40\nSpecial report hospital data : \nHospital Info : NM\nOverall rating(out of 5) : 2.73\nGenerated a report for a total of : 2\n
//Actusal : \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nSpecial report demog Data : \nDemographics Info(State) : NM\nEducation info : \n(% bachelor degree or more) : 25.58\n(% high school or more) : 83.39\n % below poverty : 20.40\nSpecial report hospital data : \nHospital Info : NM\nOverall rating(out of 5) : 2.73\nGenerated a report for a total of : 2
}
ostream& operator<<(ostream &out, const dataAQ &AQ) {
out << "bruh";
return out;
}
void dataAQ::read_csvCityCounty(string filename) {
// Create an input filestream
ifstream myFile(filename);
// Make sure the file is open
if (!myFile.is_open()) {
throw std::runtime_error("Could not open file");
}
if (myFile.good()) {
consumeColumnNames(myFile);
// Helper vars
string line, state, junk;
// Now read data, line by line and enter into the map
while (getline(myFile, line)) {
stringstream ss(line);
string city = getFieldNQ(ss);
state = getFieldNQ(ss);
junk = getFieldNQ(ss);
string county = getFieldNQ(ss);
string cityKey = city + state;
cityToCounty[cityKey] = county;
//cout << "line: " << line << endl;
//cout << "pair (city, county): " << city << ", " << county << " state " << junk << endl;
}
// Close file
myFile.close();
}
}
| 48.035714 | 577 | 0.669145 | LearnerDroid |
d080fb1b4f64a31c0d6a70bea15bfeba622e8b51 | 1,057 | cpp | C++ | sources/Emulator.cpp | NiwakaDev/NIWAKA_X86 | ae07dcd5e006c6b48459c18efd4a65e4492ce7b4 | [
"MIT"
] | 2 | 2022-02-19T04:57:16.000Z | 2022-02-19T05:45:39.000Z | sources/Emulator.cpp | NiwakaDev/NIWAKA_X86 | ae07dcd5e006c6b48459c18efd4a65e4492ce7b4 | [
"MIT"
] | 1 | 2022-02-19T04:59:05.000Z | 2022-02-19T11:02:17.000Z | sources/Emulator.cpp | NiwakaDev/NIWAKA_X86 | ae07dcd5e006c6b48459c18efd4a65e4492ce7b4 | [
"MIT"
] | null | null | null | #include "Memory.h"
#include "Cpu.h"
#include "IoManager.h"
#include "Bios.h"
#include "IntHandler.h"
#include "Device.h"
#include "Pic.h"
#include "Emulator.h"
Emulator::Emulator(Memory* memory, Bios* bios, Cpu* cpu, IoManager* io_manager){
this->mem = memory;
this->bios = bios;
this->cpu = cpu;
this->io_manager = io_manager;
this->int_handler = new IntHandler(cpu, (Pic*)this->io_manager->device_list[PIC]);
this->emu_thread = new thread(&Emulator::Run, this);
//this->Run();
}
void Emulator::ShowSelf(){
cout << "Emulator Info" << endl;
this->bios->ShowSelf();
this->mem->PrintMem(0x7c00, 512);
this->mem->ShowSelf();
}
void Emulator::Run(){
this->bios->LoadIpl(this->mem);
int irq_num;
while(1){
if(this->cpu->IsIF()){
if((irq_num=this->io_manager->device_list[PIC]->IsIrq())!=-1){
this->int_handler->Handle(irq_num);
}
}
this->cpu->ExecuteSelf();
}
this->ShowSelf();
fprintf(stdout, "stopped at Emulator::Run\n");
} | 26.425 | 86 | 0.601703 | NiwakaDev |
d081f38d1e67e302c5b176c3b84bb67b317e771e | 3,049 | cc | C++ | src/nodal_properties.cc | andrewsolis/mpm | c6ea73d3bac177a440f0aa0a5e66829c294a00e5 | [
"MIT"
] | 154 | 2017-11-29T06:41:18.000Z | 2022-03-09T23:19:05.000Z | src/nodal_properties.cc | andrewsolis/mpm | c6ea73d3bac177a440f0aa0a5e66829c294a00e5 | [
"MIT"
] | 707 | 2017-08-30T16:12:59.000Z | 2022-02-25T20:33:02.000Z | src/nodal_properties.cc | andrewsolis/mpm | c6ea73d3bac177a440f0aa0a5e66829c294a00e5 | [
"MIT"
] | 83 | 2017-11-22T15:22:07.000Z | 2022-03-19T17:02:51.000Z | #include "nodal_properties.h"
// Function to create new property with given name and size (rows x cols)
bool mpm::NodalProperties::create_property(const std::string& property,
unsigned rows, unsigned columns) {
// Create a matrix with size of rows times columns and insert it to the
// property database map
Eigen::MatrixXd property_data = Eigen::MatrixXd::Zero(rows, columns);
std::pair<std::map<std::string, Eigen::MatrixXd>::iterator, bool> status =
properties_.insert(
std::pair<std::string, Eigen::MatrixXd>(property, property_data));
return status.second;
}
// Return data in the nodal properties map at a specific index
Eigen::MatrixXd mpm::NodalProperties::property(const std::string& property,
unsigned node_id,
unsigned mat_id,
unsigned nprops) const {
// Const pointer to location of property: node_id * nprops x mat_id
const double* position = &properties_.at(property)(node_id * nprops, mat_id);
mpm::MapProperty property_handle(position, nprops);
return property_handle;
}
// Assign property value to a pair of node and material
void mpm::NodalProperties::assign_property(
const std::string& property, unsigned node_id, unsigned mat_id,
const Eigen::MatrixXd& property_value, unsigned nprops) {
// Assign a property value matrix to its proper location in the properties_
// matrix that stores all nodal properties
properties_.at(property).block(node_id * nprops, mat_id,
property_value.rows(), property_value.cols()) =
property_value;
}
// Update property value according to a pair of node and material
void mpm::NodalProperties::update_property(
const std::string& property, unsigned node_id, unsigned mat_id,
const Eigen::MatrixXd& property_value, unsigned nprops) {
// Update a property value matrix with dimensions nprops x 1 considering its
// proper location in the properties_ matrix that stores all nodal properties
properties_.at(property).block(node_id * nprops, mat_id, nprops, 1) =
property_value + this->property(property, node_id, mat_id, nprops);
}
// Initialise all the nodal values for all properties in the property pool
void mpm::NodalProperties::initialise_nodal_properties() {
// Iterate over all properties in the property map
for (auto prop_itr = properties_.begin(); prop_itr != properties_.end();
++prop_itr) {
// Create Matrix with zero values that has same size of the current property
// in the iteration. The referred size is equal to rows * cols, where:
// rows = number of nodes * size of property (1 if property is scalar, Tdim
// if property is vector)
// cols = number of materials
Eigen::MatrixXd zeroed_property =
Eigen::MatrixXd::Zero(prop_itr->second.rows(), prop_itr->second.cols());
this->assign_property(prop_itr->first, 0, 0, zeroed_property);
}
}
| 49.177419 | 80 | 0.686783 | andrewsolis |
d084bc1c05e1bc0f984e99276c75a9657d0fee3a | 11,365 | cpp | C++ | paint_board.cpp | sakky016/PaintBoardWithUndo | 339cf6204e36252a6974181f14ce099f6f3fbb88 | [
"Apache-2.0"
] | null | null | null | paint_board.cpp | sakky016/PaintBoardWithUndo | 339cf6204e36252a6974181f14ce099f6f3fbb88 | [
"Apache-2.0"
] | null | null | null | paint_board.cpp | sakky016/PaintBoardWithUndo | 339cf6204e36252a6974181f14ce099f6f3fbb88 | [
"Apache-2.0"
] | null | null | null | #include<conio.h>
#include"paint_board.h"
#include<iostream>
//----------------------------------------------------------------------------------------------
// @name : PaintBoard
//
// @description : Constructor
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
PaintBoard::PaintBoard(int width, int height)
{
m_width = width;
m_height = height;
m_cursorX = 0;
m_cursorY = 0;
m_nextCommand = CMD_NONE;
MakeSnapshot();
}
//----------------------------------------------------------------------------------------------
// @name : ~PaintBoard
//
// @description : Destructor
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
PaintBoard::~PaintBoard()
{
}
//----------------------------------------------------------------------------------------------
// @name : DisplayInstructions
//
// @description : Display instructions on screen
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::DisplayInstructions()
{
printf("arrow keys : To move UP, DOWN, LEFT, RIGHT\n");
printf("<space> : Toggles paint on current co-ordinate\n");
printf("u : Undo\n");
printf("x : Terminate\n");
}
//----------------------------------------------------------------------------------------------
// @name : DrawBoard
//
// @description : Creates the drawing board in the form of a matrix. The
// symbol to be displayed at each coordinate depends upon
// cursor location, blank space and painted area.
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::DrawBoard()
{
// Clear the screen
system("cls");
// Print the board
for (int i = 0; i < m_height; i++)
{
for (int j = 0; j < m_width; j++)
{
int index = j * m_height + i;
if (i == m_cursorY && j == m_cursorX &&
m_paintedArea[index] == true)
{
cout << PAINTED_CURSOR;
}
else if (i == m_cursorY && j == m_cursorX)
{
cout << CURSOR;
}
else if (m_paintedArea[index] == true)
{
cout << PAINTED;
}
else
{
cout << BLANK;
}
}
// End of a row
cout << endl;
}
// Display other info
printf("\nx,y (%d, %d)\n", m_cursorX, m_cursorY);
printf("Undo marks: %ld\n", m_paintedAreaSnapshots.size());
DisplayInstructions();
}
//----------------------------------------------------------------------------------------------
// @name : MoveLeft
//
// @description : Move cursor to left
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
bool PaintBoard::MoveLeft()
{
if (m_cursorX > 0)
{
m_cursorX--;
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------
// @name : MoveRight
//
// @description : Move cursor to right
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
bool PaintBoard::MoveRight()
{
if (m_cursorX < m_width - 1)
{
m_cursorX++;
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------
// @name : MoveUp
//
// @description : Move cursor up
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
bool PaintBoard::MoveUp()
{
if (m_cursorY > 0)
{
m_cursorY--;
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------
// @name : MoveDown
//
// @description : Move cursor down
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
bool PaintBoard::MoveDown()
{
if (m_cursorY < m_height - 1)
{
m_cursorY++;
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------
// @name : FetchInput
//
// @description : Waits for fetching user input. Translates the given input
// to a command and stores it. 2 types of inputs are processed
// here. ch1 is the 1st character that user enters. This is
// the input that he is feeding. But in case of arrow keys,
// a sequence of 2 characters are received ch1 and ch2. ch1
// identifies that some arrow key was pressed, ch2 determines the
// specific arrow key pressed.
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::FetchInput()
{
unsigned char ch1 = _getch();
if (ch1 == KEY_ARROW_CHAR1)
{
// Some Arrow key was pressed, determine which?
unsigned char ch2 = _getch();
switch (ch2)
{
case KEY_ARROW_UP:
// code for arrow up
m_nextCommand = CMD_MOVE_UP;
cout << "KEY_ARROW_UP" << endl;
break;
case KEY_ARROW_DOWN:
// code for arrow down
m_nextCommand = CMD_MOVE_DOWN;
cout << "KEY_ARROW_DOWN" << endl;
break;
case KEY_ARROW_LEFT:
// code for arrow right
m_nextCommand = CMD_MOVE_LEFT;
cout << "KEY_ARROW_LEFT" << endl;
break;
case KEY_ARROW_RIGHT:
// code for arrow left
m_nextCommand = CMD_MOVE_RIGHT;
cout << "KEY_ARROW_RIGHT" << endl;
break;
}
}
else
{
switch (ch1)
{
case KEY_SPACE:
// Paint
m_nextCommand = CMD_PAINT;
cout << "KEY_SPACE" << endl;
break;
case KEY_STOP:
// Stop
m_nextCommand = CMD_STOP;
cout << "KEY_STOP" << endl;
break;
case KEY_UNDO:
// Undo
m_nextCommand = CMD_UNDO;
cout << "KEY_UNDO" << endl;
break;
}
}
}
//----------------------------------------------------------------------------------------------
// @name : Process
//
// @description : Depending on the command present in m_nextCommand variable,
// function is executed
//
// @returns : True, if processing is complete, i.e, user pressed terminate
// button.
// False, if application continues.
//----------------------------------------------------------------------------------------------
bool PaintBoard::Process()
{
if (m_nextCommand != CMD_NONE)
{
switch (m_nextCommand)
{
case CMD_MOVE_UP:
MoveUp();
break;
case CMD_MOVE_DOWN:
MoveDown();
break;
case CMD_MOVE_LEFT:
MoveLeft();
break;
case CMD_MOVE_RIGHT:
MoveRight();
break;
case CMD_PAINT:
PaintAtXY(m_cursorX, m_cursorY);
break;
case CMD_UNDO:
Restore();
break;
case CMD_STOP:
// Processing done. Indicate the calling function
return true;
}
m_nextCommand = CMD_NONE;
}
return false;
}
//----------------------------------------------------------------------------------------------
// @name : PaintAtXY
//
// @description : Stores the location of the painted (PAINTED) character.
// Additionally, it creates a snapshot of the current painted
// area of this board. This will later be used for undo operation.
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::PaintAtXY(int x, int y)
{
int index = x * m_height + y;
if (m_paintedArea[index] == true)
{
m_paintedArea[index] = false;
}
else
{
m_paintedArea[index] = true;
}
MakeSnapshot();
}
//----------------------------------------------------------------------------------------------
// @name : MakeSnapshot
//
// @description : Creates a snapshot of the painted area and stores it in
// a list. This list cannot grow beyond MAX_UNDO marks.
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::MakeSnapshot()
{
if (m_paintedAreaSnapshots.size() >= MAX_UNDO)
{
m_paintedAreaSnapshots.pop_front();
}
m_paintedAreaSnapshots.push_back(m_paintedArea);
}
//----------------------------------------------------------------------------------------------
// @name : Restore
//
// @description : Restores the painted area information as per the previous
// undo mark.
//
// @returns : Nothing
//----------------------------------------------------------------------------------------------
void PaintBoard::Restore()
{
// This reverts the current painted area, because after a paint operation
// current painted area and the latest snapshot in the m_paintedAreaSnapshots
// are basically same.
if (m_paintedAreaSnapshots.size())
{
m_paintedArea = m_paintedAreaSnapshots.back();
m_paintedAreaSnapshots.pop_back();
}
// This reverts to the previous painted area.
if (m_paintedAreaSnapshots.size())
{
m_paintedArea = m_paintedAreaSnapshots.back();
m_paintedAreaSnapshots.pop_back();
}
// Once we revert, we need to create a snapshot of this
// operation as well.
MakeSnapshot();
} | 32.195467 | 101 | 0.368676 | sakky016 |
d0851bc25b62c5768475da587a815d827f138170 | 9,540 | cpp | C++ | benchmark_apps/elmerfem/ElmerGUI/Application/twod/twodview.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | elmerfem/ElmerGUI/Application/twod/twodview.cpp | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | null | null | null | elmerfem/ElmerGUI/Application/twod/twodview.cpp | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | 2 | 2021-08-02T23:23:40.000Z | 2022-02-26T12:39:30.000Z | /*****************************************************************************
* *
* Elmer, A Finite Element Software for Multiphysical Problems *
* *
* Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland *
* *
* 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 (in file fem/GPL-2); if not, write to the *
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301, USA. *
* *
*****************************************************************************/
/*****************************************************************************
* *
* ElmerGUI TwodView *
* *
*****************************************************************************
* *
* Authors: Mikko Lyly, Juha Ruokolainen and Peter Råback *
* Email: Juha.Ruokolainen@csc.fi *
* Web: http://www.csc.fi/elmer *
* Address: CSC - IT Center for Science Ltd. *
* Keilaranta 14 *
* 02101 Espoo, Finland *
* *
* Original Date: 15 Mar 2008 *
* *
*****************************************************************************/
#include <QAction>
#include <QIcon>
#include <QMenu>
#include <QMenuBar>
#include <QStatusBar>
#include <QFileDialog>
#include <QMessageBox>
#include <QDockWidget>
#include <iostream>
#include "twodview.h"
#include "renderarea.h"
#include "curveeditor.h"
using namespace std;
TwodView::TwodView(QWidget *parent)
: QMainWindow(parent)
{
renderArea = new RenderArea(this);
setCentralWidget(renderArea);
connect(renderArea, SIGNAL(statusMessage(QString)), this, SLOT(statusMessage(QString)));
curveEditor = new CurveEditor;
connect(curveEditor, SIGNAL(statusMessage(QString)), this, SLOT(statusMessage(QString)));
QDockWidget *dockWidget = new QDockWidget("Editor", this);
dockWidget->setAllowedAreas(Qt::RightDockWidgetArea);
dockWidget->setWidget(curveEditor);
addDockWidget(Qt::RightDockWidgetArea, dockWidget);
renderArea->setCurveEditor(curveEditor);
curveEditor->setRenderArea(renderArea);
createActions();
createMenus();
createStatusBar();
setWindowTitle("ElmerGUI 2D modeler (experimental)");
setWindowIcon(QIcon(":/icons/Mesh3D.png"));
resize(620, 400);
}
TwodView::~TwodView()
{
}
void TwodView::createActions()
{
openAction = new QAction(QIcon(""), tr("&Open..."), this);
openAction->setShortcut(tr("Ctrl+O"));
connect(openAction, SIGNAL(triggered()), this, SLOT(openSlot()));
saveAction = new QAction(QIcon(""), tr("&Save as..."), this);
saveAction->setShortcut(tr("Ctrl+S"));
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveSlot()));
quitAction = new QAction(QIcon(""), tr("&Quit"), this);
quitAction->setShortcut(tr("Ctrl+Q"));
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
addPointAction = new QAction(QIcon(""), tr("&Insert point"), this);
addPointAction->setShortcut(tr("Ctrl+P"));
connect(addPointAction, SIGNAL(triggered()), this, SLOT(addPointSlot()));
addCurveAction = new QAction(QIcon(""), tr("&Insert curve"), this);
addCurveAction->setShortcut(tr("Ctrl+C"));
connect(addCurveAction, SIGNAL(triggered()), this, SLOT(addCurveSlot()));
deletePointAction = new QAction(QIcon(""), tr("&Delete point"), this);
deletePointAction->setShortcut(tr("Ctrl+Z"));
connect(deletePointAction, SIGNAL(triggered()), this, SLOT(deletePointSlot()));
deleteCurveAction = new QAction(QIcon(""), tr("&Delete curve"), this);
deleteCurveAction->setShortcut(tr("Ctrl+X"));
connect(deleteCurveAction, SIGNAL(triggered()), this, SLOT(deleteCurveSlot()));
fitAction = new QAction(QIcon(""), tr("&Fit to window"), this);
fitAction->setShortcut(tr("Ctrl+F"));
connect(fitAction, SIGNAL(triggered()), renderArea, SLOT(fitSlot()));
drawPointsAction = new QAction(QIcon(""), tr("Draw points"), this);
drawPointsAction->setCheckable(true);
connect(drawPointsAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawPointsSlot(bool)));
drawPointsAction->setChecked(true);
drawSplinesAction = new QAction(QIcon(""), tr("Draw splines"), this);
drawSplinesAction->setCheckable(true);
connect(drawSplinesAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawSplinesSlot(bool)));
drawSplinesAction->setChecked(true);
drawTangentsAction = new QAction(QIcon(""), tr("Draw tangents"), this);
drawTangentsAction->setCheckable(true);
connect(drawTangentsAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawTangentsSlot(bool)));
drawTangentsAction->setChecked(true);
drawPointNumbersAction = new QAction(QIcon(""), tr("Point numbers"), this);
drawPointNumbersAction->setCheckable(true);
connect(drawPointNumbersAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawPointNumbersSlot(bool)));
drawPointNumbersAction->setChecked(true);
drawSplineNumbersAction = new QAction(QIcon(""), tr("Spline numbers"), this);
drawSplineNumbersAction->setCheckable(true);
connect(drawSplineNumbersAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawSplineNumbersSlot(bool)));
drawSplineNumbersAction->setChecked(true);
drawMaterialNumbersAction = new QAction(QIcon(""), tr("Material numbers"), this);
drawMaterialNumbersAction->setCheckable(true);
connect(drawMaterialNumbersAction, SIGNAL(toggled(bool)), renderArea, SLOT(drawMaterialNumbersSlot(bool)));
drawMaterialNumbersAction->setChecked(true);
helpAction = new QAction(QIcon(""), tr("&Help"), this);
helpAction->setShortcut(tr("Ctrl+H"));
connect(helpAction, SIGNAL(triggered()), this, SLOT(helpSlot()));
}
void TwodView::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAction);
fileMenu->addAction(saveAction);
fileMenu->addSeparator();
fileMenu->addAction(quitAction);
editMenu = menuBar()->addMenu(tr("&Edit"));
editMenu->addAction(addPointAction);
editMenu->addAction(addCurveAction);
editMenu->addSeparator();
editMenu->addAction(deletePointAction);
editMenu->addAction(deleteCurveAction);
viewMenu = menuBar()->addMenu(tr("&View"));
viewMenu->addAction(drawPointsAction);
viewMenu->addAction(drawSplinesAction);
viewMenu->addAction(drawTangentsAction);
viewMenu->addSeparator();
viewMenu->addAction(drawPointNumbersAction);
viewMenu->addAction(drawSplineNumbersAction);
viewMenu->addAction(drawMaterialNumbersAction);
viewMenu->addSeparator();
viewMenu->addAction(fitAction);
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(helpAction);
}
void TwodView::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void TwodView::statusMessage(QString message)
{
statusBar()->showMessage(message);
}
void TwodView::saveSlot()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save file"), "", tr("Geometry Input Files (*.in2d)"));
if(fileName.isEmpty())
return;
renderArea->saveSlot(fileName);
}
void TwodView::openSlot()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"), "", tr("Geometry Input Files (*.in2d)"));
if(fileName.isEmpty())
return;
renderArea->readSlot(fileName);
renderArea->fitSlot();
}
void TwodView::addPointSlot()
{
curveEditor->addPoint();
}
void TwodView::addCurveSlot()
{
curveEditor->addCurve();
}
void TwodView::deletePointSlot()
{
curveEditor->deletePoint();
}
void TwodView::deleteCurveSlot()
{
curveEditor->deleteCurve();
}
void TwodView::helpSlot()
{
QMessageBox::information(this, tr("Information"),
tr("Mouse controls:\n"
" Left-click to move points\n"
" Right-click to pan\n"
" Rotate wheel to zoom\n\n"
"Supported formats:\n"
" splinecurves2dv2"));
}
| 38.313253 | 114 | 0.58218 | readex-eu |
d0874a1724f343d76a204d0d95f37594499c8190 | 6,208 | hpp | C++ | lib/inc/thinsqlitepp/impl/statement_impl.hpp | gershnik/thinsqlitepp | c132c83c7733c1cb6173b09039ccf48d62507e49 | [
"BSD-3-Clause"
] | null | null | null | lib/inc/thinsqlitepp/impl/statement_impl.hpp | gershnik/thinsqlitepp | c132c83c7733c1cb6173b09039ccf48d62507e49 | [
"BSD-3-Clause"
] | null | null | null | lib/inc/thinsqlitepp/impl/statement_impl.hpp | gershnik/thinsqlitepp | c132c83c7733c1cb6173b09039ccf48d62507e49 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright 2019 Eugene Gershnik
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://github.com/gershnik/thinsqlitepp/blob/main/LICENSE
*/
#ifndef HEADER_SQLITEPP_STATEMENT_IMPL_INCLUDED
#define HEADER_SQLITEPP_STATEMENT_IMPL_INCLUDED
#include "database_iface.hpp"
#include "value_iface.hpp"
namespace thinsqlitepp
{
inline std::unique_ptr<statement> statement::create(const class database & db, const string_param & sql
#if SQLITE_VERSION_NUMBER >= 3020000
, unsigned int flags
#endif
)
{
const char * tail = nullptr;
sqlite3_stmt * ret = nullptr;
#if SQLITE_VERSION_NUMBER >= 3020000
int res = sqlite3_prepare_v3(db.c_ptr(), sql.c_str(), -1, flags, &ret, &tail);
#else
int res = sqlite3_prepare_v2(db.c_ptr(), sql.c_str(), -1, &ret, &tail);
#endif
if (res != SQLITE_OK)
throw exception(res, db);
return std::unique_ptr<statement>(from(ret));
}
inline std::unique_ptr<statement> statement::create(const class database & db, std::string_view & sql
#if SQLITE_VERSION_NUMBER >= 3020000
, unsigned int flags
#endif
)
{
const char * start = sql.size() ? &sql[0] : "";
const char * tail = nullptr;
sqlite3_stmt * ret = nullptr;
#if SQLITE_VERSION_NUMBER >= 3020000
int res = sqlite3_prepare_v3(db.c_ptr(), start, int(sql.size()), flags, &ret, &tail);
#else
int res = sqlite3_prepare_v2(db.c_ptr(), start, int(sql.size()), &ret, &tail);
#endif
if (res != SQLITE_OK)
throw exception(res, db);
sql.remove_prefix(tail - start);
return std::unique_ptr<statement>(from(ret));
}
inline bool statement::step()
{
int res = sqlite3_step(c_ptr());
if (res == SQLITE_DONE)
return false;
if (res == SQLITE_ROW)
return true;
throw exception(res, database());
}
inline void statement::bind(int idx, const std::string_view & value)
{
check_error(sqlite3_bind_text(c_ptr(), idx,
value.size() ? &value[0] : "",
int(value.size()),
SQLITE_TRANSIENT));
}
inline void statement::bind_reference(int idx, const std::string_view & value)
{
check_error(sqlite3_bind_text(c_ptr(), idx,
value.size() ? &value[0] : "",
int(value.size()),
SQLITE_STATIC));
}
#if __cpp_char8_t >= 201811
inline void statement::bind(int idx, const std::u8string_view & value)
{
check_error(sqlite3_bind_text(c_ptr(), idx,
value.size() ? (const char *)&value[0] : "",
int(value.size()),
SQLITE_TRANSIENT));
}
inline void statement::bind_reference(int idx, const std::u8string_view & value)
{
check_error(sqlite3_bind_text(c_ptr(), idx,
value.size() ? (const char *)&value[0] : "",
int(value.size()),
SQLITE_STATIC));
}
#endif
inline void statement::bind(int idx, const blob_view & value)
{
check_error(sqlite3_bind_blob(c_ptr(), idx,
value.size() ? &value[0] : (const std::byte *)"",
int(value.size()),
SQLITE_TRANSIENT));
}
inline void statement::bind_reference(int idx, const blob_view & value)
{
check_error(sqlite3_bind_blob(c_ptr(), idx,
value.size() ? &value[0] : (const std::byte *)"",
int(value.size()),
SQLITE_STATIC));
}
inline void statement::bind(int idx, const value & val)
{
check_error(sqlite3_bind_value(c_ptr(), idx, val.c_ptr()));
}
template<>
inline std::string_view statement::column_value<std::string_view>(int idx) const noexcept
{
auto first = (const char *)sqlite3_column_text(c_ptr(), idx);
auto size = (size_t)sqlite3_column_bytes(c_ptr(), idx);
return std::string_view(first, size);
}
#if __cpp_char8_t >= 201811
template<>
inline std::u8string_view statement::column_value<std::u8string_view>(int idx) const noexcept
{
auto first = (const char8_t *)sqlite3_column_text(c_ptr(), idx);
auto size = (size_t)sqlite3_column_bytes(c_ptr(), idx);
return std::u8string_view(first, size);
}
#endif
template<>
inline blob_view statement::column_value<blob_view>(int idx) const noexcept
{
auto first = (const std::byte *)sqlite3_column_blob(c_ptr(), idx);
auto size = sqlite3_column_bytes(c_ptr(), idx);
return blob_view(first, first + size);
}
#if SQLITE_VERSION_NUMBER >= 3014000
inline allocated_string statement::expanded_sql() const
{
auto ret = sqlite3_expanded_sql(c_ptr());
if (!ret)
throw exception(SQLITE_NOMEM);
return allocated_string(ret);
}
#endif
inline void statement::check_error(int res) const
{
if (res != SQLITE_OK)
throw exception(res, database());
}
inline std::unique_ptr<statement> statement_parser::next()
{
while (!_sql.empty())
{
auto stmt = statement::create(*_db, _sql);
if (!stmt) //this happens for a comment or white-space
continue;
//trim whitespace after statement
while (!_sql.empty() && isspace(_sql[0]))
_sql.remove_prefix(1);
return stmt;
}
return nullptr;
}
}
#endif
| 33.376344 | 107 | 0.536082 | gershnik |
d0883a7b1b82cffcb3238d45cffc94598e9f15a8 | 754 | cpp | C++ | codes/codeforces/OmkarandCompletion.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/codeforces/OmkarandCompletion.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/codeforces/OmkarandCompletion.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include <bits/stdc++.h>
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
using namespace std;
// Driver Code
int main()
{
int testCaseCount;
int testCase;
int n;
scanf("%d", &testCaseCount);
for (testCase = 1; testCase <= testCaseCount; testCase++)
{
scanf("%d", &n);
for(int i=0; i<n; i++){
cout << 1;
if(i!=n-1)
cout << " ";
}
cout << endl;
}
return 0;
} | 22.176471 | 61 | 0.460212 | smmehrab |
d08982cea5f4b208d7befbe2c2022ed9ef1511c1 | 444 | cpp | C++ | src/modell/objects/MTransX1.cpp | hemmerling/cpp-3dogs | 0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7 | [
"Apache-2.0"
] | null | null | null | src/modell/objects/MTransX1.cpp | hemmerling/cpp-3dogs | 0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7 | [
"Apache-2.0"
] | null | null | null | src/modell/objects/MTransX1.cpp | hemmerling/cpp-3dogs | 0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7 | [
"Apache-2.0"
] | null | null | null | #include "mtransx1.h"
#include "opengl2.h"
MTransX1::MTransX1(void) {}
MTransX1::MTransX1(MTranslation2 *command){
this->command = command;
}
MTransX1::~MTransX1(void) {}
void MTransX1::display(OpenGL &aOpenGL){
aOpenGL.display(this);
}
void MTransX1::update(GLubyte aKey){
update2();
}
void MTransX1::update(GLint aKey){
update2();
}
void MTransX1::update2(void){
command->setDirection(STOP);
command->setSpeed(0.0);
}
| 15.310345 | 43 | 0.693694 | hemmerling |
d08a5e3c4d3f1d7cf2e2b1465b5d105aa1e5f54f | 903 | cpp | C++ | common/stack/stackNumber.cpp | doctorsrn/manipulator_torque_controller | c276afe950448ecd03867498524f94b251f5238d | [
"MIT"
] | 11 | 2020-01-12T19:50:43.000Z | 2022-01-27T20:15:24.000Z | common/stack/stackNumber.cpp | doctorsrn/manipulator_torque_controller | c276afe950448ecd03867498524f94b251f5238d | [
"MIT"
] | 2 | 2022-01-23T06:46:27.000Z | 2022-02-21T06:17:01.000Z | coppeliaSim-client/common/stack/stackNumber.cpp | mhsitu/welding_robot | 03a1a5f83049311777f948715d7bf5399dc2dbbb | [
"MIT"
] | 2 | 2020-10-09T06:10:05.000Z | 2021-11-21T13:00:13.000Z | #include "stackNumber.h"
#include <sstream>
CStackNumber::CStackNumber(double n)
{
_objectType=STACK_NUMBER;
_value=n;
}
CStackNumber::~CStackNumber()
{
}
std::string CStackNumber::toString() const
{
std::stringstream ss;
ss << _value;
return(ss.str());
}
float CStackNumber::getFloatValue()
{
return((float)_value);
}
int CStackNumber::getIntValue()
{
return((int)_value);
}
long CStackNumber::getLongValue()
{
return((long)_value);
}
double CStackNumber::getValue()
{
return(_value);
}
void CStackNumber::setFloatValue(float n)
{
_value=(double)n;
}
void CStackNumber::setIntValue(int n)
{
_value=(int)n;
}
void CStackNumber::setLongValue(long n)
{
_value=(long)n;
}
void CStackNumber::setValue(double n)
{
_value=n;
}
CStackObject* CStackNumber::copyYourself()
{
CStackNumber* retVal=new CStackNumber(_value);
return(retVal);
}
| 13.681818 | 50 | 0.682171 | doctorsrn |
d08b77bb54317f62de909d6d66f83bb5501b9761 | 6,536 | cpp | C++ | src/Bloom.cpp | sltn011/OpenGL-Learning | 7f3b8cd730ba9d300406cdd6608afb1db6d23b31 | [
"MIT"
] | 1 | 2020-10-26T17:53:33.000Z | 2020-10-26T17:53:33.000Z | src/Bloom.cpp | sltn011/OpenGL-Learning | 7f3b8cd730ba9d300406cdd6608afb1db6d23b31 | [
"MIT"
] | null | null | null | src/Bloom.cpp | sltn011/OpenGL-Learning | 7f3b8cd730ba9d300406cdd6608afb1db6d23b31 | [
"MIT"
] | null | null | null | #include "Bloom.hpp"
namespace OGL {
Bloom::Bloom(
Shader &&downsamplingShader,
Shader &&horizontalBlurShader,
Shader &&verticalBlurShader,
Shader &&combineShader,
glm::vec3 thresHold
) : m_downsamplingShader{ std::move(downsamplingShader) },
m_horizontalBlurShader{ std::move(horizontalBlurShader) },
m_verticalBlurShader{ std::move(verticalBlurShader) },
m_combineShader{ std::move(combineShader) },
m_thresHold{ thresHold },
m_resultWidth{ 0 },
m_resultHeight{ 0 } {
}
void Bloom::initFrameBuffers(
int windowWidth,
int windowHeight
) {
initFramebuffer(m_result, windowWidth, windowHeight);
initFramebuffer(m_temp, windowWidth, windowHeight);
for (int i = 0; i < s_numMipmaps; ++i) {
int fboWidth = static_cast<int>(windowWidth / std::pow(s_downscale, i + 1));
int fboHeight = static_cast<int>(windowHeight / std::pow(s_downscale, i + 1));
initFramebuffer(m_downsamples[i], fboWidth, fboHeight);
initFramebuffer(m_intermediate[i], fboWidth, fboHeight);
}
m_resultWidth = windowWidth;
m_resultHeight = windowHeight;
}
void Bloom::drawToResultFrameBuffer(
FrameBufferObject &sceneFrameBuffer
) {
glDisable(GL_DEPTH_TEST);
blit(sceneFrameBuffer, m_result, m_resultWidth, m_resultHeight);
setupDownsampleShader(true);
resizeImage(
m_result,
m_downsamples[0],
static_cast<int>(m_resultWidth / s_downscale),
static_cast<int>(m_resultHeight / s_downscale)
);
blurImage(0, static_cast<int>(m_resultWidth / s_downscale), static_cast<int>(m_resultHeight / s_downscale));
for (int i = 1; i < s_numMipmaps; ++i) {
setupDownsampleShader(false);
int sampleWidth = static_cast<int>(m_resultWidth / std::pow(s_downscale, i + 1));
int sampleHeight = static_cast<int>(m_resultHeight / std::pow(s_downscale, i + 1));
resizeImage(
m_downsamples[i - 1],
m_downsamples[i],
sampleWidth,
sampleHeight
);
blurImage(i, sampleWidth, sampleHeight);
}
setupCombineShader();
for (int i = s_numMipmaps - 1; i > 0; --i) {
int sampleWidth = static_cast<int>(m_resultWidth / std::pow(s_downscale, i));
int sampleHeight = static_cast<int>(m_resultHeight / std::pow(s_downscale, i));
combineImages(
m_intermediate[i - 1],
m_downsamples[i],
m_downsamples[i - 1],
sampleWidth,
sampleHeight
);
blit(m_intermediate[i - 1], m_downsamples[i - 1], sampleWidth, sampleHeight);
}
combineImages(m_temp, m_downsamples[0], m_result, m_resultWidth, m_resultHeight);
blit(m_temp, m_result, m_resultWidth, m_resultHeight);
glEnable(GL_DEPTH_TEST);
}
void Bloom::bindResultFrameBuffer(
GLenum frameBufferType
) {
m_result.bind(frameBufferType);
}
void Bloom::initFramebuffer(
FrameBufferObject &fbo,
int width,
int height
) {
fbo.bind(GL_FRAMEBUFFER);
ColorBufferObject cbo;
cbo.allocateStorage(width, height, GL_TEXTURE_2D, GL_RGBA16F, GL_RGBA, GL_FLOAT);
fbo.attachColorBuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, std::move(cbo));
if (!fbo.isComplete(GL_FRAMEBUFFER)) {
FrameBufferObject::unbind(GL_FRAMEBUFFER);
throw Exception("Error creating FBO!");
}
FrameBufferObject::unbind(GL_FRAMEBUFFER);
}
void Bloom::blit(
FrameBufferObject &from,
FrameBufferObject &to,
int width,
int height
) {
from.bind(GL_READ_FRAMEBUFFER);
to.bind(GL_DRAW_FRAMEBUFFER);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
FrameBufferObject::unbind(GL_FRAMEBUFFER);
}
void Bloom::resizeImage(
FrameBufferObject &from,
FrameBufferObject &to,
int newWidth,
int newHeight
) {
glViewport(0, 0, newWidth, newHeight);
to.bind(GL_FRAMEBUFFER);
from.drawQuad(GL_COLOR_ATTACHMENT0);
}
void Bloom::blurImage(
int imageIndex,
int imageWidth,
int imageHeight
) {
setupHorizontalBlurShader(imageWidth);
m_intermediate[imageIndex].bind(GL_FRAMEBUFFER);
m_downsamples[imageIndex].drawQuad(GL_COLOR_ATTACHMENT0);
setupVerticalBlurShader(imageHeight);
m_downsamples[imageIndex].bind(GL_FRAMEBUFFER);
m_intermediate[imageIndex].drawQuad(GL_COLOR_ATTACHMENT0);
FrameBufferObject::unbind(GL_FRAMEBUFFER);
}
void Bloom::combineImages(
FrameBufferObject &dst,
FrameBufferObject &fbo1,
FrameBufferObject &fbo2,
int dstWidth,
int dstHeight
) {
glViewport(0, 0, dstWidth, dstHeight);
glActiveTexture(GL_TEXTURE0);
fbo1.getColorBuffers().at(GL_COLOR_ATTACHMENT0).bindAsTexture(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1);
fbo2.getColorBuffers().at(GL_COLOR_ATTACHMENT0).bindAsTexture(GL_TEXTURE_2D);
dst.bind(GL_FRAMEBUFFER);
dst.drawQuadRaw();
FrameBufferObject::unbind(GL_FRAMEBUFFER);
}
void Bloom::setupDownsampleShader(
bool bDoCutoff
) {
m_downsamplingShader.use();
m_downsamplingShader.setUniformInt("fboTexture", 0);
m_downsamplingShader.setUniformVec3("bloomThresHold", bDoCutoff ? m_thresHold : glm::vec3(0.0f));
}
void Bloom::setupHorizontalBlurShader(
int imageWidth
) {
m_horizontalBlurShader.use();
m_horizontalBlurShader.setUniformInt("fboTexture", 0);
m_horizontalBlurShader.setUniformInt("imageWidth", imageWidth);
}
void Bloom::setupVerticalBlurShader(
int imageHeight
) {
m_verticalBlurShader.use();
m_verticalBlurShader.setUniformInt("fboTexture", 0);
m_verticalBlurShader.setUniformInt("imageHeight", imageHeight);
}
void Bloom::setupCombineShader(
) {
m_combineShader.use();
m_combineShader.setUniformInt("fboTexture1", 0);
m_combineShader.setUniformInt("fboTexture2", 1);
}
} // OGL | 33.177665 | 116 | 0.626224 | sltn011 |
d08f48515301709c5cccfcabeb509b06d4533129 | 9,122 | cpp | C++ | src/RTL/Component/SceneGraph/CIFXViewResource.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 44 | 2016-05-06T00:47:11.000Z | 2022-02-11T06:51:37.000Z | src/RTL/Component/SceneGraph/CIFXViewResource.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 3 | 2016-06-27T12:37:31.000Z | 2021-03-24T12:39:48.000Z | src/RTL/Component/SceneGraph/CIFXViewResource.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 15 | 2016-02-28T11:08:30.000Z | 2021-06-01T03:32:01.000Z | //***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
/*
@file CIFXViewResource.cpp
*/
#include "IFXSceneGraphPCH.h"
#include "CIFXViewResource.h"
#include "IFXLightSet.h"
#include "IFXPickObject.h"
#include "IFXRenderable.h"
#include "IFXModifierDataElementIter.h"
#include "IFXModifierDataPacket.h"
#include "IFXSimpleList.h"
#include "IFXSpatialSetQuery.h"
#include "IFXBoundSphereDataElement.h"
#include "IFXDids.h"
#include "IFXExportingCIDs.h"
CIFXViewResource::CIFXViewResource()
{
m_uRefCount = 0;
m_uQualityFactor = 0;
m_layer = 0;
m_uNumRenderPasses = 0;
m_uCurrentPass = 0;
m_ppRenderPass = NULL;
AllocateRenderPasses();
FogEnable(FALSE);
SetStencilEnabled( FALSE );
SetColorBufferEnabled( TRUE ); //currently does nothing
GetRenderClear().SetColorCleared( TRUE );
GetRenderClear().SetColorValue( IFXVector3( 0,0,0 ) );
SetDepthTestEnabled( TRUE );
SetDepthWriteEnabled( TRUE );
GetRenderClear().SetDepthCleared( TRUE );
GetRenderClear().SetDepthValue( (F32)1.0 );
}
CIFXViewResource::~CIFXViewResource()
{
}
IFXRESULT IFXAPI_CALLTYPE CIFXViewResource_Factory(IFXREFIID riid, void **ppv)
{
IFXRESULT result;
if ( ppv )
{
// Create the CIFXClassName component.
CIFXViewResource *pView = new CIFXViewResource;
if ( pView )
{
// Perform a temporary AddRef for our usage of the component.
pView->AddRef();
// Attempt to obtain a pointer to the requested interface.
result = pView->QueryInterface( riid, ppv );
// Perform a Release since our usage of the component is now
// complete. Note: If the QI fails, this will cause the
// component to be destroyed.
pView->Release();
}
else result = IFX_E_OUT_OF_MEMORY;
}
else result = IFX_E_INVALID_POINTER;
return result;
}
// IFXUnknown
U32 CIFXViewResource::AddRef()
{
return ++m_uRefCount;
}
U32 CIFXViewResource::Release()
{
if (m_uRefCount == 1)
{
DeallocateRenderPasses();
delete this ;
return 0 ;
}
else
return (--m_uRefCount);
}
IFXRESULT CIFXViewResource::QueryInterface(IFXREFIID interfaceId, void** ppInterface)
{
IFXRESULT result = IFX_OK;
if ( ppInterface )
{
if ( interfaceId == IID_IFXUnknown )
*ppInterface = ( IFXUnknown* ) this;
else if ( interfaceId == IID_IFXMarker )
*ppInterface = ( IFXMarker* ) this;
else if ( interfaceId == IID_IFXMarkerX )
*ppInterface = ( IFXMarkerX* ) this;
else if ( interfaceId == IID_IFXViewResource )
*ppInterface = ( IFXViewResource* ) this;
else if ( interfaceId == IID_IFXMetaDataX )
*ppInterface = ( IFXMetaDataX* ) this;
else
{
*ppInterface = NULL;
result = IFX_E_UNSUPPORTED;
}
if ( IFXSUCCESS( result ) )
AddRef();
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
// IFXMarker
IFXRESULT CIFXViewResource::SetSceneGraph( IFXSceneGraph* pInSceneGraph )
{
return CIFXMarker::SetSceneGraph( pInSceneGraph );
}
// IFXMarkerX
void CIFXViewResource::GetEncoderX(IFXEncoderX*& rpEncoderX)
{
CIFXMarker::GetEncoderX(CID_IFXViewResourceEncoder, rpEncoderX);
}
IFXRESULT CIFXViewResource::GetRootNode(U32* pNodeIndex, U32* pNodeInstance)
{
IFXRESULT result = IFX_OK;
if ( pNodeIndex && pNodeInstance ) {
*pNodeIndex = m_ppRenderPass[m_uCurrentPass]->m_nodeIndex;
*pNodeInstance = m_ppRenderPass[m_uCurrentPass]->m_nodeInstance;
} else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT CIFXViewResource::SetRootNode(U32 nodeIndex, U32 nodeInstance)
{
IFXRESULT result = IFX_OK;
result = m_ppRenderPass[m_uCurrentPass]->SetRootNode(nodeIndex, nodeInstance);
// Make sure to set all rootnodes that are null
U32 i;
for( i = 0; IFXSUCCESS(result) && i < m_uNumRenderPasses; i++)
if(m_ppRenderPass[i]->m_nodeSet == FALSE)
result = m_ppRenderPass[i]->SetRootNode(nodeIndex, nodeInstance);
return result;
}
void CIFXViewResource::ClearRootNode()
{
m_ppRenderPass[m_uCurrentPass]->ClearRootNode();
}
IFXRenderClear& CIFXViewResource::GetRenderClear()
{
return m_ppRenderPass[m_uCurrentPass]->m_Clear;
}
// IFXViewResource
IFXRESULT CIFXViewResource::AllocateRenderPasses(U32 uNumRenderPasses)
{
IFXRESULT rc = IFX_OK;
IFXRenderPass** ppRenderPasses = new IFXRenderPass*[uNumRenderPasses];
if(NULL == ppRenderPasses)
{
rc = IFX_E_OUT_OF_MEMORY;
}
if(IFXSUCCESS(rc))
{
if(m_uNumRenderPasses)
{
U32 uNumToCopy = m_uNumRenderPasses;
if(uNumToCopy > uNumRenderPasses)
uNumToCopy = uNumRenderPasses;
U32 i;
for( i = 0; i < uNumToCopy; i++)
{
ppRenderPasses[i] = m_ppRenderPass[i];
m_ppRenderPass[i] = 0;
}
}
U32 i;
for( i = m_uNumRenderPasses; i < uNumRenderPasses; i++)
{
ppRenderPasses[i] = new IFXRenderPass();
ppRenderPasses[i]->SetDefaults(i);
// Assign new passes to have the same rootnode as the first pass
if(i && ppRenderPasses[0]->m_nodeSet)
ppRenderPasses[i]->SetRootNode(
ppRenderPasses[0]->m_nodeIndex,
ppRenderPasses[0]->m_nodeInstance);
}
IFXDELETE_ARRAY(m_ppRenderPass);
m_ppRenderPass = ppRenderPasses;
m_uNumRenderPasses = uNumRenderPasses;
}
return rc;
}
IFXRESULT CIFXViewResource::DeallocateRenderPasses()
{
U32 i;
for( i = 0; i < m_uNumRenderPasses; i++ )
IFXDELETE( m_ppRenderPass[i] );
IFXDELETE_ARRAY(m_ppRenderPass);
return IFX_OK;
}
// IFXViewResource
IFXRESULT CIFXViewResource::GetFogEnableValue( BOOL* pbEnable )
{
IFXRESULT result = IFX_OK;
if ( NULL != pbEnable )
*pbEnable = m_ppRenderPass[m_uCurrentPass]->m_bFogEnabled;
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT CIFXViewResource::FogEnable( BOOL bEnable )
{
m_ppRenderPass[m_uCurrentPass]->m_bFogEnabled = bEnable;
return IFX_OK;
}
IFXRenderFog& CIFXViewResource::GetRenderFog()
{
return m_ppRenderPass[m_uCurrentPass]->m_Fog;
}
IFXRESULT CIFXViewResource::GetColorBufferEnabled(BOOL& bEnabled )
{
bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bColorBuffer;
return IFX_OK;
}
IFXRESULT CIFXViewResource::SetColorBufferEnabled(BOOL bEnabled )
{
m_ppRenderPass[m_uCurrentPass]->m_bColorBuffer = bEnabled;
return IFX_OK;
}
IFXRESULT CIFXViewResource::GetDepthTestEnabled(BOOL& bEnabled )
{
bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bDepthTest;
return IFX_OK;
}
IFXRESULT CIFXViewResource::SetDepthTestEnabled(BOOL bEnabled )
{
m_ppRenderPass[m_uCurrentPass]->m_bDepthTest = bEnabled;
return IFX_OK;
}
IFXRESULT CIFXViewResource::GetDepthWriteEnabled(BOOL& bEnabled )
{
bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bDepthWrite;
return IFX_OK;
}
IFXRESULT CIFXViewResource::SetDepthWriteEnabled(BOOL bEnabled )
{
m_ppRenderPass[m_uCurrentPass]->m_bDepthWrite = bEnabled;
return IFX_OK;
}
IFXRESULT CIFXViewResource::GetDepthFunc(IFXenum & eDepthFunc )
{
eDepthFunc = m_ppRenderPass[m_uCurrentPass]->m_eDepthFunc;
return IFX_OK;
}
IFXRESULT CIFXViewResource::SetDepthFunc(IFXenum eDepthFunc )
{
IFXRESULT rc = IFX_OK;
switch(eDepthFunc)
{
case IFX_ALWAYS:
case IFX_LESS:
case IFX_LEQUAL:
case IFX_GREATER:
case IFX_GEQUAL:
case IFX_EQUAL:
case IFX_NOT_EQUAL:
case IFX_NEVER:
m_ppRenderPass[m_uCurrentPass]->m_eDepthFunc = eDepthFunc;
break;
default:
rc = IFX_E_INVALID_RANGE;
}
return rc;
}
IFXRESULT CIFXViewResource::GetStencilEnabled( BOOL& bEnable )
{
bEnable = m_ppRenderPass[m_uCurrentPass]->m_bStencilEnabled;
return IFX_OK;
}
IFXRESULT CIFXViewResource::SetStencilEnabled( BOOL bEnable )
{
m_ppRenderPass[m_uCurrentPass]->m_bStencilEnabled = bEnable;
return IFX_OK;
}
IFXRenderStencil& CIFXViewResource::GetRenderStencil()
{
return m_ppRenderPass[m_uCurrentPass]->m_Stencil;
}
// Multipass support
IFXRESULT CIFXViewResource::SetNumRenderPasses(U32 uNumPasses)
{
IFXRESULT rc = IFX_E_INVALID_RANGE;
IFXASSERTBOX( uNumPasses <= 32,
"Trying to use too many rendering passes - use less than 33" );
if(uNumPasses <= 32)
{
rc = AllocateRenderPasses(uNumPasses);
}
return rc;
}
U32 CIFXViewResource::GetNumRenderPasses(void)
{
return m_uNumRenderPasses;
}
IFXRESULT CIFXViewResource::SetCurrentRenderPass(U32 uRenderPass)
{
IFXRESULT rc = IFX_OK;
IFXASSERTBOX( uRenderPass < m_uNumRenderPasses,
"Setting invalid render pass number" );
if(uRenderPass >= m_uNumRenderPasses)
rc = IFX_E_INVALID_RANGE;
else
m_uCurrentPass = uRenderPass;
return rc;
}
U32 CIFXViewResource::GetCurrentRenderPass()
{
return m_uCurrentPass;
}
///
| 21.822967 | 85 | 0.725828 | alemuntoni |
d09020f7e8459f220d23b95a8e19f661d505174f | 7,664 | hpp | C++ | include/Topics.hpp | juliusHuelsmann/Logger | 8fd61f0318229dfdbb334a0d41e71fd48cd74979 | [
"Apache-2.0"
] | null | null | null | include/Topics.hpp | juliusHuelsmann/Logger | 8fd61f0318229dfdbb334a0d41e71fd48cd74979 | [
"Apache-2.0"
] | 7 | 2018-11-02T21:44:06.000Z | 2018-11-19T09:13:36.000Z | include/Topics.hpp | juliusHuelsmann/Logger | 8fd61f0318229dfdbb334a0d41e71fd48cd74979 | [
"Apache-2.0"
] | null | null | null |
#ifndef _TOPICS_HPP_
#define _TOPICS_HPP_
#include <outputHandler/OutputHandler.h>
#include <outputHandler/StdIo.h>
#include <SlogConstants.h>
#include <guard/MutexReturn.h>
#include <topics/Topic.h>
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
#include <map>
#include <boost/algorithm/string.hpp>
#include <cstdarg>
#include <mutex>
#include <thread>
namespace slog {
#define SUB_EQ(sub, str) (str).size() >= (sub).size() && \
std::equal((sub).begin(), (sub).begin()+(sub).size(), (str).begin())
typedef std::ostream& (*ManipFn)(std::ostream&);
typedef std::ios_base& (*FlagsFn)(std::ios_base&);
/**
* Contains functionality for logging and for specification of topics and
* topic-related settings and functionality for making the logging thread
* safe.
*/
class Topics {
public:
virtual ~Topics();
/**
* Set the default configuration which is applied in case no more
* specific sub-configuration is given.
*/
void setBaseContext(const topic::Context& baseContext);
/**
* Function used for enabling a topic. After it is enabled, the specified
* topic or any of its descendants are enabled and processed as specified
* via preference - parameters.
*
* Logging preferences (called "Context") for topics are inherited on
* each level of the topic tree if provided.
* The root of the tree is the base configuration "baseContext" which
* must always specify an outputHandler that might be "overwritten" by
* a more specific outputHandler specified for a descendant of the topic.
*
* If this function is called multiple times for the same topic, the
* information provided last are taken into account and the topics
* that already exist are updated.
*/
void enableTopic(std::string topic,
std::shared_ptr<outputHandler::OutputHandler> out= nullptr,
uint memorySize=0, std::string topicPrefix="",
std::string plotStyle=LINE_PLOT,
uint64_t plotBufferSize=0);
void flush();
/**
* Log values provided in #vec via outputStream provided by the topic
* configuration iferred from #tIdent.
*
* This function is not recommended to be called directly, the
* preprocessor macro #TOPIC provides a more convenient api.
*
* For a topic, the type and the vector are required to remain the
* same during an entire session.
*/
template <typename T> void topic(std::string tIdent, std::vector<T> vec) {
lock();
volatile MutexReturn mr(this);
preprocessTopic(tIdent);
// The topic is implicitly disabled (check returned false before); exit
if (disabledTopics.count(tIdent)) return;
const auto sizeType = sizeof(T);
const auto sizeVec = vec.size();
auto type = typeid(T).name()[0];
type = type == 'x' ? 'q': type; //XXX: fix this generally
if (!launchedTopics.count(tIdent)) {
// the exact topic has not been used yet, but it is possible that
// it is a descendant of a topic that is enabled.
assert(sizeVec < std::numeric_limits<unsigned char>::max());
assert(sizeVec < std::numeric_limits<unsigned char>::max());
auto contextToAdd = computeSettings(tIdent,
(unsigned char) sizeVec,
(unsigned char) sizeType,
type);
if (contextToAdd) {
launchedTopics[tIdent] = contextToAdd;
launchedTopics[tIdent]->els = (char* ) malloc(contextToAdd->memorySize);
}
else {
disabledTopics[tIdent] = true;
return;
}
}
// The topic can be found in the enabled-mapping.
// Log the provided parameters.
//
// Sanity checks.
assert(launchedTopics.count(tIdent));
auto topic = launchedTopics[tIdent];
assert(topic->out);
// the amount of parameters and the size of the data type is assumed
// to remain unchanged.
assert(sizeVec == topic->amount && sizeType == topic->typeSize
&& topic->dataType == type);
// Size of the topic and subTopic string has to fit into an unsigned char.
// The size of the plot style is guaranteed to be < 255 as its contents are
// predefined.
const auto limitSize = std::numeric_limits<unsigned char>::max();
assert (topic->topic.size() <= limitSize);
assert (topic->subTopic.size() <= limitSize);
assert (topic->plotStyle.size() <= limitSize);
// Find out if the new parameters have space inside the buffer or if the
// buffer has to be flushed
const auto sizeToAdd = vec.size() * sizeof(T);
if (topic->memorySize <= sizeToAdd + topic->nextFreeIndex) {
topic->out->logTopic(topic, (const char*) vec.data(), (size_t) sizeToAdd);
} else {
//
// write to buffer and increase buffer index.
memcpy(topic->els+topic->nextFreeIndex, vec.data(), sizeToAdd);
topic->nextFreeIndex += sizeToAdd;
assert(topic->nextFreeIndex < topic->memorySize);
}
}
topic::Context const & getBaseContext() const;
protected:
void lock();
void unlock();
private:
/**
* Utility method for computing the context for a given branch if enabled.
*
* @param topicBranchId a string that uniquely identifies the
* branch in the settings tree.
* @param amountParameters the typical amount of parameters that is
* logged under the specific topic.
* @param sizeType the type of the size that is to be stored
* under topic.
*
* @return the context that is attached for the provided settings
* branch identifier or nullptr if the settings in question
* are not logged.
* @see recomputeSettings
*/
topic::Context* computeSettings(const std::string& topic,
unsigned char amountParameters, unsigned char sizeType, char dataType);
/**
*
* @param topic a string that uniquely identifies the
* branch in the settings tree.
* @param ctx Handle to a pointer of context, is deleted and
* set to nullptr if the subject branch is not
* enabled, otherwise contains the context
* associated with the settingds branch.
*/
void recomputeSettings(const std::string& topic,
topic::Context*& ctx, bool enabled=false);
inline void preprocessTopic(std::string& raw) {
while(raw.find("..") != std::string::npos) boost::replace_all(raw, "..", ".");
while(raw.find("].") != std::string::npos) boost::replace_all(raw, "].", "]");
}
static void iterate(slog::topic::Topic* top, size_t sz, std::stringstream& sstr);
/**
* Root of the settings tree, guaranteed to have an outputHandler
* configured.
*/
topic::Context baseContext;
/**
* Root of the topics tree.
*/
topic::Topic topics;
/**
* Map for quick lookup of topics that have already been launched
*/
std::unordered_map<std::string, topic::Context*> launchedTopics;
/**
* Map for quick lookup of topics that have already been used in #log
* but not been enabled yet.
*/
std::unordered_map<std::string, bool> disabledTopics;
std::recursive_mutex mtx;
friend MutexReturn;
};
}
#endif // _TOPICS_HPP_
| 32.752137 | 85 | 0.626174 | juliusHuelsmann |
d092a46ac91962e86187d573f3cfc211ffd2c2a4 | 3,372 | cc | C++ | src/4env/env.cc | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | null | null | null | src/4env/env.cc | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | 9 | 2018-05-05T08:01:58.000Z | 2018-05-07T19:10:01.000Z | src/4env/env.cc | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the file COPYING for License information.
*/
#include "0root/root.h"
// Always verify that a file of level N does not include headers > N!
#include "4cursor/cursor.h"
#include "4db/db.h"
#include "4env/env.h"
#ifndef UPS_ROOT_H
# error "root.h was not included"
#endif
using namespace upscaledb;
namespace upscaledb {
Db *
Env::create_db(DbConfig &config, const ups_parameter_t *param)
{
Db *db = do_create_db(config, param);
assert(db != 0);
// on success: store the open database in the environment's list of
// opened databases
_database_map[config.db_name] = db;
// flush the environment to make sure that the header page is written
// to disk
ups_status_t st = flush(0);
if (unlikely(st))
throw Exception(st);
return db;
}
Db *
Env::open_db(DbConfig &config, const ups_parameter_t *param)
{
// make sure that this database is not yet open
if (unlikely(_database_map.find(config.db_name) != _database_map.end()))
throw Exception(UPS_DATABASE_ALREADY_OPEN);
Db *db = do_open_db(config, param);
assert(db != 0);
// on success: store the open database in the environment's list of
// opened databases
_database_map[config.db_name] = db;
return db;
}
ups_status_t
Env::close_db(Db *db, uint32_t flags)
{
uint16_t dbname = db->name();
// flush committed Txns
ups_status_t st = flush(UPS_FLUSH_COMMITTED_TRANSACTIONS);
if (unlikely(st))
return (st);
st = db->close(flags);
if (unlikely(st))
return (st);
_database_map.erase(dbname);
delete db;
/* in-memory database: make sure that a database with the same name
* can be re-created */
if (IS_SET(config.flags, UPS_IN_MEMORY))
erase_db(dbname, 0);
return 0;
}
ups_status_t
Env::close(uint32_t flags)
{
ups_status_t st = 0;
ScopedLock lock(mutex);
/* auto-abort (or commit) all pending transactions */
if (txn_manager.get()) {
Txn *t;
while ((t = txn_manager->oldest_txn())) {
if (!t->is_aborted() && !t->is_committed()) {
if (IS_SET(flags, UPS_TXN_AUTO_COMMIT))
st = txn_manager->commit(t);
else /* if (flags & UPS_TXN_AUTO_ABORT) */
st = txn_manager->abort(t);
if (unlikely(st))
return st;
}
txn_manager->flush_committed_txns();
}
}
/* close all databases */
Env::DatabaseMap::iterator it = _database_map.begin();
while (it != _database_map.end()) {
Env::DatabaseMap::iterator it2 = it; it++;
Db *db = it2->second;
if (IS_SET(flags, UPS_AUTO_CLEANUP))
st = ups_db_close((ups_db_t *)db, flags | UPS_DONT_LOCK);
else
st = db->close(flags);
if (unlikely(st))
return st;
}
_database_map.clear();
return do_close(flags);
}
} // namespace upscaledb
| 24.794118 | 75 | 0.674081 | romz-pl |
d0957ef912818acc8cea594b0348d71d21daf660 | 467 | cpp | C++ | 2DProject2ndYear/main.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | 2DProject2ndYear/main.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | 2DProject2ndYear/main.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | #include "_2DProject2ndYearApp.h"
#include "PhysicsEngineApp.h"
#include "BrickTest.h"
#include <vld.h> // visual leak detection
#include <crtdbg.h> // traditional method to check memory leak
#include <Imgui.h>
int main()
{
// leak detection
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// allocation
auto app = new PhysicsEngineApp();
// initialise and loop
app->run("AIE", 1280, 720, false);
// deallocation
delete app;
return 0;
} | 20.304348 | 64 | 0.721627 | ryan0432 |
d096b820283b096111d61c95bab22b4f663a60ea | 4,742 | cpp | C++ | codeforce/E53/E53G.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | 5 | 2019-03-17T01:33:19.000Z | 2021-06-25T09:50:45.000Z | codeforce/E53/E53G.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | codeforce/E53/E53G.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <tuple>
#include <string>
using namespace std;
struct SuffixDataStructure {
const std::vector<int> &a;
std::vector<int> sa;
std::vector<int> isa;
std::vector<int> lcp;
std::vector<int> lg;
std::vector<std::vector<int> > rmq;
// a[i]>=0
SuffixDataStructure(const std::vector<int> &a) : a(a) {
sa = suffix_array(a);
sa.insert(sa.begin(), a.size());
build_lcp();
build_rmq();
}
int get_lcp(int i, int j) {
if (i == j) {
return a.size() - std::max(i, j);
}
i = isa[i];
j = isa[j];
if (i > j) {
std::swap(i, j);
}
int k = __lg(j - i);
return std::min(rmq[k][i], rmq[k][j - (1 << k)]);
}
vector<int> suffix_array(vector<int> a) {
const int n = a.size();
if (n == 0) return {};
const int H = *max_element(begin(a), end(a)) + 1;
vector<bool> s(n);
vector<int> next(n), ss;
for (int i = n - 2; i >= 0; i--) {
s[i] = a[i] == a[i + 1] ? s[i + 1] : a[i] < a[i + 1];
if (!s[i] && s[i + 1]) ss.push_back(i + 1);
}
reverse(ss.begin(), ss.end());
for (int i = 0; i < ss.size(); i++) {
next[ss[i]] = i + 1 < ss.size() ? ss[i + 1] : n;
}
auto induced_sort = [&]() {
vector<int> sa(n, -1), L(H + 1);
for (int i = 0; i < n; i++) L[a[i] + 1]++;
for (int i = 0; i < H; i++) L[i + 1] += L[i];
auto S = L;
for (int i = (int)ss.size() - 1; i >= 0; i--) {
int j = ss[i];
sa[--S[a[j] + 1]] = j;
}
S = L;
sa[L[a[n - 1]]++] = n - 1;
for (int i = 0; i < n; i++) {
int j = sa[i] - 1;
if (j >= 0 && !s[j]) sa[L[a[j]]++] = j;
}
for (int i = n - 1; i >= 0; i--) {
int j = sa[i] - 1;
if (j >= 0 && s[j]) sa[--S[a[j] + 1]] = j;
}
return sa;
};
vector<int> rank(n);
int j = -1;
for (int i : induced_sort()) {
if (0 < i && s[i] && !s[i - 1]) {
if (j != -1) rank[i] = rank[j] + (next[i] - i != next[j] - j || !equal(a.begin() + i, a.begin() + next[i], a.begin() + j));
j = i;
}
}
vector<int> b;
for (int i : ss) b.push_back(rank[i]);
vector<int> tmp(ss);
ss.clear();
for (int i : suffix_array(b)) ss.push_back(tmp[i]);
return induced_sort();
}
void build_lcp() {
const int n = a.size();
isa.resize(n + 1);
lcp.assign(n + 1, 0);
for (int i = 0; i <= n; i++) {
isa[sa[i]] = i;
}
int k = 0;
for (int i = 0; i < n; i++) {
int j = sa[isa[i] - 1];
k = std::max(0, k - 1);
while (i + k < n && j + k < n && a[i + k] == a[j + k]) {
k++;
}
lcp[isa[i] - 1] = k;
}
}
void build_rmq() {
const int n = lcp.size();
lg.resize(n + 1);
for (int i = 2; i <= n; i++) {
lg[i] = lg[i / 2] + 1;
}
const int m = lg[n];
rmq.assign(m + 1, std::vector<int>(n));
for (int i = 0; i < n; i++) {
rmq[0][i] = lcp[i];
}
for (int i = 0; i < m; i++) {
for (int j = 0; j + (1 << i) < n; j++) {
rmq[i + 1][j] = std::min(rmq[i][j], rmq[i][j + (1 << i)]);
}
}
}
};
const long long inf = 1e9;
struct Stack {
vector<pair<int, long long>> a;
long long sum = 0;
void push() {
sum += inf;
a.emplace_back(inf, 1);
}
void cut(int k) {
long long s = 0;
while (!a.empty() && a.back().first >= k) {
s += a.back().second;
sum -= a.back().first * a.back().second;
a.pop_back();
}
sum += s * k;
a.emplace_back(k, s);
}
int total() {
int s = 0;
for (auto p : a) s += p.second;
return s;
}
};
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> a;
for (int i = 0; i < n; i++) {
a.push_back(s[i] - 'a');
}
SuffixDataStructure sa(a);
while (q--) {
int u, v;
scanf("%d %d", &u, &v);
vector<int> a(u);
vector<int> b(v);
for (int i = 0; i < u; i++) scanf("%d", &a[i]), a[i]--, a[i] = sa.isa[a[i]];
for (int i = 0; i < v; i++) scanf("%d", &b[i]), b[i]--, b[i] = sa.isa[b[i]];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int i = 0;
int j = 0;
Stack A, B;
int p = -1;
long long ans = 0;
while (i < u || j < v) {
if (j == v || (i < u && a[i] < b[j])) {
int h = p == -1 ? 0 : sa.get_lcp(sa.sa[p], sa.sa[a[i]]);
p = a[i];
A.cut(h);
B.cut(h);
ans += B.sum;
A.push();
i++;
} else {
int h = p == -1 ? 0 : sa.get_lcp(sa.sa[p], sa.sa[b[j]]);
p = b[j];
A.cut(h);
B.cut(h);
ans += A.sum;
B.push();
j++;
}
}
printf("%lld\n", ans);
}
} | 23.475248 | 131 | 0.412273 | heiseish |
d097074d91e884566fb39e3e198fa2f261f1aca7 | 497 | cpp | C++ | boost.asio/chapter01/passive-socket/main.cpp | pvthuyet/books | bac5f754a68243e463ec7b0d93610be8807b31ac | [
"BSL-1.0"
] | null | null | null | boost.asio/chapter01/passive-socket/main.cpp | pvthuyet/books | bac5f754a68243e463ec7b0d93610be8807b31ac | [
"BSL-1.0"
] | null | null | null | boost.asio/chapter01/passive-socket/main.cpp | pvthuyet/books | bac5f754a68243e463ec7b0d93610be8807b31ac | [
"BSL-1.0"
] | null | null | null | #include <boost/asio.hpp>
#include <iostream>
int main()
{
namespace asio = boost::asio;
// step 1
asio::io_service ios;
// step 2
asio::ip::tcp protocal = asio::ip::tcp::v6();
// step 3
asio::ip::tcp::acceptor acceptor(ios);
boost::system::error_code ec;
acceptor.open(protocal, ec);
if (ec.value() != 0) {
std::cout << "Failed to open the acceptor socket! Error code = "
<< ec.value() << ". Message: " << ec.message() << std::endl;
return ec.value();
}
return EXIT_SUCCESS;
} | 23.666667 | 66 | 0.627767 | pvthuyet |
d09b2be2b7726c9cf8ff5138d01db8578843a47c | 3,509 | cpp | C++ | lib-input/src/buttonsadafruit.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | 5 | 2019-04-25T20:03:19.000Z | 2021-12-29T23:28:17.000Z | lib-input/src/buttonsadafruit.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | null | null | null | lib-input/src/buttonsadafruit.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | 1 | 2021-12-31T01:33:02.000Z | 2021-12-31T01:33:02.000Z | #if defined (RASPPI)
/**
* @file buttonsadafruit.cpp
*
*/
/* Copyright (C) 2017-2019 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* 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 <stdint.h>
#include <stdio.h>
#include "bcm2835.h"
#if defined(__linux__)
#else
#include "bcm2835_gpio.h"
#endif
#include "input.h"
#include "buttonsadafruit.h"
#define PIN_L RPI_V2_GPIO_P1_13 ///< BCM 27
#define PIN_R RPI_V2_GPIO_P1_16 ///< BCM 23
#define PIN_C RPI_V2_GPIO_P1_07 ///< BCM 4
#define PIN_U RPI_V2_GPIO_P1_11 ///< BCM 17
#define PIN_D RPI_V2_GPIO_P1_15 ///< BCM 22
#define PIN_A RPI_V2_GPIO_P1_29 ///< BCM 5
#define PIN_B RPI_V2_GPIO_P1_31 ///< BCM 6
#define MASK_GPLEV0 static_cast<uint32_t>((1 << PIN_L) | (1 << PIN_R) | (1 << PIN_C) | (1 << PIN_U) | (1 << PIN_D) | (1 << PIN_A) | (1 << PIN_B))
ButtonsAdafruit::ButtonsAdafruit(void): m_rMaskedBits(0), m_PrevChar(INPUT_KEY_NOT_DEFINED) {
}
ButtonsAdafruit::~ButtonsAdafruit(void) {
}
bool ButtonsAdafruit::Start(void) {
InitGpioPin(PIN_L);
InitGpioPin(PIN_R);
InitGpioPin(PIN_C);
InitGpioPin(PIN_U);
InitGpioPin(PIN_D);
InitGpioPin(PIN_A);
InitGpioPin(PIN_B);
return true;
}
bool ButtonsAdafruit::IsAvailable(void) {
#if defined(__linux__)
volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPLEV0/4;
const uint32_t reg = bcm2835_peri_read(paddr);
#else
__sync_synchronize();
const uint32_t reg = BCM2835_GPIO->GPLEV0;
#endif
m_rMaskedBits = ~reg & MASK_GPLEV0;
if (m_rMaskedBits != 0) {
return true;
}
m_PrevChar = INPUT_KEY_NOT_DEFINED;
return false;
}
int ButtonsAdafruit::GetChar(void) {
int ch = INPUT_KEY_NOT_DEFINED;
if ((m_rMaskedBits & (1 << PIN_L)) == (1 << PIN_L)) {
ch = INPUT_KEY_LEFT;
} else if ((m_rMaskedBits & (1 << PIN_R)) == (1 << PIN_R)) {
ch = INPUT_KEY_RIGHT;
} else if ((m_rMaskedBits & (1 << PIN_C)) == (1 << PIN_C)) {
ch = INPUT_KEY_ENTER;
} else if ((m_rMaskedBits & (1 << PIN_U)) == (1 << PIN_U)) {
ch = INPUT_KEY_UP;
} else if ((m_rMaskedBits & (1 << PIN_D)) == (1 << PIN_D)) {
ch = INPUT_KEY_DOWN;
} else if ((m_rMaskedBits & (1 << PIN_A)) == (1 << PIN_A)) {
ch = INPUT_KEY_ENTER;
} else if ((m_rMaskedBits & (1 << PIN_B)) == (1 << PIN_B)) {
ch = INPUT_KEY_ESC;
}
if (m_PrevChar == ch) {
return INPUT_KEY_NOT_DEFINED;
}
m_PrevChar = ch;
return ch;
}
void ButtonsAdafruit::InitGpioPin(const uint8_t nPin) {
bcm2835_gpio_fsel(nPin, BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_set_pud(nPin, BCM2835_GPIO_PUD_UP);
}
#endif
| 28.762295 | 147 | 0.708179 | rodb70 |
d09bf2248e5a222dabaf7e3d6e9a71116894d5de | 352 | cc | C++ | webkit/media/android/webmediaplayer_proxy_android.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 2 | 2020-06-10T07:15:26.000Z | 2020-12-13T19:44:12.000Z | webkit/media/android/webmediaplayer_proxy_android.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | webkit/media/android/webmediaplayer_proxy_android.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/media/android/webmediaplayer_proxy_android.h"
namespace webkit_media {
WebMediaPlayerProxyAndroid::~WebMediaPlayerProxyAndroid() {};
} // namespace webkit_media
| 29.333333 | 73 | 0.778409 | quisquous |
d09c65f9434d047f6393f2ab7424074d5f8682f2 | 30,055 | cpp | C++ | src/Button.cpp | cclark2a/SchmickleWorks | 6945cc443c1a65426770b11f0de1b44b5fdcbd85 | [
"Unlicense"
] | 15 | 2018-02-19T19:45:32.000Z | 2020-07-23T07:23:37.000Z | src/Button.cpp | cclark2a/SchmickleWorks | 6945cc443c1a65426770b11f0de1b44b5fdcbd85 | [
"Unlicense"
] | 24 | 2018-08-09T13:49:40.000Z | 2019-11-08T19:31:55.000Z | src/Button.cpp | cclark2a/SchmickleWorks | 6945cc443c1a65426770b11f0de1b44b5fdcbd85 | [
"Unlicense"
] | null | null | null | #include "Button.hpp"
#include "Display.hpp"
#include "Taker.hpp"
#include "Wheel.hpp"
#include "Widget.hpp"
// try to get rest working as well as note
void AdderButton::onDragEndPreamble(const event::DragEnd& e) {
// insertLoc, shiftTime set by caller
shiftLoc = insertLoc + 1;
startTime = this->ntw()->n().notes[insertLoc].startTime;
if (debugVerbose) DEBUG("insertLoc %u shiftLoc %u startTime %d", insertLoc, shiftLoc, startTime);
}
void AdderButton::onDragEnd(const event::DragEnd& e) {
auto ntw = this->ntw();
auto& n = ntw->n();
if (shiftTime) {
n.shift(shiftLoc, shiftTime, AddToChannels::all == addToChannels ?
ALL_CHANNELS : this->ntw()->selectChannels);
}
n.sort();
ntw->selectButton->setOff();
NoteTakerButton::onDragEnd(e);
ntw->invalAndPlay(Inval::cut);
ntw->setSelect(insertLoc, insertLoc + 1);
ntw->turnOffLEDButtons();
ntw->setWheelRange(); // range is larger
ntw->displayBuffer->redraw();
}
ButtonBuffer::ButtonBuffer(NoteTakerButton* button) {
fb = new FramebufferWidget();
fb->dirty = true;
this->addChild(fb);
fb->addChild(button);
}
template<class TButton>
std::string WidgetToolTip<TButton>::getDisplayValueString() {
if (!widget) {
return "!uninitialized";
}
if (defaultLabel.empty()) {
defaultLabel = label;
}
if (widget->ntw()->runButton->ledOn()) {
label = "Play";
return widget->runningTooltip();
} else {
label = defaultLabel;
}
return "";
}
template struct WidgetToolTip<CutButton>;
template struct WidgetToolTip<FileButton>;
template struct WidgetToolTip<InsertButton>;
template struct WidgetToolTip<KeyButton>;
template struct WidgetToolTip<PartButton>;
template struct WidgetToolTip<RestButton>;
template struct WidgetToolTip<SelectButton>;
template struct WidgetToolTip<SustainButton>;
template struct WidgetToolTip<SlotButton>;
template struct WidgetToolTip<TempoButton>;
template struct WidgetToolTip<TieButton>;
template struct WidgetToolTip<TimeButton>;
void CutButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 4 + af, 41 - af, ";", NULL);
}
void CutButton::getState() {
auto ntw = this->ntw();
if (ntw->runButton->ledOn()) {
state = State::running;
return;
}
if (ntw->fileButton->ledOn()) {
state = State::cutAll;
return;
}
if (ntw->partButton->ledOn()) {
state = State::cutPart;
return;
}
SelectButton* selectButton = ntw->selectButton;
if (selectButton->editStart()
&& (ntw->slotButton->ledOn() ? ntw->storage.saveZero : selectButton->saveZero)) {
state = State::clearClipboard;
return;
}
if (selectButton->editEnd()) {
state = State::cutToClipboard;
return;
}
state = selectButton->editStart() ? State::insertCutAndShift : State::cutAndShift;
}
void CutButton::onDragEnd(const rack::event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
this->getState();
auto ntw = this->ntw();
auto& n = ntw->n();
ntw->clipboardInvalid = true;
NoteTakerButton::onDragEnd(e);
if (State::cutAll == state) {
SCHMICKLE(!ntw->slotButton->ledOn());
n.selectStart = 0;
n.selectEnd = n.notes.size() - 1;
ntw->copyNotes(); // allows add to undo accidental cut / clear all
ntw->setScoreEmpty();
ntw->setSelectStart(n.atMidiTime(0));
ntw->selectButton->setSingle();
ntw->setWheelRange();
ntw->displayBuffer->redraw();
return;
}
if (State::cutPart == state) {
SCHMICKLE(!ntw->slotButton->ledOn());
n.selectStart = 0;
n.selectEnd = n.notes.size() - 1;
ntw->copySelectableNotes();
ntw->setSelectableScoreEmpty();
ntw->setSelectStart(n.atMidiTime(0));
ntw->setWheelRange();
ntw->displayBuffer->redraw();
return;
}
bool slotOn = ntw->slotButton->ledOn();
if (State::clearClipboard == state) {
ntw->clipboard.clear(slotOn);
return;
}
unsigned start = slotOn ? ntw->storage.slotStart : n.selectStart;
unsigned end = slotOn ? ntw->storage.slotEnd : n.selectEnd;
if (!slotOn && (!start || end <= 1)) {
DEBUG("*** selectButton should have been set to edit start, save zero");
_schmickled();
return;
}
if (State::insertCutAndShift != state) {
slotOn ? ntw->copySlots() : ntw->copyNotes();
}
if (slotOn) {
if (0 == start && ntw->storage.size() <= end) {
++start; // always leave one slot
}
if (start >= end) {
return;
}
ntw->storage.shiftSlots(start, end);
if (ntw->storage.size() <= start) {
--start; // move select to last remaining slot
}
ntw->storage.slotStart = start;
ntw->storage.slotEnd = start + 1;
} else {
int shiftTime = n.notes[start].startTime - n.notes[end].startTime;
if (State::cutToClipboard == state) {
// to do : insert a rest if existing notes do not include deleted span
shiftTime = 0;
} else {
SCHMICKLE(State::cutAndShift == state || State::insertCutAndShift == state);
}
// set selection to previous selectable note, or zero if none
int vWheel = (int) ntw->verticalWheel->getValue();
if (vWheel) {
float lo, hi;
ntw->verticalWheel->getLimits(&lo, &hi);
if (vWheel == (int) hi - 1) {
--vWheel;
}
}
if (vWheel) {
unsigned selStart = ntw->edit.voices[vWheel - 1];
ntw->setSelect(selStart, selStart + 1);
} else {
int wheel = ntw->noteToWheel(start);
unsigned previous = ntw->wheelToNote(std::max(0, wheel - 1));
ntw->setSelect(previous, previous < start ? start : previous + 1);
}
n.eraseNotes(start, end, ntw->selectChannels);
if (shiftTime) {
ntw->shiftNotes(start, shiftTime);
} else {
n.sort();
}
ntw->invalAndPlay(Inval::cut);
ntw->turnOffLEDButtons();
}
ntw->selectButton->setSingle();
// range is smaller
ntw->setWheelRange();
ntw->displayBuffer->redraw();
}
void EditButton::onDragStart(const event::DragStart& e) {
auto ntw = this->ntw();
if (ntw->runButton->ledOn()) {
return;
}
NoteTakerButton::onDragStart(e);
}
void EditLEDButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
NoteTakerButton::onDragEnd(e);
ntw->turnOffLEDButtons(this);
ntw->setWheelRange();
ntw->displayBuffer->redraw();
}
void FileButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditLEDButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 5 + af, 41 - af, ":", NULL);
}
// to do : change graphic on insert button to show what pressing the button will do
// distinguish : add one note after / add multiple notes after / add one note above /
// add multiple notes above
// also change tooltips to describe this in words
void InsertButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 8 + af, 41 - af, "H", NULL);
}
// allows tooltip to show what button is going to do without pressing it
void InsertButton::getState() {
auto ntw = this->ntw();
const auto& n = ntw->n();
if (ntw->runButton->ledOn()) {
state = State::running;
return;
}
auto selectButton = ntw->selectButton;
bool useClipboard = selectButton->ledOn();
if (ntw->slotButton->ledOn()) {
insertLoc = selectButton->editStart() ? ntw->storage.startToWheel() : ntw->storage.slotEnd;
state = useClipboard && !ntw->clipboard.playback.empty() ? State::clipboardShift :
State::dupShift;
return;
}
span.clear();
// all notes on pushed on span stack require note off to be added as well
lastEndTime = 0;
insertTime = 0;
if (!n.noteCount(ntw->selectChannels) && ntw->clipboard.notes.empty()) {
insertLoc = n.atMidiTime(0);
span.push_back(ntw->middleC());
Notes::AddNoteOff(span);
state = State::middleCShift;
return;
}
// select set to insert (start) or off:
// Insert loc is where the new note goes, but not when the new note goes;
// the new start time is 'last end time(insert loc)'
// select set to extend (end):
// Insert loc is select start; existing notes are not shifted, insert is transposed
bool insertInPlace = selectButton->editEnd();
unsigned iStart = n.selectStart;
if (!iStart) {
iStart = insertLoc = ntw->wheelToNote(1);
} else if (insertInPlace) {
insertLoc = n.selectStart;
} else {
insertLoc = n.selectEnd;
// A prior edit (e.g., changing a note duration) may invalidate using select end as the
// insert location. Use select end to determine the last active note to insert after,
// but not the location to insert after.
for (unsigned index = 0; index < n.selectEnd; ++index) {
const auto& note = n.notes[index];
if (note.isSelectable(ntw->selectChannels)) {
lastEndTime = std::max(lastEndTime, note.endTime());
insertLoc = n.selectEnd;
}
if (note.isNoteOrRest() && note.startTime >= lastEndTime && index < insertLoc) {
insertLoc = index;
}
}
}
while (NOTE_OFF == n.notes[insertLoc].type) {
++insertLoc;
}
insertTime = n.notes[insertLoc].startTime;
if (!insertInPlace) {
// insertLoc may be different channel, so can't use that start time by itself
// shift to selectStart time, but not less than previous end (if any) on same channel
while (insertTime < lastEndTime) {
SCHMICKLE(TRACK_END != n.notes[insertLoc].type);
++insertLoc;
SCHMICKLE(insertLoc < n.notes.size());
insertTime = n.notes[insertLoc].startTime;
}
}
if (!useClipboard || ntw->clipboard.notes.empty() || !ntw->extractClipboard(&span)) {
for (unsigned index = iStart; index < n.selectEnd; ++index) {
const auto& note = n.notes[index];
if (note.isSelectable(ntw->selectChannels)) { // use lambda for this pattern
span.push_back(note);
span.back().cache = nullptr;
}
}
state = insertInPlace ? State::dupInPlace : selectButton->editStart() ?
State::dupLeft : State::dupShift;
} else {
state = insertInPlace ? State::clipboardInPlace : State::clipboardShift;
}
if (span.empty() || (1 == span.size() && NOTE_ON != span[0].type) ||
(span[0].isSignature() && n.notes[insertLoc].isSignature())) {
span.clear();
state = insertInPlace ? State::dupInPlace : State::dupShift;
for (unsigned index = iStart; index < n.notes.size(); ++index) {
const auto& note = n.notes[index];
if (NOTE_ON == note.type && note.isSelectable(ntw->selectChannels)) {
span.push_back(note);
span.back().cache = nullptr;
break;
}
}
}
if (span.empty()) {
for (unsigned index = iStart; --index > 0; ) {
const auto& note = n.notes[index];
if (NOTE_ON == note.type && note.isSelectable(ntw->selectChannels)) {
span.push_back(note);
span.back().cache = nullptr;
break;
}
}
}
if (span.empty()) {
const DisplayNote& midC = ntw->middleC();
span.push_back(midC);
state = insertInPlace ? State::middleCInPlace : State::middleCShift;
}
if (1 == span.size()) {
Notes::AddNoteOff(span);
}
}
void InsertButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
this->getState();
auto ntw = this->ntw();
auto& n = ntw->n();
ntw->clipboardInvalid = true;
ntw->turnOffLEDButtons(nullptr, true); // turn off pitch, file, sustain, etc but not slot
if (debugVerbose) DEBUG("lastEndTime %d insertLoc %u", lastEndTime, insertLoc);
bool slotOn = ntw->slotButton->ledOn();
if (debugVerbose) DEBUG("insertTime %d clipboard size %u", insertTime,
slotOn ? ntw->clipboard.playback.size() : ntw->clipboard.notes.size());
vector<SlotPlay> pspan;
if (State::middleCShift != state) {
// select set to insert (start) or off:
// Insert loc is where the new note goes, but not when the new note goes;
// the new start time is 'last end time(insert loc)'
// select set to extend (end):
// Insert loc is select start; existing notes are not shifted, insert is transposed
if (state != State::clipboardInPlace && state != State::clipboardShift) {
if (debugVerbose) DEBUG(!n.selectStart ? "left of first note" :
"duplicate selection");
ntw->clipboard.clear(slotOn);
ntw->setClipboardLight();
if (slotOn) {
pspan.assign(ntw->storage.playback.begin() + ntw->storage.slotStart,
ntw->storage.playback.begin() + ntw->storage.slotEnd);
}
} else {
if (slotOn) {
pspan = ntw->clipboard.playback;
}
if (debugVerbose) slotOn ? DEBUG("clipboard to pspan (%u slots)", pspan.size()) :
DEBUG("clipboard to span (%u notes)", span.size());
}
}
// insertInPlace mode disabled for now, for several reasons
// it allows duplicating (a top note of) a phrase and transposing it, but the 'top note' part is buggy
// the result is a non-continuous selection -- currently that isn't supported
// it's an idea that is not uniformly supported: i.e., one can't copy and paste the top note of a phrase
// or copy from one part to another
// as mentioned, highest only is buggy and without it it would be odd to copy and transpose whole chords
bool insertInPlace = false && !slotOn && ntw->selectButton->editEnd();
unsigned insertSize = slotOn ? pspan.size() : span.size();
int shiftTime = 0;
if (insertInPlace) {
// not sure what I was thinking -- already have a way to add single notes to chord
// Notes::HighestOnly(span); // if edit end, remove all but highest note of chord
if (!n.transposeSpan(span)) {
DEBUG("** failed to transpose span");
return;
}
n.notes.insert(n.notes.begin() + insertLoc, span.begin(), span.end());
} else {
if (slotOn) {
ntw->storage.playback.insert(ntw->storage.playback.begin() + insertLoc, pspan.begin(),
pspan.end());
ntw->stageSlot(pspan[0].index);
} else {
int nextStart = ntw->nextStartTime(insertLoc);
if (Notes::ShiftNotes(span, 0, lastEndTime - span.front().startTime)) {
std::sort(span.begin(), span.end());
}
n.notes.insert(n.notes.begin() + insertLoc, span.begin(), span.end());
// include notes on other channels that fit within the start/end window
// shift by span duration less next start (if any) on same channel minus selectStart time
shiftTime = (lastEndTime - insertTime)
+ (Notes::LastEndTime(span) - span.front().startTime);
int availableTime = nextStart - insertTime;
if (debugVerbose) DEBUG("shift time %d available %d", shiftTime, availableTime);
shiftTime = std::max(0, shiftTime - availableTime);
}
if (debugVerbose) DEBUG("insertLoc=%u insertSize=%u shiftTime=%d selectStart=%u"
" selectEnd=%u",
insertLoc, insertSize, shiftTime, slotOn ? ntw->storage.slotStart : n.selectStart,
slotOn ? ntw->storage.slotEnd : n.selectEnd);
if (debugVerbose) ntw->debugDump(false, true);
}
ntw->selectButton->setOff();
ntw->insertFinal(shiftTime, insertLoc, insertSize);
NoteTakerButton::onDragEnd(e);
}
// insert key signature
void KeyButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
auto& n = ntw->n();
insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime);
if (n.insertContains(insertLoc, KEY_SIGNATURE)) {
return;
}
shiftTime = duration = 0;
onDragEndPreamble(e);
DisplayNote keySignature(KEY_SIGNATURE);
n.notes.insert(n.notes.begin() + insertLoc, keySignature);
shiftTime = duration = 0;
AdderButton::onDragEnd(e);
}
void KeyButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 6 + af, 33 - af, "#", NULL);
nvgText(vg, 10 + af, 41 - af, "$", NULL);
}
void NoteTakerButton::draw(const DrawArgs& args) {
if (false && debugVerbose) {
float t[6];
nvgCurrentTransform(args.vg, t);
if (memcmp(lastTransform, t, sizeof(lastTransform))) {
DEBUG("notetakerbutton xform %g %g %g %g %g %g", t[0], t[1], t[2], t[3], t[4], t[5]);
memcpy(lastTransform, t, sizeof(lastTransform));
this->fb()->dirty = true;
}
}
const int af = animationFrame;
auto ntw = this->ntw();
auto nt = ntw->nt();
if (!nt || slotNumber >= SLOT_COUNT) {
return;
}
auto runButton = ntw->runButton;
if (runButton->dynamicRunTimer >= nt->getRealSeconds()) {
this->fb()->dirty = true;
}
auto vg = args.vg;
int alpha = std::max(0, (int) (255 * (runButton->dynamicRunTimer - nt->getRealSeconds())
/ runButton->fadeDuration));
if (runButton->ledOn()) {
alpha = 255 - alpha;
}
runButton->dynamicRunAlpha = alpha;
if (ntw->storage.slots[slotNumber].n.isEmpty(ALL_CHANNELS)) {
alpha /= 3;
}
nvgFillColor(vg, nvgRGBA(0, 0, 0, alpha));
std::string label = std::to_string(slotNumber + 1);
nvgFontFaceId(vg, ntw->textFont());
nvgTextAlign(vg, NVG_ALIGN_CENTER);
nvgFontSize(vg, 18);
nvgText(vg, 10 + af, 32 - af, label.c_str(), NULL);
}
int NoteTakerButton::runAlpha() const {
return 255 - ntw()->runButton->dynamicRunAlpha;
}
bool NoteTakerButton::stageSlot(const event::DragEnd& e) {
if (e.button != GLFW_MOUSE_BUTTON_LEFT) {
return true;
}
auto ntw = this->ntw();
if (!ntw->runButton->ledOn()) {
return false;
}
if (ntw->storage.slots[slotNumber].n.isEmpty(ALL_CHANNELS)) {
return true;
}
ntw->stageSlot(slotNumber);
return true;
}
void PartButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditLEDButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 8 + af, 41 - af, "\"", NULL);
}
void PartButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
NoteTakerButton::onDragEnd(e);
auto ntw = this->ntw();
if (!ledOn()) {
this->onTurnOff();
} else if (ntw->selectButton->editEnd()) {
ntw->clipboardInvalid = true;
ntw->copySelectableNotes();
}
if (debugVerbose) DEBUG("part button onDragEnd ledOn %d part %d selectChannels %d unlocked %u",
this->ledOn(), ntw->horizontalWheel->part(), ntw->selectChannels, ntw->unlockedChannel());
ntw->turnOffLEDButtons(this);
// range is larger
ntw->setWheelRange();
ntw->displayBuffer->redraw();
}
void RestButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 36);
nvgText(vg, 8 + af, 41 - af, "t", NULL);
}
void RestButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
auto& n = ntw->n();
ntw->turnOffLEDButtons(); // turn off pitch, file, sustain, etc
if (!ntw->selectButton->editStart()) {
event::DragEnd e;
ntw->cutButton->onDragEnd(e);
if (debugVerbose) ntw->debugDump();
}
insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime);
onDragEndPreamble(e);
DisplayNote rest(REST_TYPE, startTime, n.ppq, (uint8_t) ntw->unlockedChannel());
shiftTime = rest.duration;
n.notes.insert(n.notes.begin() + insertLoc, rest);
AdderButton::onDragEnd(e);
}
void RunButton::onDragEnd(const event::DragEnd& e) {
if (e.button != GLFW_MOUSE_BUTTON_LEFT) {
return;
}
NoteTakerButton::onDragEnd(e);
auto ntw = this->ntw();
auto nt = ntw->nt();
if (!this->ledOn()) {
ntw->enableButtons();
dynamicRunAlpha = 255;
nt->requests.push(RequestType::resetPlayStart);
} else {
nt->requests.push(RequestType::resetAndPlay);
ntw->resetForPlay();
ntw->turnOffLEDButtons(this, true);
ntw->disableEmptyButtons();
dynamicRunAlpha = 0;
}
dynamicRunTimer = nt->getRealSeconds() + fadeDuration;
ntw->setWheelRange();
ntw->displayBuffer->redraw();
DEBUG("onDragEnd end af %d ledOn %d", animationFrame, ledOn());
}
// to do : change drawn graphic to show the mode? edit / insert / select ?
// (not crazy about this idea)
void SelectButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditLEDButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 4 + af, 41 - af, "<", NULL); // was \u00E0
}
void SelectButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
auto& n = ntw->n();
NoteTakerButton::onDragEnd(e);
bool slotOn = ntw->slotButton->ledOn();
auto& storage = ntw->storage;
if (this->isOff()) {
SCHMICKLE(!this->ledOn());
slotOn ? ntw->copySlots() : ntw->copySelectableNotes();
} else if (this->isSingle()) {
SCHMICKLE(this->ledOn());
if (slotOn) {
if (debugVerbose) DEBUG("isSingle pre storage saveZero=%d s=%d e=%d", storage.saveZero,
storage.slotStart, storage.slotEnd);
// to do : leave slot end alone, and only look at slot start in insertion mode?
storage.slotEnd = storage.slotStart + 1;
if (debugVerbose) DEBUG("isSingle post storage saveZero=%d s=%d e=%d", storage.saveZero,
storage.slotStart, storage.slotEnd);
} else {
if (ntw->edit.voice) {
ntw->nt()->requests.push(RequestType::invalidateVoiceCount);
ntw->edit.voice = false;
}
unsigned start = saveZero ? ntw->wheelToNote(0) : n.selectStart;
ntw->setSelect(start, n.nextAfter(start, 1));
}
} else {
SCHMICKLE(this->isExtend());
SCHMICKLE(this->ledOn());
if (slotOn) {
if (debugVerbose) DEBUG("isExtend pre storage saveZero=%d s=%d e=%d", storage.saveZero,
storage.slotStart, storage.slotEnd);
} else {
if (ntw->edit.voice) {
ntw->nt()->requests.push(RequestType::invalidateVoiceCount);
ntw->edit.voice = false;
}
if (!n.horizontalCount(ntw->selectChannels)) {
ntw->clipboard.notes.clear();
this->setState(State::single); // can't start selection if there's nothing to select
} else {
int wheelStart = ntw->noteToWheel(n.selectStart);
saveZero = !wheelStart;
int wheelIndex = std::max(1, wheelStart);
selStart = ntw->wheelToNote(wheelIndex);
SCHMICKLE(MIDI_HEADER != n.notes[selStart].type);
SCHMICKLE(TRACK_END != n.notes[selStart].type);
const auto& note = n.notes[selStart];
unsigned end = note.isSignature() ? selStart + 1 : n.nextAfter(selStart, 1);
ntw->setSelect(selStart, end);
}
}
}
ntw->setClipboardLight();
ntw->turnOffLEDButtons(this, true);
// if state is single, set to horz from -1 to size
ntw->setWheelRange();
ntw->displayBuffer->redraw();
}
// currently not called by anyone
#if 0
void SelectButton::setExtend() {
this->setState(State::extend);
fb()->dirty = true;
ntw()->setClipboardLight();
}
#endif
void SelectButton::setOff() {
saveZero = false;
this->setState(State::ledOff);
fb()->dirty = true;
ntw()->setClipboardLight();
}
void SelectButton::setSingle() {
auto ntw = this->ntw();
auto& n = ntw->n();
saveZero = !ntw->noteToWheel(n.selectStart);
this->setState(State::single);
fb()->dirty = true;
ntw->setClipboardLight();
}
void SlotButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditLEDButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 32);
nvgText(vg, 1.5 + af, 41 - af, "?", NULL);
}
void SustainButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditLEDButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 4 + af, 41 - af, "=", NULL);
}
void TempoButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
auto& n = ntw->n();
insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime);
if (n.insertContains(insertLoc, MIDI_TEMPO)) {
return;
}
shiftTime = duration = 0;
onDragEndPreamble(e);
DisplayNote tempo(MIDI_TEMPO, startTime);
n.notes.insert(n.notes.begin() + insertLoc, tempo);
shiftTime = duration = 0;
AdderButton::onDragEnd(e);
}
void TempoButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 5 + af, 41 - af, "@", NULL);
}
// to do : call body (minus inherited part) on json load to restore state?
void TieButton::onDragEnd(const event::DragEnd& e) {
// horz: no slur / original / all slur
// vert: no triplet / original / all triplet
// to do : if selection is too small to slur / trip, button should be disabled ?
auto ntw = this->ntw();
ntw->edit.clear();
auto& n = ntw->n();
ntw->edit.init(n, ntw->selectChannels);
setTie = n.slursOrTies(ntw->selectChannels, Notes::HowMany::set, &setSlur);
setTriplet = n.triplets(ntw->selectChannels, Notes::HowMany::set);
clearTie = n.slursOrTies(ntw->selectChannels, Notes::HowMany::clear, &clearSlur);
clearTriplet = n.triplets(ntw->selectChannels, Notes::HowMany::clear);
EditLEDButton::onDragEnd(e);
}
void TieButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 1 + af, 41 - af, ">", NULL);
}
// insert time signature
void TimeButton::onDragEnd(const event::DragEnd& e) {
if (this->stageSlot(e)) {
return;
}
auto ntw = this->ntw();
auto& n = ntw->n();
insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime);
if (n.insertContains(insertLoc, TIME_SIGNATURE)) {
return;
}
shiftTime = duration = 0;
onDragEndPreamble(e);
DisplayNote timeSignature(TIME_SIGNATURE, startTime);
n.notes.insert(n.notes.begin() + insertLoc, timeSignature);
shiftTime = duration = 0;
AdderButton::onDragEnd(e);
}
void TimeButton::draw(const DrawArgs& args) {
const int af = animationFrame;
EditButton::draw(args);
NVGcontext* vg = args.vg;
nvgFontFaceId(vg, ntw()->musicFont());
nvgTextAlign(vg, NVG_ALIGN_LEFT);
nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha()));
nvgFontSize(vg, 24);
nvgText(vg, 8 + af, 33 - af, "4", NULL);
nvgText(vg, 8 + af, 41 - af, "4", NULL);
}
| 35.950957 | 108 | 0.598669 | cclark2a |
d09d725432a318c583c8b59538636389100bc3c1 | 3,102 | cpp | C++ | Sources/Elastos/LibCore/src/elastos/net/SocketImpl.cpp | xiaoweiruby/Elastos.RT | 238e9b747f70fc129769ae7850def4362c43e443 | [
"Apache-2.0"
] | 1 | 2019-04-15T13:08:56.000Z | 2019-04-15T13:08:56.000Z | Sources/Elastos/LibCore/src/elastos/net/SocketImpl.cpp | xiaoweiruby/Elastos.RT | 238e9b747f70fc129769ae7850def4362c43e443 | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/elastos/net/SocketImpl.cpp | xiaoweiruby/Elastos.RT | 238e9b747f70fc129769ae7850def4362c43e443 | [
"Apache-2.0"
] | null | null | null | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "Elastos.CoreLibrary.IO.h"
#include "elastos/net/SocketImpl.h"
#include "elastos/core/StringUtils.h"
using Elastos::Core::StringUtils;
namespace Elastos {
namespace Net {
CAR_INTERFACE_IMPL(SocketImpl, Object, ISocketImpl, ISocketOptions)
SocketImpl::SocketImpl()
: mStreaming(TRUE)
, mPort(0)
, mLocalport(0)
{
}
ECode SocketImpl::GetFD(
/* [out] */ IFileDescriptor** fileDescriptor)
{
VALIDATE_NOT_NULL(fileDescriptor)
*fileDescriptor = mFd;
REFCOUNT_ADD(*fileDescriptor)
return NOERROR;
}
ECode SocketImpl::ToString(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
AutoPtr<IInetAddress> netadd;
GetInetAddress((IInetAddress**)&netadd);
String outstr;
IObject* o = (IObject*)netadd->Probe(EIID_IObject);
o->ToString(&outstr);
*str = String("Socket[address=") + outstr +
String(",port=") + StringUtils::ToString(mPort) +
String(",localPort=") + StringUtils::ToString(mLocalport) + String("]");
return NOERROR;
}
ECode SocketImpl::GetFileDescriptor(
/* [out] */ IFileDescriptor** fileDescriptor)
{
VALIDATE_NOT_NULL(fileDescriptor);
*fileDescriptor = mFd;
REFCOUNT_ADD(*fileDescriptor);
return NOERROR;
}
ECode SocketImpl::GetInetAddress(
/* [out] */ IInetAddress** netAddress)
{
VALIDATE_NOT_NULL(netAddress);
*netAddress = mAddress;
REFCOUNT_ADD(*netAddress);
return NOERROR;
}
ECode SocketImpl::GetLocalPort(
/* [out] */ Int32* num)
{
VALIDATE_NOT_NULL(num);
*num = mLocalport;
return NOERROR;
}
ECode SocketImpl::GetPort(
/* [out] */ Int32* port)
{
VALIDATE_NOT_NULL(port);
*port = mPort;
return NOERROR;
}
ECode SocketImpl::ShutdownInput()
{
// throw new IOException("Method has not been implemented");
return E_IO_EXCEPTION;
}
ECode SocketImpl::ShutdownOutput()
{
// throw new IOException("Method has not been implemented");
return E_IO_EXCEPTION;
}
ECode SocketImpl::SupportsUrgentData(
/* [out] */ Boolean* isSupports)
{
VALIDATE_NOT_NULL(isSupports);
*isSupports = FALSE;
return NOERROR;
}
ECode SocketImpl::SetPerformancePreferences(
/* [in] */ Int32 connectionTime,
/* [in] */ Int32 latency,
/* [in] */ Int32 bandwidth)
{
return NOERROR;
}
} // namespace Net
} // namespace Elastos
| 23.861538 | 84 | 0.652482 | xiaoweiruby |
d09e4be5225b159e0973d74a71e0c31dd158ee78 | 1,854 | tpp | C++ | rb_tree/includes/btree_delete.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | 1 | 2022-03-02T15:14:16.000Z | 2022-03-02T15:14:16.000Z | rb_tree/includes/btree_delete.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | 73 | 2021-12-11T18:54:53.000Z | 2022-03-28T01:32:52.000Z | rb_tree/includes/btree_delete.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | null | null | null |
#ifndef BTREE_DELETE_TPP
#define BTREE_DELETE_TPP
#include "btree.tpp"
#include "btree_create_node.tpp"
#include "btree_delete_rules.tpp"
template <class T>
ft::btree<T> * find_neighbor(ft::btree<T> *node)
{
if (!is_nil(node->left))
return (find_predecessor_below(node->left));
else
return (find_successor_below(node->right));
}
template <class T>
void replace_content(ft::btree<T> *node, ft::btree<T> *node_to_replace)
{
node->item = node_to_replace->item;
}
template <class T, class Alloc>
void delete_leaf(ft::btree<T> *leaf, Alloc alloc)
{
alloc.deallocate(leaf->right, 1);
alloc.deallocate(leaf->left, 1);
alloc.deallocate(leaf, 1);
}
template <class T, class Alloc>
void delete_node(ft::btree<T> *node, Alloc alloc)
{
check_delete_rules(node);
if (is_left_child(node->parent, node))
node->parent->left = create_nil_node(node->parent, alloc);
else
node->parent->right = create_nil_node(node->parent, alloc);
delete_leaf(node, alloc);
}
template <class T, class Alloc>
void btree_delete_recursive(ft::btree<T> *node_to_delete, Alloc alloc)
{
if (is_leaf(node_to_delete))
return (delete_node(node_to_delete, alloc));
ft::btree<T> * node_to_replace = find_neighbor(node_to_delete);
replace_content(node_to_delete, node_to_replace);
return (btree_delete_recursive(node_to_replace, alloc));
}
template <class T, class Compare, class Alloc>
T * btree_delete(ft::btree<T> **root, T data_ref, Compare compare, Alloc alloc)
{
ft::btree<T> * node_to_delete = btree_search_node<T>(*root, data_ref, compare);
if (!node_to_delete)
return (NULL);
const T * item_to_return = node_to_delete->item;
if (is_last_node(node_to_delete))
{
delete_leaf(node_to_delete, alloc);
*root = NULL;
}
else
{
btree_delete_recursive(node_to_delete, alloc);
update_root(root);
}
return (const_cast<T *>(item_to_return));
}
#endif
| 25.054054 | 80 | 0.735707 | paulahemsi |
d09fcd04433388bfb34be49d83d963aee00c6a5c | 634 | cpp | C++ | leetcode/two_sum/leetcode_804.cpp | HuangJingGitHub/PracMakePert_C | 94e570c55d9e391913ccd9c5c72026ab926809b2 | [
"Apache-2.0"
] | 1 | 2019-10-17T03:13:29.000Z | 2019-10-17T03:13:29.000Z | leetcode/two_sum/leetcode_804.cpp | HuangJingGitHub/PracMakePert_C-Cpp | 6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5 | [
"Apache-2.0"
] | null | null | null | leetcode/two_sum/leetcode_804.cpp | HuangJingGitHub/PracMakePert_C-Cpp | 6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
vector<string> dic{".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
unordered_set<string> uniqueMorseResp;
for (auto w:words){
string temp = "";
for (auto c:w)
temp += dic[c - 'a'];
uniqueMorseResp.emplace(temp);
}
return uniqueMorseResp.size();
}
};
| 31.7 | 70 | 0.324921 | HuangJingGitHub |
d0a12678e771de4ce7b18142dfdb630718a0f0ba | 466 | hpp | C++ | transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | null | null | null | transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | null | null | null | transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | 1 | 2021-10-14T06:37:36.000Z | 2021-10-14T06:37:36.000Z | #ifndef TRANSMISSION_INTERFACE_EXTENSIONS_COMMON_NAMESPACES_HPP
#define TRANSMISSION_INTERFACE_EXTENSIONS_COMMON_NAMESPACES_HPP
namespace hardware_interface {}
namespace hardware_interface_extensions {}
namespace transmission_interface {}
namespace transmission_interface_extensions {
namespace hi = hardware_interface;
namespace hie = hardware_interface_extensions;
namespace ti = transmission_interface;
} // namespace transmission_interface_extensions
#endif | 29.125 | 63 | 0.879828 | smilerobotics |
d0a285f3f8a5506ab698fd1dc084435df009c5ba | 1,457 | cpp | C++ | slUtil.cpp | FigBug/slCommon | b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b | [
"MIT"
] | null | null | null | slUtil.cpp | FigBug/slCommon | b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b | [
"MIT"
] | null | null | null | slUtil.cpp | FigBug/slCommon | b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b | [
"MIT"
] | null | null | null | #include "slUtil.h"
LevelTracker::LevelTracker (float decayPerSecond) : decayRate (decayPerSecond)
{
}
void LevelTracker::trackBuffer (AudioSampleBuffer& buffer)
{
for (int i = 0; i < buffer.getNumChannels(); i++)
trackBuffer (buffer.getReadPointer (0), buffer.getNumSamples());
}
void LevelTracker::trackBuffer (const float* buffer, int numSamples)
{
Range<float> range = FloatVectorOperations::findMinAndMax (buffer, numSamples);
float v1 = std::fabs (range.getStart());
float v2 = std::fabs (range.getEnd());
float peakDB = Decibels::gainToDecibels (jmax (v1, v2));
if (peakDB > 0)
clip = true;
const float time = (Time::getMillisecondCounter() / 1000.0f);
if (getLevel() < peakDB)
{
peakLevel = peakDB;
peakTime = time;
}
}
float LevelTracker::getLevel()
{
const float hold = 50.0f / 1000.0f;
const float elapsed = (Time::getMillisecondCounter() / 1000.0f) - peakTime;
if (elapsed < hold)
return peakLevel;
return peakLevel - (decayRate * (elapsed - hold));
}
int versionStringToInt (const String& versionString)
{
StringArray parts;
parts.addTokens (versionString, ".", "");
parts.trim();
parts.removeEmptyStrings();
int res = 0;
for (auto part : parts)
res = (res << 8) + part.getIntValue();
return res;
}
| 24.694915 | 84 | 0.59849 | FigBug |
d0a2bdd276f46fbf2b4a70e42e3ec1638d8e9b3b | 4,013 | cpp | C++ | CS2370/Labs/LabVectorT/Vector.cpp | Davidjbennett/DavidBennett.github.io | 09a2652b7ace8741bf23c6432abd58ee790b9f0c | [
"MIT"
] | 3 | 2021-05-18T16:17:29.000Z | 2022-01-20T15:46:59.000Z | CS2370/Labs/LabVectorT/Vector.cpp | Davidjbennett/DavidBennett | 09a2652b7ace8741bf23c6432abd58ee790b9f0c | [
"MIT"
] | null | null | null | CS2370/Labs/LabVectorT/Vector.cpp | Davidjbennett/DavidBennett | 09a2652b7ace8741bf23c6432abd58ee790b9f0c | [
"MIT"
] | null | null | null | #include "Vector.h"
#include "test.h"
#include <iostream>
#include <cstddef>
#include <stdexcept>
using namespace std;
using std::size_t;
// constructor
Vector::Vector(){
data_ptr = new int[CHUNK];
capacity = CHUNK;
n_elems = 0;
}
// copy constructor
Vector::Vector(const Vector &v){
this->capacity = v.capacity;
this->data_ptr = new int[this->capacity];
this->n_elems = v.n_elems;
for(int i = 0;i<v.n_elems;i++){
this->data_ptr[i] = v.at(i);
}
}
//equal overload
Vector& Vector::operator=(const Vector &v){
this->capacity = v.capacity;
this->data_ptr = new int[this->capacity];
this->n_elems = v.n_elems;
for(int i = 0;i<v.n_elems;i++){
this->data_ptr[i] = v.at(i);
}
return (*this);
}
//destructor
Vector::~Vector(){
delete[] data_ptr;
}
//insert int at pos 0
int Vector::front() const{
if (this-> n_elems == 0){
throw range_error("out of bounds");
}else {
return this->data_ptr[0];
}
}
// returns last element on array
int Vector::back() const{
if (this->n_elems == 0){
throw range_error("out of bounds");
}else{
return this->data_ptr[n_elems-1];
}
}
// returns element at pos x
int Vector::at(size_t pos) const{
if (this->n_elems == 0){
throw range_error("out of bounds");
}else if (pos <= 0 && pos >= this->n_elems){
throw range_error("out of bounds");
}else{
return this->data_ptr[pos];
}
}
//returns size of vector
size_t Vector::size() const{
return (size_t)this->n_elems;
}
// returns bool on if vector is empty or not
bool Vector::empty() const{
return this->n_elems == 0;
}
// returns vector at pos x with no bound checks
int& Vector::operator[](size_t pos){
return this->data_ptr[pos];
}
//appends new element to end of arr
void Vector::push_back(int item){
if (this->n_elems < this->capacity){
this->data_ptr[n_elems++] = item;
}else{
this->capacity = ((this->capacity*16)/10);
int* temp = new int[this->capacity];
for (int x =0; x < this->n_elems; x++){
temp[x] = data_ptr[x];
}
delete[] this->data_ptr;
this->data_ptr = temp;
this->data_ptr[n_elems] = item;
n_elems++;
}
}
void Vector::pop_back(){
if(n_elems==0){
throw range_error("Out of bound");
}else{
n_elems--;
}
}
// erases item at pos x and fills in
void Vector::erase(size_t pos){
if (pos < this->n_elems){
for(int x = pos; x < this->n_elems; x++){
data_ptr[x] = data_ptr[x+1];
}
n_elems--;
}else{
throw range_error("out of bounds");
}
}
// moves elements at x and up 1 right of pos x and inserts element at pos x
void Vector::insert(size_t pos, int item){
if(capacity==n_elems){
capacity = (capacity*16)/10;
int* temp_ptr = new int[capacity];
for(int i=0;i<n_elems;i++){
temp_ptr[i] = data_ptr[i];
}
delete[] data_ptr;
data_ptr = temp_ptr;
}
for(int i=n_elems;i>pos;i--){
data_ptr[i] = data_ptr[i-1];
}
data_ptr[pos] = item;
n_elems++;
}
// clears the vector elements
void Vector::clear(){
delete[] data_ptr;
data_ptr = new int[CHUNK];
capacity = CHUNK;
n_elems = 0;
}
// returns pointer on first element
int* Vector::begin(){
if(n_elems==0)return NULL;
return &data_ptr[0];
}
// returns pointer to last element
int* Vector::end(){
if(n_elems==0)return NULL;
return &data_ptr[n_elems];
}
// == operator overload
bool Vector::operator==(const Vector &v) const{
if(this->capacity!=v.capacity){
return false;
}
if(this->n_elems!=v.n_elems){
return false;
}
for(int i=0;i<n_elems;i++){
if(this->data_ptr[i]!=v.data_ptr[i]){
return false;
}
}
return true;
}
// != operator overload
bool Vector::operator!=(const Vector &v) const{
return !(operator==(v));
}
| 23.605882 | 75 | 0.58161 | Davidjbennett |
d0a3baceee4f28ff0f39f64bf7f5268ee7ac5a7c | 28 | cpp | C++ | PictureFrame/src/propertyhelper.cpp | taiko000/PictureFrame | 9895f46b64f365618caa968d5fa1769e4c53d90b | [
"Apache-2.0"
] | null | null | null | PictureFrame/src/propertyhelper.cpp | taiko000/PictureFrame | 9895f46b64f365618caa968d5fa1769e4c53d90b | [
"Apache-2.0"
] | null | null | null | PictureFrame/src/propertyhelper.cpp | taiko000/PictureFrame | 9895f46b64f365618caa968d5fa1769e4c53d90b | [
"Apache-2.0"
] | null | null | null | #include "propertyhelper.h"
| 14 | 27 | 0.785714 | taiko000 |
d0a4d865cadc72f67e6388db2cc36154818ba265 | 12,460 | cpp | C++ | clf_object_recognition_merger/src/object_merger.cpp | CentralLabFacilities/clf_object_recognition | f4579980682687c3706c1dded8a255903795097d | [
"Apache-2.0"
] | 2 | 2019-01-22T05:00:05.000Z | 2019-01-22T05:00:20.000Z | clf_object_recognition_merger/src/object_merger.cpp | CentralLabFacilities/clf_object_recognition | f4579980682687c3706c1dded8a255903795097d | [
"Apache-2.0"
] | null | null | null | clf_object_recognition_merger/src/object_merger.cpp | CentralLabFacilities/clf_object_recognition | f4579980682687c3706c1dded8a255903795097d | [
"Apache-2.0"
] | null | null | null | // ros
#include <ros/ros.h>
// msg
#include <vision_msgs/Detection3D.h>
#include <vision_msgs/Detection3DArray.h>
#include <vision_msgs/Detection2D.h>
#include <vision_msgs/Detection2DArray.h>
#include <vision_msgs/ObjectHypothesisWithPose.h>
// srv
#include <clf_object_recognition_msgs/Detect3D.h>
#include <clf_object_recognition_msgs/Detect2D.h>
// opencv
#include <cv_bridge/cv_bridge.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "clf_object_recognition_merger/oobb_calculate.h"
// ros
ros::NodeHandle* nh;
ros::ServiceClient segmentationClient;
ros::ServiceClient detection2DClient;
// TODO: read as param
bool visualize = false;
double threshold = 0.3; // threshold for matching boxes, TODO: find appropriate value
void fixBoxes(std::vector<vision_msgs::Detection3D>& detections3D)
{
// ROS_INFO_STREAM("calculate oobbs");
for (auto& detection : detections3D)
{
auto newbox = OOBB_Calculate::calculate(detection.source_cloud);
// ROS_INFO_STREAM("BOX PRE: " << detection.bbox );
// ROS_INFO_STREAM("BOX POST: " << newbox );
detection.bbox = newbox;
}
}
vision_msgs::BoundingBox2D bbox3Dto2D(const vision_msgs::BoundingBox3D bbox3D) {
vision_msgs::BoundingBox2D estimatedBbox2D;
// shift from origin from image center to upper left corner
estimatedBbox2D.center.x = bbox3D.center.position.x / bbox3D.center.position.z + 0.5;
estimatedBbox2D.center.y = bbox3D.center.position.y / bbox3D.center.position.z + 0.5;
estimatedBbox2D.size_x = bbox3D.size.x / bbox3D.center.position.z;
estimatedBbox2D.size_y = bbox3D.size.y / bbox3D.center.position.z;
// estimated bboxes might be too large for the image: check and resize
if ((estimatedBbox2D.center.x + estimatedBbox2D.size_x / 2) > 1.0)
{
// resize x dimension
double x_max = estimatedBbox2D.center.x + estimatedBbox2D.size_x / 2;
double diff = x_max - 1.0;
estimatedBbox2D.size_x = estimatedBbox2D.size_x - diff;
estimatedBbox2D.center.x = estimatedBbox2D.center.x - diff / 2;
}
if ((estimatedBbox2D.center.x - estimatedBbox2D.size_x / 2) < 0.0)
{
// resize x dimension
double x_min = estimatedBbox2D.center.x - estimatedBbox2D.size_x / 2;
double diff = -x_min;
estimatedBbox2D.size_x = estimatedBbox2D.size_x - diff;
estimatedBbox2D.center.x = estimatedBbox2D.center.x + diff / 2;
}
if ((estimatedBbox2D.center.y + estimatedBbox2D.size_y / 2) > 1.0)
{
// resize y dimension
double y_max = estimatedBbox2D.center.y + estimatedBbox2D.size_y / 2;
double diff = y_max - 1.0;
estimatedBbox2D.size_y = estimatedBbox2D.size_y - diff;
estimatedBbox2D.center.y = estimatedBbox2D.center.y - diff / 2;
}
if ((estimatedBbox2D.center.y - estimatedBbox2D.size_y / 2) < 0.0)
{
// resize y dimension
double y_min = estimatedBbox2D.center.y - estimatedBbox2D.size_y / 2;
double diff = -y_min;
estimatedBbox2D.size_y = estimatedBbox2D.size_y - diff;
estimatedBbox2D.center.y = estimatedBbox2D.center.y + diff / 2;
}
return estimatedBbox2D;
}
/*vision_msgs::BoundingBox2D bbox3Dto2Dv2(const vision_msgs::BoundingBox3D bbox3D) {
vision_msgs::BoundingBox2D estimatedBbox2D;
float xmin=cam_image.width, ymin=cam_image.height, xmax=0.0, ymax=0.0;
//Iterate through all 8 edges of the bounding box, project them on the camera image, and find a 2D box that includes them all.
for(int k=-1; k<=1; k+=2) {
for(int l=-1; l<=1; l+=2) {
for(int m=-1; m<=1; m+=2) {
float imx, imy;
tf2::Vector3 vec(k*bbox3D.size.x/2.0, l*bbox3D.size.y/2.0, m*bbox3D.size.z/2.0), vec2(bbox3D.center.position.x, bbox3D.center.position.y, bbox3D.center.position.z);
tf2::Quaternion rot;
tf2::fromMsg(bbox3D.center.orientation, rot);
tf2::Transform trans(rot);
vec=trans*vec;
vec+=vec2;
imx=535.0*vec.x()/vec.z()+319.0;//TODO get camera matrix from /xtion/rgb/camera_info-topic
imy=535.0*vec.y()/vec.z()+253.0;
if(imx<xmin) xmin=imx;
if(imx>xmax) xmax=imx;
if(imy<ymin) ymin=imy;
if(imy>ymax) ymax=imy;
}
}
}
if(xmin<0.0) xmin=0.0;
if(ymin<0.0) ymin=0.0;
if(xmax>cam_image.width) xmax=cam_image.width;
if(ymax>cam_image.height) ymax=cam_image.height;
estimatedBbox2D.center.x=(xmin+xmax)/2.0;
estimatedBbox2D.center.y=(ymin+ymax)/2.0;
estimatedBbox2D.size_x=xmax-xmin;
estimatedBbox2D.size_y=ymax-ymin;
return estimatedBbox2D;
}*/
/* this service provides a list of detections with hypothesis (id, score), 3d boundingbox and pointcloud
by merging 2d and 3d detections */
bool detectObjectsCallback(clf_object_recognition_msgs::Detect3D::Request& req,
clf_object_recognition_msgs::Detect3D::Response& res)
{
// call segmentation (3d)
clf_object_recognition_msgs::Detect3D segmentCall;
segmentationClient.call(segmentCall);
std::vector<vision_msgs::Detection3D> detections3D = segmentCall.response.detections;
ROS_INFO_STREAM("segmented " << detections3D.size() << " objects");
// call object detection (2d)
clf_object_recognition_msgs::Detect2D detect2DCall;
detection2DClient.call(detect2DCall);
std::vector<vision_msgs::Detection2D> detections2D = detect2DCall.response.detections;
ROS_INFO_STREAM("detected " << detections2D.size() << " objects in 2d");
if (detections2D.size() == 0)
{
ROS_INFO_STREAM("no detections in 2d image, return 3d detections");
fixBoxes(detections3D);
res.detections = detections3D;
return true;
}
if (detections3D.size() == 0)
{
ROS_INFO_STREAM("no object were segmented, convert 2d detections and return");
for (int i = 0; i < detections2D.size(); i++)
{
vision_msgs::Detection3D detection;
detection.results = detections2D.at(i).results;
detections3D.push_back(detection);
}
res.detections = detections3D;
return true;
}
double likelihood[detections3D.size()][detections2D.size()];
std::vector<vision_msgs::BoundingBox2D> estimatedBboxes;
// compare 3d and 2d bboxes and set likelihood
for (int i = 0; i < detections3D.size(); i++)
{
vision_msgs::BoundingBox3D bbox3D = detections3D.at(i).bbox; // in camera frame
vision_msgs::BoundingBox2D estimatedBbox2D=bbox3Dto2D(bbox3D);
// keep list for visualization
estimatedBboxes.push_back(estimatedBbox2D);
for (int j = 0; j < detections2D.size(); j++)
{
// compare bbox2D and estimatedBbox2D
vision_msgs::BoundingBox2D bbox2D = detections2D.at(j).bbox;
// likelihood is area of intersection / area of union
double x1 = (bbox2D.center.x - bbox2D.size_x / 2.0);
double y1 = (bbox2D.center.y - bbox2D.size_y / 2.0);
double x2 = (bbox2D.center.x + bbox2D.size_x / 2.0);
double y2 = (bbox2D.center.y + bbox2D.size_y / 2.0);
double x1_est = (estimatedBbox2D.center.x - estimatedBbox2D.size_x / 2.0);
double y1_est = (estimatedBbox2D.center.y - estimatedBbox2D.size_y / 2.0);
double x2_est = (estimatedBbox2D.center.x + estimatedBbox2D.size_x / 2.0);
double y2_est = (estimatedBbox2D.center.y + estimatedBbox2D.size_y / 2.0);
double x_min = std::max(x1_est, x1);
double y_min = std::max(y1_est, y1);
double x_max = std::min(x2_est, x2);
double y_max = std::min(y2_est, y2);
double area_of_intersection = std::max((x_max - x_min), 0.0) * std::max((y_max - y_min), 0.0);
double area_est_box = estimatedBbox2D.size_x * estimatedBbox2D.size_y;
double area_box = bbox2D.size_x * bbox2D.size_y;
double area_of_union =
area_est_box + area_box - area_of_intersection; // assume the detected and estimated box cannot be 0
likelihood[i][j] = area_of_intersection / area_of_union;
ROS_INFO_STREAM("(" << i << "," << j << ") likelihood " << likelihood[i][j]);
}
}
// keep track of merged 2d detections
std::vector<bool> mergedDetection2D;
for (int j = 0; j < detections2D.size(); j++)
{
mergedDetection2D.push_back(false);
}
// check which 2d and 3d detections are matching
for (int i = 0; i < detections3D.size(); i++)
{
double maxLikelihood = 0.0;
int index = -1;
for (int j = 0; j < detections2D.size(); j++)
{
if (likelihood[i][j] > maxLikelihood && likelihood[i][j] > threshold)
{
maxLikelihood = likelihood[i][j];
index = j;
}
}
if (index != -1)
{
ROS_INFO_STREAM("matching boxes for 3D no. " << i << " and 2D no. " << index);
// set hypotheses of detection 3d with corresponding 2d detection
detections3D.at(i).results = detections2D.at(index).results;
// TODO: set pose and covariance?
// remember that 2d detection was merged
mergedDetection2D.at(index) = true;
}
}
// add unmerged detections2d to detection3d list without pointcloud and 3d bbox
for (int i = 0; i < mergedDetection2D.size(); i++)
{
if (!mergedDetection2D.at(i))
{
vision_msgs::Detection3D detection;
detection.results = detections2D.at(i).results;
detections3D.push_back(detection);
}
}
// visualize segmented boxes in 2d image
if (visualize)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
// assume all detections have the same source image
cv_ptr = cv_bridge::toCvCopy(detections2D.at(0).source_img, sensor_msgs::image_encodings::BGR8);
// draw 3d results (red)
for (int i = 0; i < estimatedBboxes.size(); i++)
{
int width = cv_ptr->image.cols;
int height = cv_ptr->image.rows;
// estimated box in normalized coordinates
int x_min = (estimatedBboxes.at(i).center.x - estimatedBboxes.at(i).size_x / 2) * width;
int y_min = (estimatedBboxes.at(i).center.y - estimatedBboxes.at(i).size_y / 2) * height;
int x_max = (estimatedBboxes.at(i).center.x + estimatedBboxes.at(i).size_x / 2) * width;
int y_max = (estimatedBboxes.at(i).center.y + estimatedBboxes.at(i).size_y / 2) * height;
cv::rectangle(cv_ptr->image, cv::Point(x_min, y_min), cv::Point(x_max, y_max), CV_RGB(255, 0, 0));
cv::putText(cv_ptr->image, std::to_string(i), cv::Point(x_min, y_min), 0, 1.0, CV_RGB(255, 0, 0));
}
// draw 2d results (green)
for (int i = 0; i < detections2D.size(); i++)
{
int width = cv_ptr->image.cols;
int height = cv_ptr->image.rows;
vision_msgs::BoundingBox2D bbox2D = detections2D.at(i).bbox;
// estimated box in normalized coordinates where (0,0) is the left upper corner
int x_min = (bbox2D.center.x - bbox2D.size_x / 2) * width;
int y_min = (bbox2D.center.y - bbox2D.size_y / 2) * height;
int x_max = (bbox2D.center.x + bbox2D.size_x / 2) * width;
int y_max = (bbox2D.center.y + bbox2D.size_y / 2) * height;
cv::rectangle(cv_ptr->image, cv::Point(x_min, y_min), cv::Point(x_max, y_max), CV_RGB(0, 255, 0));
cv::putText(cv_ptr->image, std::to_string(i), cv::Point(x_min, y_min), 0, 1.0, CV_RGB(0, 255, 0));
}
cv::imshow("OPENCV_WINDOW", cv_ptr->image);
cv::waitKey(0);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
}
}
fixBoxes(detections3D);
res.detections = detections3D;
return true;
}
int main(int argc, char* argv[])
{
ros::init(argc, argv, "object_merger");
nh = new ros::NodeHandle("~");
ros::ServiceServer objectDetectionService = nh->advertiseService("detect_objects", detectObjectsCallback);
auto srv_seg = "/segment";
auto srv_detect = "/detect";
ROS_INFO_STREAM("waiting for service: " << srv_seg);
ros::service::waitForService(srv_seg, -1);
ROS_INFO_STREAM("waiting for service: " << srv_detect);
ros::service::waitForService(srv_detect, -1);
segmentationClient = nh->serviceClient<clf_object_recognition_msgs::Detect3D>(srv_seg);
detection2DClient = nh->serviceClient<clf_object_recognition_msgs::Detect2D>(srv_detect);
nh->getParam("show_image", visualize);
nh->getParam("threshold", threshold);
ROS_INFO_STREAM("show images: " << visualize);
ROS_INFO_STREAM("threshold: " << threshold);
ros::spin();
return 0;
}
| 38.220859 | 180 | 0.662119 | CentralLabFacilities |
d0a5cbdbef2939103c237028f888b0bd3fe9c230 | 10,566 | hpp | C++ | generic_ext/comm_tool_scatter.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | generic_ext/comm_tool_scatter.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | generic_ext/comm_tool_scatter.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | /**************************************************************************************************/
/**
* @file comm_tool_scatter.hpp
* @brief STL container wrapper for PS::Comm::scatter()
*/
/**************************************************************************************************/
#pragma once
#include <cassert>
#include <vector>
#include <string>
#include <tuple>
#include <utility>
#include <unordered_map>
#include <particle_simulator.hpp>
#include "comm_tool_SerDes.hpp"
namespace COMM_TOOL {
//=====================
// wrapper functions
//=====================
/**
* @brief wrapper for static size class.
* @param[in] send_vec send target.
* MUST NOT contain pointer member.
* @param[out] recv_data recieve data.
* @details send_vec[i] is send data to process rank i.
*/
template <class T>
void scatter(const std::vector<T> &send_vec,
T &recv_data,
const PS::S32 root ,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<T>>" << std::endl;
#endif
const int n_proc = PS::Comm::getNumberOfProc();
assert(send_vec.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Scatter(&send_vec[0], 1, PS::GetDataType<T>(),
&recv_data , 1, PS::GetDataType<T>(),
root,
comm);
#else
recv_data = send_vec[0];
#endif
}
/**
* @brief specialization for std::vector<T>.
* @param[in] send_vec_vec send target.
* MUST NOT contain pointer member.
* @param[out] recv_vec recieve data.
* @details send_vec_vec[i] is send data to process rank i.
*/
template <class T>
void scatter(const std::vector<std::vector<T>> &send_vec_vec,
std::vector<T> &recv_vec,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<T>>>" << std::endl;
#endif
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
assert(send_vec_vec.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
std::vector<PS::S32> n_send;
n_send.resize(n_proc);
for(PS::S32 i=0; i<n_proc; ++i){
n_send[i] = send_vec_vec[i].size();
}
PS::S32 n_recv;
scatter(n_send, n_recv, root);
recv_vec.resize(n_recv);
std::vector<T> send_data;
std::vector<PS::S32> n_send_disp;
serialize_vector_vector(send_vec_vec, send_data, n_send_disp);
MPI_Scatterv(&send_data[0], &n_send[0], &n_send_disp[0], PS::GetDataType<T>(),
&recv_vec[0] , n_recv , PS::GetDataType<T>(),
root,
comm);
#else
recv_vec.resize(1);
recv_vec[0] = send_vec_vec[0];
#endif
}
/**
* @brief specialization for std::string.
* @param[in] send_vec_str send target.
* @param[out] recv_str recieve data.
* @details send_vec_str[i] is send data to process rank i.
*/
void scatter(const std::vector<std::string> &send_vec_str,
std::string &recv_str,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::string>>>" << std::endl;
#endif
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
assert(send_vec_str.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
std::vector<std::vector<char>> send_vec_vec_char;
std::vector<char> recv_vec_char;
send_vec_vec_char.resize(n_proc);
for(PS::S32 i=0; i<n_proc; ++i){
serialize_string(send_vec_str[i], send_vec_vec_char[i]);
}
scatter(send_vec_vec_char, recv_vec_char, root, comm);
deserialize_string(recv_vec_char, recv_str);
}
/**
* @brief specialization for std::vector<std::string>.
* @param[in] send_vec_vec_str send target.
* @param[out] recv_vec_str recieve data.
* @details send_vec_vec_str[i] is send data to process rank i.
*/
void scatter(const std::vector<std::vector<std::string>> &send_vec_vec_str,
std::vector<std::string> &recv_vec_str,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::std::vector<vector<std::string>>>" << std::endl;
#endif
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
assert(send_vec_vec_str.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
std::vector<std::vector<char>> send_vec_vec_char;
std::vector<char> recv_vec_char;
send_vec_vec_char.resize(n_proc);
for(PS::S32 i=0; i<n_proc; ++i){
serialize_vector_string(send_vec_vec_str[i], send_vec_vec_char[i]);
}
scatter(send_vec_vec_char, recv_vec_char, root, comm);
deserialize_vector_string(recv_vec_char, recv_vec_str);
}
/**
* @brief specialization for std::vector<std::vector<T>>.
* @param[in] send_vec_vv send target.
* MUST NOT contain pointer member.
* @param[out] recv_vec_v recieve data.
* @details send_vec_vec_str[i] is send data to process rank i.
* @details devide std::vector<std::vector<T>> into std::vector<T> and std::vector<index>, then call scatterV() for std::vector<>.
* @details class T accepts std::vector<>, std::string, or user-defined class WITHOUT pointer member.
* @details If 4 or more nested std::vector<...> is passed, this function will call itself recurcively.
*/
template <class T>
void scatter(const std::vector<std::vector<std::vector<T>>> &send_vec_vv,
std::vector<std::vector<T>> &recv_vec_v,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<std::vector<T>>>>" << std::endl;
#endif
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
assert(send_vec_vv.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
std::vector<std::vector<T>> send_data;
std::vector<std::vector<size_t>> send_index;
send_data.resize(n_proc);
send_index.resize(n_proc);
for(PS::S32 i=0; i<n_proc; ++i){
serialize_vector_vector(send_vec_vv[i],
send_data[i], send_index[i]);
}
std::vector<T> recv_data;
std::vector<size_t> recv_index;
scatter(send_data, recv_data , root, comm);
scatter(send_index, recv_index, root, comm);
deserialize_vector_vector(recv_data, recv_index,
recv_vec_v );
}
/**
* @brief specialization for std::vector<std::pair<Ta, Tb>>.
* @param[in] send_vec_vp send target.
* MUST NOT contain pointer member.
* @param[out] recv_vec_pair recieve data.
* @details send_vec_vec_str[i] is send data to process rank i.
* @details devide std::vector<std::pair<Ta, Tb>> into std::vector<Ta> and std::vector<Tb>, then call scatterV() for std::vector<T>.
* @details class Ta and Tb accept std::vector<>, std::string, or user-defined class WITHOUT pointer member.
*/
template <class Ta, class Tb>
void scatter(const std::vector<std::vector<std::pair<Ta, Tb>>> &send_vec_vp,
std::vector<std::pair<Ta, Tb>> &recv_vec_pair,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<std::pair<Ta, Tb>>>>" << std::endl;
#endif
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
assert(send_vec_vp.size() >= static_cast<size_t>(n_proc));
assert(0 <= root && root < n_proc);
std::vector<std::vector<Ta>> send_vec_1st;
std::vector<std::vector<Tb>> send_vec_2nd;
send_vec_1st.resize(n_proc);
send_vec_2nd.resize(n_proc);
for(PS::S32 i=0; i<n_proc; ++i){
split_vector_pair(send_vec_vp[i],
send_vec_1st[i], send_vec_2nd[i]);
}
std::vector<Ta> recv_vec_1st;
std::vector<Tb> recv_vec_2nd;
scatter(send_vec_1st, recv_vec_1st, root, comm);
scatter(send_vec_2nd, recv_vec_2nd, root, comm);
combine_vector_pair(recv_vec_1st, recv_vec_2nd,
recv_vec_pair );
}
/**
* @brief specialization for returning type interface.
* @param[in] send_vec send target.
* @return recv_vec recieved data.
* @detail wrapper for the use case: "auto recv_vec = COMM_TOOL::allToAll(vec);"
* @detail recv_vec.size() = PS::Comm::getNumberOfProc();
* @detail send/recv_vec[i] is send/recieve data to/from process i.
*/
template <class T>
T scatter(const std::vector<T> &send_vec,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
T recv_data;
scatter(send_vec, recv_data, root, comm);
return recv_data;
}
}
| 39.27881 | 138 | 0.530475 | Tokumasu-Lab |
d0a772d51042d726237c37e9f95db81912eb93f5 | 382 | cpp | C++ | acm/contest/7.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | acm/contest/7.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | acm/contest/7.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int main(int argc, char const *argv[]){
int a,b;
cin>>a>>b;
map<int,int> mp;
for(int i=1;i<=b;i++){
for(int j=(a/i)*i;j<=b;j+=i){
mp[j]+=i;
}
}
long long int sum=0;
for(int i=a;i<=b;i++){
//cout<<i<<endl;
sum+=mp[i];
}
cout<<sum<<endl;
return 0;
}
| 15.916667 | 39 | 0.575916 | AadityaJ |
d0a868938d64c864bda8abfd03170595f625ed70 | 2,468 | cpp | C++ | moai/src/moaicore/MOAICollisionShape.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | moai/src/moaicore/MOAICollisionShape.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | moai/src/moaicore/MOAICollisionShape.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAICollisionShape.h>
//================================================================//
// MOAICollisionShape
//================================================================//
//----------------------------------------------------------------//
const USRect& MOAICollisionShape::GetRect () const {
return *( USRect* )this->mRectBuffer;
}
//----------------------------------------------------------------//
const USQuad& MOAICollisionShape::GetQuad () const {
return *( USQuad* )this->mQuadBuffer;
}
//----------------------------------------------------------------//
MOAICollisionShape::MOAICollisionShape () :
mType ( NONE ) {
}
//----------------------------------------------------------------//
MOAICollisionShape::~MOAICollisionShape () {
}
//----------------------------------------------------------------//
bool MOAICollisionShape::Overlap ( const MOAICollisionShape& shape ) const {
switch ( this->mType ) {
case RECT: {
switch ( shape.mType ) {
case RECT: MOAICollisionShape::Overlap ( this->GetRect (), shape.GetRect ());
case QUAD: MOAICollisionShape::Overlap ( shape.GetQuad (), this->GetRect ());
}
break;
}
case QUAD: {
switch ( shape.mType ) {
case RECT: MOAICollisionShape::Overlap ( this->GetQuad (), shape.GetRect ());
case QUAD: MOAICollisionShape::Overlap ( this->GetQuad (), shape.GetQuad ());
}
break;
}
}
return false;
}
//----------------------------------------------------------------//
void MOAICollisionShape::Set ( const USRect& rect ) {
memcpy ( this->mRectBuffer, &rect, sizeof ( USRect ));
this->mType = RECT;
}
//----------------------------------------------------------------//
void MOAICollisionShape::Set ( const USQuad& quad ) {
memcpy ( this->mQuadBuffer, &quad, sizeof ( USQuad ));
this->mType = QUAD;
}
//----------------------------------------------------------------//
bool MOAICollisionShape::Overlap ( const USRect& s0, const USRect& s1 ) {
return s0.Overlap ( s1 );
}
//----------------------------------------------------------------//
bool MOAICollisionShape::Overlap ( const USQuad& s0, const USRect& s1 ) {
return s0.Overlap ( s1 );
}
//----------------------------------------------------------------//
bool MOAICollisionShape::Overlap ( const USQuad& s0, const USQuad& s1 ) {
return s0.Overlap ( s1 );
} | 29.035294 | 81 | 0.449757 | jjimenezg93 |
d0a96f7199b16477408266572e239c0516121321 | 11,031 | cpp | C++ | data/8.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/8.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/8.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int o3At,E7
,NPTt
,yQV,oY ,rs3s//oDd
, BJfEsB
,klq ,Dhv1
//j
,MQ
, N2
,QXu, nn4
, IlemB
,
MvE,/*vd6V*/ NZ ,X
, nuYH, zAc,rwvjkO//U1Rd
//k
, WPltg ,Zd,AL
, qndos
,
//GA26v
IDDAh6, A ,/*zM72*/Po4hp
, /*Q*/EaG,
Y5ia ,
kH
,
LybZ , Af3M, l/*sV*/ ,
D2Rch,
BhdS
//Js3H
,
YeG ,Xc,yjc0
, Ou
,
Cj
,
H5X
,U56
,acD9 , T1x;void
f_f0(){ { return /*p3S*/ ;{ int
i; volatile int Fg , W5w ,lToU6 ;; { { }return ;
}
{ {}
{} }i
= lToU6 +Fg+ W5w;{{
}
}}
//ko
return ;
{//7P0
{ if(true)
{ {/*B*/ for(int
i=1; i<1 ;++i){ }
if (
true ) ;//Bi
else if (true) ;else return
;
{} } }
else if
( true); else return ; };/**/for
(int
i=1 /*r*/;
i< /*jl*/ 2 ;++i )
return
;}}{ return
;return ;//AMKH
{ volatile int rT5x ,vDP ,
mVd
;
;return ;
T1x = mVd /*n4*/+rT5x + vDP;for(int i=1 //4b
; i<
3
;++i
){ {} ;
if(true
)//pCn
for(int
i=1 ;i<
4 ;++i )for (int i=1
; i<
5 ;++i)
{{
} } else {
{volatile int
I
; o3At/*YaI8Xv*/
= I
; }{
}}
} /*fx*/return
; if//xh0
(true)for
(int i=1 ; i<6 ;++i ){volatile int F ,xE
, QbkA
, /*2*/jfkY
/**/
, D0 ; if
(
true)
//MA
E7 =//3Z
D0+F ;/*fI9*/ else {{ }}
{if (
true)for
(int i=1 ;i<
7;++i/*7X9*/){} else
{if
(
true){
}
else{ }
} return
;
}if (
true) NPTt =
xE +QbkA+ jfkY
;/*82*/ else
{ volatile int eWN
; if( true
){}
else for
(int i=1
;i<8 ;++i
/*Lfi*/
) yQV
=
eWN;{/*9*/
/*RIp*/ return ;
return ;
}}}else
for(int i=1
; i< 9 ;++i ) {{ if ( true)return //uK
; else/*y3b*/{ return ; return ;{ } } } } }{//
for//e9u
(int
i=1 ; i<
10
/*3*/;++i){{ }} ; return ; ; }
for
(int i=1; i<
11 ;++i )for(int
i=1;
//
i<12 ;++i//eZ5X
)
for(int i=1;//19
i< 13//P
;++i) return
;{ {for(int
i=1;
i<14;++i )//xl
{
}if (
true
) if
( true/*hPVN*/ ) {
{{ {}} } for(int
//RIRL
i=1
; i< 15 ;++i)/*I3rN*/for
(int i=1/*zP8*/ ; i<
16
;++i//CB
)
{}} else{
{
}}else
return ;if(/*c*/true ) { for
(int i=1;i< 17 ;++i
//An
)return ;
}
else ;
} {
{
}{ } }//w4lI
{
;{{ }
} }{ {for
(int i=1
;//Z
i< 18/*N*/ ;++i
) if/*SL541*/
(
true)
{
}
else
return ; }/*wm6u*/
}/*7qn*/} for (int i=1;
i< 19;++i)return ;
}return ;
{int ijAAj
; volatile int
WPm//7
, XHP, RNDRGW, jq ,
C2Lp ; return ;
ijAAj
=C2Lp + WPm /*ckky7ku*/
+
XHP+
RNDRGW+ jq ; ;
; } {return ;
{ {
{
{}
return
;
} }; {
{
}
}}/*nPu*/{ ;{ /*uU*/if (
true
) { }else{{}
}/**/
{
}}
} {
{ { } }return ;
}
}
{{ {volatile int
hcV9 , Y1gs
,PBV8; oY = //NB
PBV8 +
hcV9+Y1gs
; }{ {}/*E*/} }return
;
{{{ int//b3
/*L*/ RUCN ;
volatile int Oxy
,
n7p6,
Awts ; rs3s=
Awts //FX
//sGB
;if(true )
{//ZCJYE
} else ;
RUCN =Oxy +n7p6 ;/*Th*/} { }
}return/*pt*/ ; //o
}/*p1R*///N6mEx
{ int/*7cT*/ MszV;volatile int bd,S, c69 , AtSz
,
xPS,
c
,Vz4PJl //ojm
,
f;
return ;
MszV= f + bd +S
+ c69//
;BJfEsB=
AtSz +xPS+ c
+
Vz4PJl
; }
{ int wf61//4y
;volatile int lO3pP ,c1et
, pyJ ,zK8aV
,
Pl;for(int /*81u*/i=1; i< 20 ;++i) {
{ return
;}
} wf61= Pl
+//
lO3pP /*xP*/
+ c1et+ pyJ
+zK8aV ;
} } ;return ;}void f_f1 (){{volatile int ZZfji ,XB,tBA0, /**/nAc9Fl, YmdvYb
;//R
{ {volatile int Pqh , iDHe/*R8*/ ;if (true)
{ volatile int DrsB
, C2Xsp ;return ;for (int i=1;
i<
21;++i ) if ( true/*UvmY*/)
klq= C2Xsp;else //TSX
{}/*HX*/for(int i=1 ; i<
22 ;++i )
Dhv1 =DrsB//g8
;} else
MQ=
iDHe+
Pqh ;
for (int i=1
;
i</*n*/ 23;++i)return
;}
for
(int i=1;
i<
24 ;++i)
if( true
)
{//xBSHD
{
int
t11 ;volatile int Iso, pOv ;; t11 =pOv+ Iso ; } { }
if (true )return ; else for (int i=1
;i< 25 ;++i)
return
;
{volatile int eAmsTj /*uO*/,
m ;
N2
=
m
+//8G
eAmsTj ;}
}else if
( true){
return ; }else {{
} } {{volatile int
VwMH, LwoBQ; { } if( true
){}else{
} QXu
=
LwoBQ
+VwMH
; } {}
{ { }}}
}if( true )nn4=YmdvYb
+ZZfji +XB +tBA0+
nAc9Fl//
/*u1*/ ; else ;
{
int VnvtQ/*5*/;
volatile int oPy , IGo , ZXdSTf, YF7
,
U ;
; { for (int i=1
; i< 26//yU
//
;++i ){}
{ for(int i=1;
i< 27;++i){
} //
}; {/*r*/{ }
{ }//d
}/*BIv*/
}for (int i=1
;
//
i<
28
;++i)VnvtQ =U//
+ oPy +IGo
+ZXdSTf + YF7
;{ {
int X3QW
;//
volatile int//LRJ
BlJ2; X3QW =BlJ2 ;
} {//2
{
}} ;} } };
if
(
true)
;else
if ( true) ; else//WJXBO
{
volatile int
DdCe,
Tqy ,
b
,lKv ;IlemB =lKv +DdCe+Tqy
+//ni
b/*AVH*/; {for(int
i=1/*8*/;i<
29;++i)
for
(int i=1
;i<30 ;++i
){volatile int F1Mo
, cpS
;{{ {
}
{//pAT
} }{
}
}for(int i=1;i< 31;++i)if(
true ){ }else
MvE= cpS +F1Mo ;
{for(int i=1 ;i<32 ;++i
){}} }{return ;
}if(//
true)
return //H
;else
return/*y*/ ; }{
//e5
for(int i=1/*C*/ ; i<33
;++i) for(int i=1 ;
i<34
;++i
) {{ { }}
}{
{volatile int
Ts,/*X5*/k
,b2H;NZ
=b2H/*Ak*/+Ts+k;
} for
(int i=1 ;i< 35/*5O*/;++i//
)return ;
}/**/
} }//g4
{volatile int RYA, uKzkd, QMnE//DtS
,
Ug, KlKD ; X = KlKD + RYA
+uKzkd
+QMnE+
Ug;{return ;
{int RqXp, G//M
/*n*/;volatile int tlVrU ,
ee1Aiv, iB , yN8,KX6,WX; {return ;
}
{ }G
= WX+tlVrU+ ee1Aiv;if(true /*M*/)return ;else
RqXp//Vx
= iB +
yN8+
KX6 ;}}
; }
return//AQ9
;/*sm*/ }
void
f_f2 ()
{ { {volatile int
B7X,L
,Qz, suiWl,
NfyD
,
D1YwZ, jfw
;nuYH=jfw+ B7X +//wJ
L + Qz;
; if (true/**/ ); else
{int K8wm6PvOr;
volatile int tIR, Nfe , nV7E ; ; {volatile int Ouc ,
C1//
,hYIh;zAc=hYIh+ Ouc+ C1;}{
return ;//dF
} {{
} ;{}} if(
true )
K8wm6PvOr=nV7E//K7
+tIR/*e*/+
Nfe ;else{
}}if(
true) ; else
rwvjkO=//Vule
suiWl + NfyD+D1YwZ ; }
{for
(int
i=1
; i< 36;++i ){
{int
U9fH; volatile int
Q
,JWM, s, /**/vKur ;U9fH =vKur;
WPltg//NL
= Q+
JWM + s; }/*P*/{ int
J;/*zh4*/volatile int pWs,
S7 ;
if(true
) {}else J= S7 +pWs ;
for(int i=1
;i< 37;++i )
{}
}
}{/**/int oSx
;volatile int t5i,q ,
NPl ;;oSx
=NPl//5K
+
t5i+
q ; }
/*sDlQAB*/ {
{
;}}}
return ; return
;{
{ volatile int BE9/*lMk*/ ,dVyi;
{/*UNh*/int rgxvY/*K*/;volatile int siA , ep;//lU1m
if (true/*3T*/)
//
rgxvY =
ep
+
siA /*5rS*/;else{/*w3*/}{} } {
if
(//3
true
)
{} else ;}//4H1
if(/*sHc1*/true
)
for (int i=1 ; i</*TMH*/38 ;++i)Zd =dVyi//l1
+BE9
;
else {}} {{{/*yOWzu*///nf
if (
true
) //QNA
; else return ; }
}
{int zQS ; volatile int Lb/**///1
,OqtQ ,
/*P6N*/E ; for
/*BsMT*/(int i=1 ;i<39
;++i ) zQS=E +Lb +
//BCqz
OqtQ;}}
} {
{
{}/**/for//FIyY8
(int i=1
;
i<
40 ;++i ){{
} {}} }//xs
{//FB6
int
lU ; volatile int
nt ,
xxTB
,ua3j;
lU= ua3j + nt +xxTB;}}if
(
true ) {
{
volatile int
ipt,
kF5,AthL
; AL
= AthL
+ ipt +kF5 ;{/*3Rf*//*WYdw*/int
/*X*/ fm
; volatile int D ,Jb ; { //
}fm= //AJTy
Jb+
D;{
//RZs
}
}}//h
for(int i=1
;i<41
;++i)
{//8J
volatile int Tz//H
,e7GZ, KFx
; if
(
true){ { return ; } //TJP
}else if(
true) qndos=KFx
+ Tz+e7GZ;
else if (true )for(int
i=1 ;i<42 ;++i
) return
; else//R
{}}for(int i=1;
i<43
;++i
) { volatile int XHk,
JXgy ,
v
;if(
true )
//K
IDDAh6= v/**/
+ XHk
+JXgy ;
else ;}{
//7
{
{
} }
} {
;} } /*ge*/else ;return
;}; {
volatile int NivH ,ZMLP ,eLS,mRL
/**/;
{
volatile int
f8b, nk , mN7
;{
volatile int cTVv, UaT
,
dQTe;
; {return ;{/**/}
}
if
(true) { }else A =dQTe+cTVv + UaT
;; }Po4hp =mN7 /*hL*/+f8b +
nk
; { ;}
}
{ {
if
( true)
{ }
else{;
/*W*/}
; }{;
}
{ {
volatile int vd ;
for
(int i=1 /*pf*/;i<44 /*1*///HT9
;++i )
EaG =
/*KFt*/vd;}//wF
{} }
} Y5ia= mRL+ NivH +
/*3p6*/ZMLP+
eLS;for(int i=1;
i<
45//1lRf
;++i )for /*wat*/
(int i=1 ;i<46
;++i) for(int i=1; i< 47
;++i
)
return ;//YzC
}
{volatile int h6 /*ux*/,G4B, yTc , C , FRz,buDo ,Tw,fuJ , v4k
,C6N ,
A7//W8p
,aoy
,//h1
R,
tH//Z4A
,vA , zrR6 ,WClLw
,
PFb;if(
true )if (true) { { return ; }{{ }
} {if
(
//L
true
){
} else
for (int i=1; i< /*w*/48 /*b*/;++i)
/*u*/{} {
} } }else{ { {;
}
}
return ;/*2v*/ }else
kH
= PFb+ /*hE*/h6+/**/G4B+ yTc+
C
+FRz+ buDo
;/*ZPf*/if//r4
( true) ; else if(
true)//
LybZ=Tw+//
fuJ
+v4k+C6N+/*pkHS*/ A7 /*w4*/ ;
else return
;
Af3M= aoy+R
+
tH+
vA + zrR6+WClLw;
return
;{return//lF
;
{{}{return ; {} for
(int i=1 ; i< 49;++i
)/*x*/{ for (int //SoTD
i=1; i< 50;++i
)/*g*/{}
} }}}}/*KC9*//*VMFkM*/return ; }int main () { volatile int//
QPW ,
tW8, /*21*/bt
,R7 , DMK
,xg
,
Y4, q8
,lRMo3I,yXh ,
i2;if (
true /*ce*/)
for
(int
i=1
; i<51;++i ) l=/*8Xo*/i2
+QPW +tW8+//0iOQ
bt + R7 + DMK; else { {//g3t
return
1251288111 ;
for (int
i=1; i<52 ;++i){
for
(int /*SC*/i=1 ;i<53;++i )
; ;} if (true ) {
{
return 867038002; {/*pLW*/}//PhT
}//2
/**/if(true) {}else{{ }
}}
else ;
}
{
{
{} } for (int
i=1 ; i<//9E
54
;++i
){{} ;}{
int tke
;volatile int Bmi,FLksQ ,
M9 , //CU
kp//c
,/*uxU*/uN; {
volatile int
z ,yRM
,F3 ;
D2Rch= F3+ z +yRM; { }} BhdS=uN
+
Bmi; if//r
(true
)//Lw
{ }else tke
=
FLksQ
+M9+
kp;}}
{volatile int iVf/*ms*/ , b2
,Jt5Z
;YeG
=
Jt5Z+iVf+b2 ;
; } { for
(int
i=1 ; i<55
;++i)
{ return//K
1765747176 ; return
2062316704; /*eHW*/ }if (true) //p
return 808082939
;else { {
}{ } {{{ }{ }} }
for//JQ
(int i=1/**/; i<
56;++i
)
{} }return //
384502502;;/*hC*/ }
; }
Xc= /*oJ*/ xg+ Y4+ q8
+
lRMo3I + /*88*/yXh
/*SevI*/;{
return
1867852740;
{{{
int X6 ;volatile int peuQ,y; for
(int i=1 ;
i<57;++i) X6 = y
+peuQ ;}
{ }
}{
{{}{ }}}
{ ;{if (true
)
return 1081798268 ; else { } }
{ { ;}{ }
} {for (int
i=1
;
i<58;++i
)for (int
i=1 ;
i<
59
;++i) ;{for(int i=1/**/ ; i<
60
;++i) {
/*vSEM*/}}}if//abvS
(
true) return
943161846;else ;
}
}
return
1239660351;
} return 608054594 ; {volatile int Ri6 ,//2NY
FB ,
bvo , sa
; { { { {}} return/*PN*/ 786909423 ;
/**/if(//3H
/*G*/true) for(int i=1; i<61 /*ri*/;++i
) for
(int
i=1; i<
62
//Ff
;++i
)
for
(int i=1 //t
;
i< 63/*rZV*/
;++i
)
{{ }} else
//ci
{ volatile int t9Cf, dxd; {
}
//5
{ }yjc0 =
dxd
+t9Cf;
}}//te
if( true
) if(
true
)
{ {volatile int pw
/**/, AILt;Ou = AILt+pw;} }
else{ return 1955638066;{ } {//UT
return 1293742239; }
if
(
true
)
{{
{}}
//w
} else//
;}/*h*/else
{
{
; return 1814964128 ; }
{
}{
return
75363636 ; } { //06
}
}};Cj = sa
+Ri6+ FB
+
bvo/*FY*/ ;//i
;
}
if
(
true)
{return 1257669817 ;
{ { volatile int d30, c3BBm ; H5X= c3BBm +
d30 ;};/*Tl*/
{for (int
i=1; i< 64;++i){}return 1661774657
; } }for
//Q
(int i=1;i<
65;++i)
return 1603901541 ;
} else { volatile int
Zv,mR,GlG, qm1,
AzQ,Hd5uA;//50W
for
(int i=1
//eq
;i<66/*d989*/ //Kfz
;++i//jm
) U56
= Hd5uA/**/ +Zv/*h*/+mR +
GlG
+ qm1
+ AzQ
;if ( true
){int Xd6 ;volatile int NyA
, g , nw8S, hUhGd ; { { }} { for
(int i=1 ; i<67 ;++i/*a*/)
{} { {/*7QKx*/ } {//R
/*CF2*/ } }
}if ( true){{volatile int ZLfk
,Udyu , Z8sh;
{} acD9 =//R1q4C7
Z8sh +
ZLfk +Udyu; { } /*lZE*/;{ } }/*Tt*/}else//fa8
Xd6 //ldaj
/*Ja*/ = hUhGd + NyA +//4f
g+nw8S;
}else{ ; /*Eh*/{
{{}}
}} for (int i=1 ;i< 68
;++i)
{ ; { {for (int i=1; i<69 ;++i ) {}}{
}
{//
}}}/**/} } | 10.987052 | 76 | 0.458526 | TianyiChen |
d0af510f34f2f8a51519428af0ce2e5d1278127b | 12,282 | cpp | C++ | src/lib/utils/meta_table_manager.cpp | nannancy/hyrise | a22d270b0692a24605fe02937cbd070ee4b8ebcb | [
"MIT"
] | null | null | null | src/lib/utils/meta_table_manager.cpp | nannancy/hyrise | a22d270b0692a24605fe02937cbd070ee4b8ebcb | [
"MIT"
] | 11 | 2019-12-02T20:47:52.000Z | 2020-02-04T23:19:31.000Z | src/lib/utils/meta_table_manager.cpp | nannancy/hyrise | a22d270b0692a24605fe02937cbd070ee4b8ebcb | [
"MIT"
] | null | null | null | #include "meta_table_manager.hpp"
#include "constant_mappings.hpp"
#include "hyrise.hpp"
#include "resolve_type.hpp"
#include "statistics/table_statistics.hpp"
#include "storage/base_encoded_segment.hpp"
#include "storage/dictionary_segment.hpp"
#include "storage/fixed_string_dictionary_segment.hpp"
#include "storage/segment_iterables/any_segment_iterable.hpp"
#include "storage/table.hpp"
#include "storage/table_column_definition.hpp"
namespace {
using namespace opossum; // NOLINT
// TODO(anyone): #1968 introduced this namespace. With the expected growth of the meta table manager of time, there
// might be a large number of helper function that are only loosely related to the core functionality
// of the MetaTableManager. If this becomes the case, restructure and move the functions to other files.
size_t get_distinct_value_count(const std::shared_ptr<BaseSegment>& segment) {
auto distinct_value_count = size_t{0};
resolve_data_type(segment->data_type(), [&](auto type) {
using ColumnDataType = typename decltype(type)::type;
// For dictionary segments, an early (and much faster) exit is possible by using the dictionary size
if (const auto dictionary_segment = std::dynamic_pointer_cast<const DictionarySegment<ColumnDataType>>(segment)) {
distinct_value_count = dictionary_segment->dictionary()->size();
return;
} else if (const auto fs_dictionary_segment =
std::dynamic_pointer_cast<const FixedStringDictionarySegment<pmr_string>>(segment)) {
distinct_value_count = fs_dictionary_segment->fixed_string_dictionary()->size();
return;
}
std::unordered_set<ColumnDataType> distinct_values;
auto iterable = create_any_segment_iterable<ColumnDataType>(*segment);
iterable.with_iterators([&](auto it, auto end) {
for (; it != end; ++it) {
const auto segment_item = *it;
if (!segment_item.is_null()) {
distinct_values.insert(segment_item.value());
}
}
});
distinct_value_count = distinct_values.size();
});
return distinct_value_count;
}
auto gather_segment_meta_data(const std::shared_ptr<Table>& meta_table, const MemoryUsageCalculationMode mode) {
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) {
for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) {
const auto& chunk = table->get_chunk(chunk_id);
const auto& segment = chunk->get_segment(column_id);
const auto data_type = pmr_string{data_type_to_string.left.at(table->column_data_type(column_id))};
const auto estimated_size = segment->memory_usage(mode);
AllTypeVariant encoding = NULL_VALUE;
AllTypeVariant vector_compression = NULL_VALUE;
if (const auto& encoded_segment = std::dynamic_pointer_cast<BaseEncodedSegment>(segment)) {
encoding = pmr_string{encoding_type_to_string.left.at(encoded_segment->encoding_type())};
if (encoded_segment->compressed_vector_type()) {
std::stringstream ss;
ss << *encoded_segment->compressed_vector_type();
vector_compression = pmr_string{ss.str()};
}
}
if (mode == MemoryUsageCalculationMode::Full) {
const auto distinct_value_count = static_cast<int64_t>(get_distinct_value_count(segment));
meta_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int32_t>(column_id),
pmr_string{table->column_name(column_id)}, data_type, distinct_value_count, encoding,
vector_compression, static_cast<int64_t>(estimated_size)});
} else {
meta_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int32_t>(column_id),
pmr_string{table->column_name(column_id)}, data_type, encoding, vector_compression,
static_cast<int64_t>(estimated_size)});
}
}
}
}
}
} // namespace
namespace opossum {
MetaTableManager::MetaTableManager() {
_methods["tables"] = &MetaTableManager::generate_tables_table;
_methods["columns"] = &MetaTableManager::generate_columns_table;
_methods["chunks"] = &MetaTableManager::generate_chunks_table;
_methods["chunk_sort_orders"] = &MetaTableManager::generate_chunk_sort_orders_table;
_methods["segments"] = &MetaTableManager::generate_segments_table;
_methods["segments_accurate"] = &MetaTableManager::generate_accurate_segments_table;
_table_names.reserve(_methods.size());
for (const auto& [table_name, _] : _methods) {
_table_names.emplace_back(table_name);
}
std::sort(_table_names.begin(), _table_names.end());
}
const std::vector<std::string>& MetaTableManager::table_names() const { return _table_names; }
std::shared_ptr<Table> MetaTableManager::generate_table(const std::string& table_name) const {
const auto table = _methods.at(table_name)();
table->set_table_statistics(TableStatistics::from_table(*table));
return table;
}
std::shared_ptr<Table> MetaTableManager::generate_tables_table() {
const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false},
{"column_count", DataType::Int, false},
{"row_count", DataType::Long, false},
{"chunk_count", DataType::Int, false},
{"max_chunk_size", DataType::Long, false}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
output_table->append({pmr_string{table_name}, static_cast<int32_t>(table->column_count()),
static_cast<int64_t>(table->row_count()), static_cast<int32_t>(table->chunk_count()),
static_cast<int64_t>(table->max_chunk_size())});
}
return output_table;
}
std::shared_ptr<Table> MetaTableManager::generate_columns_table() {
const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false},
{"column_name", DataType::String, false},
{"data_type", DataType::String, false},
{"nullable", DataType::Int, false}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) {
output_table->append({pmr_string{table_name}, static_cast<pmr_string>(table->column_name(column_id)),
static_cast<pmr_string>(data_type_to_string.left.at(table->column_data_type(column_id))),
static_cast<int32_t>(table->column_is_nullable(column_id))});
}
}
return output_table;
}
std::shared_ptr<Table> MetaTableManager::generate_chunks_table() {
const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false},
{"chunk_id", DataType::Int, false},
{"row_count", DataType::Long, false},
{"invalid_row_count", DataType::Long, false},
{"cleanup_commit_id", DataType::Long, true}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) {
const auto& chunk = table->get_chunk(chunk_id);
const auto cleanup_commit_id = chunk->get_cleanup_commit_id()
? AllTypeVariant{static_cast<int64_t>(*chunk->get_cleanup_commit_id())}
: NULL_VALUE;
output_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int64_t>(chunk->size()),
static_cast<int64_t>(chunk->invalid_row_count()), cleanup_commit_id});
}
}
return output_table;
}
/**
* At the moment, each chunk can be sorted by exactly one column or none. Hence, having a column within the chunk table
* would be sufficient. However, this will change in the near future (e.g., when a sort-merge join evicts a chunk that
* is sorted on two columns). To prepare for this change, this additional table stores the sort orders and allows a
* chunk to have multiple sort orders. Cascading sort orders for chunks are currently not planned.
*/
std::shared_ptr<Table> MetaTableManager::generate_chunk_sort_orders_table() {
const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false},
{"chunk_id", DataType::Int, false},
{"column_id", DataType::Int, false},
{"order_mode", DataType::String, false}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) {
const auto& chunk = table->get_chunk(chunk_id);
const auto ordered_by = chunk->ordered_by();
if (ordered_by) {
std::stringstream order_by_mode_steam;
order_by_mode_steam << ordered_by->second;
output_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id),
static_cast<int32_t>(ordered_by->first), pmr_string{order_by_mode_steam.str()}});
}
}
}
return output_table;
}
std::shared_ptr<Table> MetaTableManager::generate_segments_table() {
const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false},
{"chunk_id", DataType::Int, false},
{"column_id", DataType::Int, false},
{"column_name", DataType::String, false},
{"column_data_type", DataType::String, false},
{"encoding_type", DataType::String, true},
{"vector_compression_type", DataType::String, true},
{"estimated_size_in_bytes", DataType::Long, false}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
gather_segment_meta_data(output_table, MemoryUsageCalculationMode::Sampled);
return output_table;
}
std::shared_ptr<Table> MetaTableManager::generate_accurate_segments_table() {
PerformanceWarning("Accurate segment information are expensive to gather. Use with caution.");
const auto columns = TableColumnDefinitions{
{"table_name", DataType::String, false}, {"chunk_id", DataType::Int, false},
{"column_id", DataType::Int, false}, {"column_name", DataType::String, false},
{"column_data_type", DataType::String, false}, {"distinct_value_count", DataType::Long, false},
{"encoding_type", DataType::String, true}, {"vector_compression_type", DataType::String, true},
{"size_in_bytes", DataType::Long, false}};
auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes);
gather_segment_meta_data(output_table, MemoryUsageCalculationMode::Full);
return output_table;
}
bool MetaTableManager::is_meta_table_name(const std::string& name) {
const auto prefix_len = META_PREFIX.size();
return name.size() > prefix_len && std::string_view{&name[0], prefix_len} == MetaTableManager::META_PREFIX;
}
} // namespace opossum
| 51.605042 | 120 | 0.650708 | nannancy |
d0b0709cdd17548982516f20f0fed6741ecab45c | 1,200 | cpp | C++ | Assignment4/1025.6.34.cpp | cebarobot/Data-Structures-UCAS | 26d47f96b3b985b921a05e901b5d72713501baa4 | [
"MIT"
] | 2 | 2022-02-04T07:05:38.000Z | 2022-03-29T11:16:30.000Z | Assignment4/1025.6.34.cpp | cebarobot/Data-Structures-UCAS | 26d47f96b3b985b921a05e901b5d72713501baa4 | [
"MIT"
] | null | null | null | Assignment4/1025.6.34.cpp | cebarobot/Data-Structures-UCAS | 26d47f96b3b985b921a05e901b5d72713501baa4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 110;
int array_L[maxn];
int array_R[maxn];
int array_T[maxn];
bool is_parent(int uu, int vv) {
// printf("---%d %d\n", uu, vv);
if (uu == vv) {
return true;
}
if (array_T[vv]) {
return is_parent(uu, array_T[vv]);
}
return false;
}
int main() {
int tmp;
char ch;
int iii = 0;
while (scanf("%d%c", &tmp, &ch) == 2) {
array_L[iii] = tmp;
iii ++;
if (ch == ';') {
break;
}
}
int nn = iii;
iii = 0;
while (scanf("%d%c", &tmp, &ch) == 2) {
array_R[iii] = tmp;
iii ++;
if (ch == ';') {
break;
}
}
int uu, vv;
scanf("%d;%d", &uu, &vv);
for (int i = 0; i < nn; i++) {
if (array_L[i]) {
array_T[array_L[i]] = i;
}
if (array_R[i]) {
array_T[array_R[i]] = i;
}
}
// for (int i = 0; i < nn; i++) {
// printf("%d ", array_T[i]);
// }
if (is_parent(vv, uu)) {
printf("1\n");
} else {
printf("0\n");
}
return 0;
} | 19.354839 | 43 | 0.4225 | cebarobot |
d0b11866e091002fc395d58222a1a7109b90bafb | 1,588 | cpp | C++ | aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define len(a) (int)a.size()
#define all(a) (a.begin(),a.end())
#define fi first
#define sc second
#define ort(x,y) (x+y)/2
#define endl '\n'
#define FAST ios_base::sync_with_stdio(false);
#define d1(x) cerr<<#x<<":"<<x<<endl;
#define d2(x,y) cerr<<#x<<":"<<x<<" "<<#y<<":"<<y<<endl;
#define d3(x,y,z) cerr<<#x<<":"<<x<<" "<<#y<<":"<<y<<" "<<#z<<":"<<z<<endl;
#define N (int) ()
#define inf (int) (1e7)
#define p (1000000007)
#define heap priority_queue
#define mem(a,val) memset(a,val,sizeof(a))
#define y1 asdassa
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<pair<int,int>,int> piii;
int n;
void multiply(lli F[2][2],lli M[2][2])
{
lli R[2][2]={0};
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
R[i][j]=(R[i][j] + F[i][k] * M[k][j] %p )%p;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
F[i][j]=R[i][j];
}
void power(lli F[2][2], int n)
{
if (n == 0 || n == 1)
return;
lli M[2][2] = {{0,3},{1,2}};
power(F, n / 2);//to lower ones
multiply(F, F);
if (n % 2 != 0)//odd case one additional
multiply(F, M);
}
lli solve(lli n)
{
if(n==1) return 0;//no path
lli F[2][2] = {{0,3},{1,2}};//why 03 12? what are base cases?
//3 cases 1 case and 2
if (n == 0)
return 0;
power(F, n - 1);
return F[0][1];//why not 00
}
int main()
{
cin>>n;
printf("%lld\n",solve(n));
}
/*
https://discuss.codechef.com/questions/116710/codeforces-166e-help-needed-binary-matrix-exponentiation-for-a-begineer
*/ | 24.8125 | 117 | 0.564232 | aashishgahlawat |
d0b415cc938c7f9172b5af466464ef30381115a5 | 35,033 | cpp | C++ | src/lib/operators/aggregate.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2021-04-14T11:16:52.000Z | 2021-04-14T11:16:52.000Z | src/lib/operators/aggregate.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | null | null | null | src/lib/operators/aggregate.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2020-11-30T13:11:04.000Z | 2020-11-30T13:11:04.000Z | #include "aggregate.hpp"
#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "constant_mappings.hpp"
#include "resolve_type.hpp"
#include "scheduler/abstract_task.hpp"
#include "scheduler/current_scheduler.hpp"
#include "scheduler/job_task.hpp"
#include "storage/create_iterable_from_column.hpp"
#include "type_comparison.hpp"
#include "utils/assert.hpp"
namespace opossum {
Aggregate::Aggregate(const std::shared_ptr<AbstractOperator>& in,
const std::vector<AggregateColumnDefinition>& aggregates,
const std::vector<ColumnID>& groupby_column_ids)
: AbstractReadOnlyOperator(OperatorType::Aggregate, in),
_aggregates(aggregates),
_groupby_column_ids(groupby_column_ids) {
Assert(!(aggregates.empty() && groupby_column_ids.empty()),
"Neither aggregate nor groupby columns have been specified");
}
const std::vector<AggregateColumnDefinition>& Aggregate::aggregates() const { return _aggregates; }
const std::vector<ColumnID>& Aggregate::groupby_column_ids() const { return _groupby_column_ids; }
const std::string Aggregate::name() const { return "Aggregate"; }
const std::string Aggregate::description(DescriptionMode description_mode) const {
std::stringstream desc;
desc << "[Aggregate] GroupBy ColumnIDs: ";
for (size_t groupby_column_idx = 0; groupby_column_idx < _groupby_column_ids.size(); ++groupby_column_idx) {
desc << _groupby_column_ids[groupby_column_idx];
if (groupby_column_idx + 1 < _groupby_column_ids.size()) {
desc << ", ";
}
}
desc << " Aggregates: ";
for (size_t expression_idx = 0; expression_idx < _aggregates.size(); ++expression_idx) {
const auto& aggregate = _aggregates[expression_idx];
desc << aggregate_function_to_string.left.at(aggregate.function);
if (aggregate.column) {
desc << "(Column #" << *aggregate.column << ")";
} else {
desc << "(*)";
}
if (aggregate.alias) {
desc << " AS " << *aggregate.alias;
}
if (expression_idx + 1 < _aggregates.size()) {
desc << ", ";
}
}
return desc.str();
}
std::shared_ptr<AbstractOperator> Aggregate::_on_recreate(
const std::vector<AllParameterVariant>& args, const std::shared_ptr<AbstractOperator>& recreated_input_left,
const std::shared_ptr<AbstractOperator>& recreated_input_right) const {
return std::make_shared<Aggregate>(recreated_input_left, _aggregates, _groupby_column_ids);
}
void Aggregate::_on_cleanup() {
_contexts_per_column.clear();
_keys_per_chunk.clear();
}
/*
Visitor context for the partitioning/grouping visitor
*/
struct GroupByContext : ColumnVisitableContext {
GroupByContext(const std::shared_ptr<const Table>& t, ChunkID chunk, ColumnID column,
const std::shared_ptr<std::vector<AggregateKey>>& keys)
: table_in(t), chunk_id(chunk), column_id(column), hash_keys(keys) {}
// constructor for use in ReferenceColumn::visit_dereferenced
GroupByContext(const std::shared_ptr<BaseColumn>&, const std::shared_ptr<const Table>& referenced_table,
const std::shared_ptr<ColumnVisitableContext>& base_context, ChunkID chunk_id,
const std::shared_ptr<std::vector<ChunkOffset>>& chunk_offsets)
: table_in(referenced_table),
chunk_id(chunk_id),
column_id(std::static_pointer_cast<GroupByContext>(base_context)->column_id),
hash_keys(std::static_pointer_cast<GroupByContext>(base_context)->hash_keys),
chunk_offsets_in(chunk_offsets) {}
std::shared_ptr<const Table> table_in;
ChunkID chunk_id;
const ColumnID column_id;
std::shared_ptr<std::vector<AggregateKey>> hash_keys;
std::shared_ptr<std::vector<ChunkOffset>> chunk_offsets_in;
};
/*
Visitor context for the AggregateVisitor.
*/
template <typename ColumnType, typename AggregateType>
struct AggregateContext : ColumnVisitableContext {
AggregateContext() = default;
explicit AggregateContext(const std::shared_ptr<GroupByContext>& base_context) : groupby_context(base_context) {}
// constructor for use in ReferenceColumn::visit_dereferenced
AggregateContext(const std::shared_ptr<BaseColumn>&, const std::shared_ptr<const Table>&,
const std::shared_ptr<ColumnVisitableContext>& base_context, ChunkID chunk_id,
const std::shared_ptr<std::vector<ChunkOffset>>& chunk_offsets)
: groupby_context(std::static_pointer_cast<AggregateContext>(base_context)->groupby_context),
results(std::static_pointer_cast<AggregateContext>(base_context)->results) {
groupby_context->chunk_id = chunk_id;
groupby_context->chunk_offsets_in = chunk_offsets;
}
std::shared_ptr<GroupByContext> groupby_context;
std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>>
results;
};
/*
The following structs describe the different aggregate traits.
Given a ColumnType and AggregateFunction, certain traits like the aggregate type
can be deduced.
*/
template <typename ColumnType, AggregateFunction function, class Enable = void>
struct AggregateTraits {};
// COUNT on all types
template <typename ColumnType>
struct AggregateTraits<ColumnType, AggregateFunction::Count> {
using AggregateType = int64_t;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long;
};
// COUNT(DISTINCT) on all types
template <typename ColumnType>
struct AggregateTraits<ColumnType, AggregateFunction::CountDistinct> {
using AggregateType = int64_t;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long;
};
// MIN/MAX on all types
template <typename ColumnType, AggregateFunction function>
struct AggregateTraits<
ColumnType, function,
typename std::enable_if_t<function == AggregateFunction::Min || function == AggregateFunction::Max, void>> {
using AggregateType = ColumnType;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Null;
};
// AVG on arithmetic types
template <typename ColumnType, AggregateFunction function>
struct AggregateTraits<
ColumnType, function,
typename std::enable_if_t<function == AggregateFunction::Avg && std::is_arithmetic<ColumnType>::value, void>> {
using AggregateType = double;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Double;
};
// SUM on integers
template <typename ColumnType, AggregateFunction function>
struct AggregateTraits<
ColumnType, function,
typename std::enable_if_t<function == AggregateFunction::Sum && std::is_integral<ColumnType>::value, void>> {
using AggregateType = int64_t;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long;
};
// SUM on floating point numbers
template <typename ColumnType, AggregateFunction function>
struct AggregateTraits<
ColumnType, function,
typename std::enable_if_t<function == AggregateFunction::Sum && std::is_floating_point<ColumnType>::value, void>> {
using AggregateType = double;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Double;
};
// invalid: AVG on non-arithmetic types
template <typename ColumnType, AggregateFunction function>
struct AggregateTraits<
ColumnType, function,
typename std::enable_if_t<!std::is_arithmetic<ColumnType>::value &&
(function == AggregateFunction::Avg || function == AggregateFunction::Sum),
void>> {
using AggregateType = ColumnType;
static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Null;
};
/*
The AggregateFunctionBuilder is used to create the lambda function that will be used by
the AggregateVisitor. It is a separate class because methods cannot be partially specialized.
Therefore, we partially specialize the whole class and define the get_aggregate_function anew every time.
*/
template <typename ColumnType, typename AggregateType>
using AggregateFunctor = std::function<std::optional<AggregateType>(ColumnType, std::optional<AggregateType>)>;
template <typename ColumnType, typename AggregateType, AggregateFunction function>
struct AggregateFunctionBuilder {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { Fail("Invalid aggregate function"); }
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Min> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) {
if (!current_aggregate || value_smaller(new_value, *current_aggregate)) {
// New minimum found
return new_value;
}
return *current_aggregate;
};
}
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Max> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) {
if (!current_aggregate || value_greater(new_value, *current_aggregate)) {
// New maximum found
return new_value;
}
return *current_aggregate;
};
}
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Sum> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) {
// add new value to sum
return new_value + (!current_aggregate ? 0 : *current_aggregate); // NOLINT - false positive hicpp-use-nullptr
};
}
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Avg> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) {
// add new value to sum
return new_value + (!current_aggregate ? 0 : *current_aggregate); // NOLINT - false positive hicpp-use-nullptr
};
}
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Count> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType, std::optional<AggregateType> current_aggregate) { return std::nullopt; };
}
};
template <typename ColumnType, typename AggregateType>
struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::CountDistinct> {
AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() {
return [](ColumnType, std::optional<AggregateType> current_aggregate) { return std::nullopt; };
}
};
template <typename ColumnDataType, AggregateFunction function>
void Aggregate::_aggregate_column(ChunkID chunk_id, ColumnID column_index, const BaseColumn& base_column) {
using AggregateType = typename AggregateTraits<ColumnDataType, function>::AggregateType;
auto aggregator = AggregateFunctionBuilder<ColumnDataType, AggregateType, function>().get_aggregate_function();
auto& context =
*std::static_pointer_cast<AggregateContext<ColumnDataType, AggregateType>>(_contexts_per_column[column_index]);
auto& results = *context.results;
auto& hash_keys = _keys_per_chunk[chunk_id];
resolve_column_type<ColumnDataType>(
base_column, [&results, &hash_keys, chunk_id, aggregator](const auto& typed_column) {
auto iterable = create_iterable_from_column<ColumnDataType>(typed_column);
ChunkOffset chunk_offset{0};
// Now that all relevant types have been resolved, we can iterate over the column and build the aggregations.
iterable.for_each([&, chunk_id, aggregator](const auto& value) {
results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset);
/**
* If the value is NULL, the current aggregate value does not change.
*/
if (!value.is_null()) {
// If we have a value, use the aggregator lambda to update the current aggregate value for this group
results[(*hash_keys)[chunk_offset]].current_aggregate =
aggregator(value.value(), results[(*hash_keys)[chunk_offset]].current_aggregate);
// increase value counter
++results[(*hash_keys)[chunk_offset]].aggregate_count;
if (function == AggregateFunction::CountDistinct) {
// for the case of CountDistinct, insert this value into the set to keep track of distinct values
results[(*hash_keys)[chunk_offset]].distinct_values.insert(value.value());
}
}
++chunk_offset;
});
});
}
std::shared_ptr<const Table> Aggregate::_on_execute() {
auto input_table = input_table_left();
for ([[maybe_unused]] const auto groupby_column_id : _groupby_column_ids) {
DebugAssert(groupby_column_id < input_table->column_count(), "GroupBy column index out of bounds");
}
// check for invalid aggregates
for (const auto& aggregate : _aggregates) {
if (!aggregate.column) {
if (aggregate.function != AggregateFunction::Count) {
Fail("Aggregate: Asterisk is only valid with COUNT");
}
} else {
DebugAssert(*aggregate.column < input_table->column_count(), "Aggregate column index out of bounds");
if (input_table->column_data_type(*aggregate.column) == DataType::String &&
(aggregate.function == AggregateFunction::Sum || aggregate.function == AggregateFunction::Avg)) {
Fail("Aggregate: Cannot calculate SUM or AVG on string column");
}
}
}
/*
PARTITIONING PHASE
First we partition the input chunks by the given group key(s).
This is done by creating a vector that contains the AggregateKey for each row.
It is gradually built by visitors, one for each group column.
*/
_keys_per_chunk = std::vector<std::shared_ptr<std::vector<AggregateKey>>>(input_table->chunk_count());
for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) {
_keys_per_chunk[chunk_id] = std::make_shared<std::vector<AggregateKey>>(input_table->get_chunk(chunk_id)->size(),
AggregateKey(_groupby_column_ids.size()));
}
std::vector<std::shared_ptr<AbstractTask>> jobs;
jobs.reserve(_groupby_column_ids.size());
for (size_t group_column_index = 0; group_column_index < _groupby_column_ids.size(); ++group_column_index) {
jobs.emplace_back(std::make_shared<JobTask>([&input_table, group_column_index, this]() {
const auto column_id = _groupby_column_ids.at(group_column_index);
const auto data_type = input_table->column_data_type(column_id);
resolve_data_type(data_type, [&](auto type) {
using ColumnDataType = typename decltype(type)::type;
/*
Store unique IDs for equal values in the groupby column (similar to dictionary encoding).
The ID 0 is reserved for NULL values. The combined IDs build an AggregateKey for each row.
*/
auto id_map = std::unordered_map<ColumnDataType, uint64_t>();
uint64_t id_counter = 1u;
for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) {
const auto chunk_in = input_table->get_chunk(chunk_id);
const auto base_column = chunk_in->get_column(column_id);
resolve_column_type<ColumnDataType>(*base_column, [&](auto& typed_column) {
auto iterable = create_iterable_from_column<ColumnDataType>(typed_column);
ChunkOffset chunk_offset{0};
iterable.for_each([&](const auto& value) {
if (value.is_null()) {
(*_keys_per_chunk[chunk_id])[chunk_offset][group_column_index] = 0u;
} else {
auto inserted = id_map.try_emplace(value.value(), id_counter);
// store either the current id_counter or the existing ID of the value
(*_keys_per_chunk[chunk_id])[chunk_offset][group_column_index] = inserted.first->second;
// if the id_map didn't have the value as a key and a new element was inserted
if (inserted.second) ++id_counter;
}
++chunk_offset;
});
});
}
});
}));
jobs.back()->schedule();
}
CurrentScheduler::wait_for_tasks(jobs);
/*
AGGREGATION PHASE
*/
_contexts_per_column = std::vector<std::shared_ptr<ColumnVisitableContext>>(_aggregates.size());
if (_aggregates.empty()) {
/*
Insert a dummy context for the DISTINCT implementation.
That way, _contexts_per_column will always have at least one context with results.
This is important later on when we write the group keys into the table.
We choose int8_t for column type and aggregate type because it's small.
*/
auto context = std::make_shared<AggregateContext<DistinctColumnType, DistinctAggregateType>>();
context->results =
std::make_shared<std::unordered_map<AggregateKey, AggregateResult<DistinctAggregateType, DistinctColumnType>,
std::hash<AggregateKey>>>();
_contexts_per_column.push_back(context);
}
/**
* Create an AggregateContext for each column in the input table that a normal (i.e. non-DISTINCT) aggregate is
* created on. We do this here, and not in the per-chunk-loop below, because there might be no Chunks in the input
* and _write_aggregate_output() needs these contexts anyway.
*/
for (ColumnID column_id{0}; column_id < _aggregates.size(); ++column_id) {
const auto& aggregate = _aggregates[column_id];
if (!aggregate.column && aggregate.function == AggregateFunction::Count) {
// SELECT COUNT(*) - we know the template arguments, so we don't need a visitor
auto context = std::make_shared<AggregateContext<CountColumnType, CountAggregateType>>();
context->results =
std::make_shared<std::unordered_map<AggregateKey, AggregateResult<CountAggregateType, CountColumnType>,
std::hash<AggregateKey>>>();
_contexts_per_column[column_id] = context;
continue;
}
auto data_type = input_table->column_data_type(*aggregate.column);
_contexts_per_column[column_id] = _create_aggregate_context(data_type, aggregate.function);
}
// Process Chunks and perform aggregations
for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) {
auto chunk_in = input_table->get_chunk(chunk_id);
auto& hash_keys = _keys_per_chunk[chunk_id];
if (_aggregates.empty()) {
/**
* DISTINCT implementation
*
* In Opossum we handle the SQL keyword DISTINCT by grouping without aggregation.
*
* For a query like "SELECT DISTINCT * FROM A;"
* we would assume that all columns from A are part of 'groupby_columns',
* respectively any columns that were specified in the projection.
* The optimizer is responsible to take care of passing in the correct columns.
*
* How does this operation work?
* Distinct rows are retrieved by grouping by vectors of values. Similar as for the usual aggregation
* these vectors are used as keys in the 'column_results' map.
*
* At this point we've got all the different keys from the chunks and accumulate them in 'column_results'.
* In order to reuse the aggregation implementation, we add a dummy AggregateResult.
* One could optimize here in the future.
*
* Obviously this implementation is also used for plain GroupBy's.
*/
auto context = std::static_pointer_cast<AggregateContext<DistinctColumnType, DistinctAggregateType>>(
_contexts_per_column[0]);
auto& results = *context->results;
for (ChunkOffset chunk_offset{0}; chunk_offset < chunk_in->size(); chunk_offset++) {
results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset);
}
} else {
ColumnID column_index{0};
for (const auto& aggregate : _aggregates) {
/**
* Special COUNT(*) implementation.
* Because COUNT(*) does not have a specific target column, we use the maximum ColumnID.
* We then basically go through the _keys_per_chunk map and count the occurrences of each group key.
* The results are saved in the regular aggregate_count variable so that we don't need a
* specific output logic for COUNT(*).
*/
if (!aggregate.column && aggregate.function == AggregateFunction::Count) {
auto context = std::static_pointer_cast<AggregateContext<CountColumnType, CountAggregateType>>(
_contexts_per_column[column_index]);
auto& results = *context->results;
// count occurrences for each group key
for (ChunkOffset chunk_offset{0}; chunk_offset < chunk_in->size(); chunk_offset++) {
results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset);
++results[(*hash_keys)[chunk_offset]].aggregate_count;
}
++column_index;
continue;
}
auto base_column = chunk_in->get_column(*aggregate.column);
auto data_type = input_table->column_data_type(*aggregate.column);
/*
Invoke correct aggregator for each column
*/
resolve_data_type(data_type, [&, this, aggregate](auto type) {
using ColumnDataType = typename decltype(type)::type;
switch (aggregate.function) {
case AggregateFunction::Min:
_aggregate_column<ColumnDataType, AggregateFunction::Min>(chunk_id, column_index, *base_column);
break;
case AggregateFunction::Max:
_aggregate_column<ColumnDataType, AggregateFunction::Max>(chunk_id, column_index, *base_column);
break;
case AggregateFunction::Sum:
_aggregate_column<ColumnDataType, AggregateFunction::Sum>(chunk_id, column_index, *base_column);
break;
case AggregateFunction::Avg:
_aggregate_column<ColumnDataType, AggregateFunction::Avg>(chunk_id, column_index, *base_column);
break;
case AggregateFunction::Count:
_aggregate_column<ColumnDataType, AggregateFunction::Count>(chunk_id, column_index, *base_column);
break;
case AggregateFunction::CountDistinct:
_aggregate_column<ColumnDataType, AggregateFunction::CountDistinct>(chunk_id, column_index, *base_column);
break;
}
});
++column_index;
}
}
}
// add group by columns
for (const auto column_id : _groupby_column_ids) {
_output_column_definitions.emplace_back(input_table->column_name(column_id),
input_table->column_data_type(column_id));
auto groupby_column =
make_shared_by_data_type<BaseColumn, ValueColumn>(input_table->column_data_type(column_id), true);
_groupby_columns.push_back(groupby_column);
_output_columns.push_back(groupby_column);
}
/**
* Write group-by columns.
*
* 'results_per_column' always contains at least one element, since there are either GroupBy or Aggregate columns.
* However, we need to look only at the first element, because the keys for all columns are the same.
*
* The following loop is used for both, actual GroupBy columns and DISTINCT columns.
**/
if (_aggregates.empty()) {
auto context =
std::static_pointer_cast<AggregateContext<DistinctColumnType, DistinctAggregateType>>(_contexts_per_column[0]);
auto pos_list = PosList();
pos_list.reserve(context->results->size());
for (auto& map : *context->results) {
pos_list.push_back(map.second.row_id);
}
_write_groupby_output(pos_list);
}
/*
Write the aggregated columns to the output
*/
ColumnID column_index{0};
for (const auto& aggregate : _aggregates) {
const auto column = aggregate.column;
// Output column for COUNT(*). int is chosen arbitrarily.
const auto data_type = !column ? DataType::Int : input_table->column_data_type(*column);
resolve_data_type(
data_type, [&, column_index](auto type) { _write_aggregate_output(type, column_index, aggregate.function); });
++column_index;
}
// Write the output
auto output = std::make_shared<Table>(_output_column_definitions, TableType::Data);
output->append_chunk(_output_columns);
return output;
}
/*
The following template functions write the aggregated values for the different aggregate functions.
They are separate and templated to avoid compiler errors for invalid type/function combinations.
*/
// MIN, MAX, SUM write the current aggregated value
template <typename ColumnType, typename AggregateType, AggregateFunction func>
typename std::enable_if<
func == AggregateFunction::Min || func == AggregateFunction::Max || func == AggregateFunction::Sum, void>::type
write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>> column,
std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>,
std::hash<AggregateKey>>>
results) {
DebugAssert(column->is_nullable(), "Aggregate: Output column needs to be nullable");
auto& values = column->values();
auto& null_values = column->null_values();
values.resize(results->size());
null_values.resize(results->size());
size_t i = 0;
for (auto& kv : *results) {
null_values[i] = !kv.second.current_aggregate;
if (kv.second.current_aggregate) {
values[i] = *kv.second.current_aggregate;
}
++i;
}
}
// COUNT writes the aggregate counter
template <typename ColumnType, typename AggregateType, AggregateFunction func>
typename std::enable_if<func == AggregateFunction::Count, void>::type write_aggregate_values(
std::shared_ptr<ValueColumn<AggregateType>> column,
std::shared_ptr<
std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>>
results) {
DebugAssert(!column->is_nullable(), "Aggregate: Output column for COUNT shouldn't be nullable");
auto& values = column->values();
values.resize(results->size());
size_t i = 0;
for (auto& kv : *results) {
values[i] = kv.second.aggregate_count;
++i;
}
}
// COUNT(DISTINCT) writes the number of distinct values
template <typename ColumnType, typename AggregateType, AggregateFunction func>
typename std::enable_if<func == AggregateFunction::CountDistinct, void>::type write_aggregate_values(
std::shared_ptr<ValueColumn<AggregateType>> column,
std::shared_ptr<
std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>>
results) {
DebugAssert(!column->is_nullable(), "Aggregate: Output column for COUNT shouldn't be nullable");
auto& values = column->values();
values.resize(results->size());
size_t i = 0;
for (auto& kv : *results) {
values[i] = kv.second.distinct_values.size();
++i;
}
}
// AVG writes the calculated average from current aggregate and the aggregate counter
template <typename ColumnType, typename AggregateType, AggregateFunction func>
typename std::enable_if<func == AggregateFunction::Avg && std::is_arithmetic<AggregateType>::value, void>::type
write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>> column,
std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>,
std::hash<AggregateKey>>>
results) {
DebugAssert(column->is_nullable(), "Aggregate: Output column needs to be nullable");
auto& values = column->values();
auto& null_values = column->null_values();
values.resize(results->size());
null_values.resize(results->size());
size_t i = 0;
for (auto& kv : *results) {
null_values[i] = !kv.second.current_aggregate;
if (kv.second.current_aggregate) {
values[i] = *kv.second.current_aggregate / static_cast<AggregateType>(kv.second.aggregate_count);
}
++i;
}
}
// AVG is not defined for non-arithmetic types. Avoiding compiler errors.
template <typename ColumnType, typename AggregateType, AggregateFunction func>
typename std::enable_if<func == AggregateFunction::Avg && !std::is_arithmetic<AggregateType>::value, void>::type
write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>>,
std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>,
std::hash<AggregateKey>>>) {
Fail("Invalid aggregate");
}
void Aggregate::_write_groupby_output(PosList& pos_list) {
auto input_table = input_table_left();
for (size_t group_column_index = 0; group_column_index < _groupby_column_ids.size(); ++group_column_index) {
auto base_columns = std::vector<std::shared_ptr<const BaseColumn>>();
for (const auto& chunk : input_table->chunks()) {
base_columns.push_back(chunk->get_column(_groupby_column_ids[group_column_index]));
}
for (const auto row_id : pos_list) {
_groupby_columns[group_column_index]->append((*base_columns[row_id.chunk_id])[row_id.chunk_offset]);
}
}
}
template <typename ColumnType>
void Aggregate::_write_aggregate_output(boost::hana::basic_type<ColumnType> type, ColumnID column_index,
AggregateFunction function) {
switch (function) {
case AggregateFunction::Min:
write_aggregate_output<ColumnType, AggregateFunction::Min>(column_index);
break;
case AggregateFunction::Max:
write_aggregate_output<ColumnType, AggregateFunction::Max>(column_index);
break;
case AggregateFunction::Sum:
write_aggregate_output<ColumnType, AggregateFunction::Sum>(column_index);
break;
case AggregateFunction::Avg:
write_aggregate_output<ColumnType, AggregateFunction::Avg>(column_index);
break;
case AggregateFunction::Count:
write_aggregate_output<ColumnType, AggregateFunction::Count>(column_index);
break;
case AggregateFunction::CountDistinct:
write_aggregate_output<ColumnType, AggregateFunction::CountDistinct>(column_index);
break;
}
}
template <typename ColumnType, AggregateFunction function>
void Aggregate::write_aggregate_output(ColumnID column_index) {
// retrieve type information from the aggregation traits
typename AggregateTraits<ColumnType, function>::AggregateType aggregate_type;
auto aggregate_data_type = AggregateTraits<ColumnType, function>::AGGREGATE_DATA_TYPE;
const auto& aggregate = _aggregates[column_index];
if (aggregate_data_type == DataType::Null) {
// if not specified, it’s the input column’s type
aggregate_data_type = input_table_left()->column_data_type(*aggregate.column);
}
// use the alias or generate the name, e.g. MAX(column_a)
std::string output_column_name;
if (aggregate.alias) {
output_column_name = *aggregate.alias;
} else if (!aggregate.column) {
output_column_name = "COUNT(*)";
} else {
const auto& column_name = input_table_left()->column_name(*aggregate.column);
if (aggregate.function == AggregateFunction::CountDistinct) {
output_column_name = std::string("COUNT(DISTINCT ") + column_name + ")";
} else {
output_column_name = aggregate_function_to_string.left.at(function) + "(" + column_name + ")";
}
}
constexpr bool NEEDS_NULL = (function != AggregateFunction::Count && function != AggregateFunction::CountDistinct);
_output_column_definitions.emplace_back(output_column_name, aggregate_data_type, NEEDS_NULL);
auto output_column = std::make_shared<ValueColumn<decltype(aggregate_type)>>(NEEDS_NULL);
auto context = std::static_pointer_cast<AggregateContext<ColumnType, decltype(aggregate_type)>>(
_contexts_per_column[column_index]);
// write all group keys into the respective columns
if (column_index == 0) {
auto pos_list = PosList();
pos_list.reserve(context->results->size());
for (auto& map : *context->results) {
pos_list.push_back(map.second.row_id);
}
_write_groupby_output(pos_list);
}
// write aggregated values into the column
if (!context->results->empty()) {
write_aggregate_values<ColumnType, decltype(aggregate_type), function>(output_column, context->results);
} else if (_groupby_columns.empty()) {
// If we did not GROUP BY anything and we have no results, we need to add NULL for most aggregates and 0 for count
output_column->values().push_back(decltype(aggregate_type){});
if (function != AggregateFunction::Count && function != AggregateFunction::CountDistinct) {
output_column->null_values().push_back(true);
}
}
_output_columns.push_back(output_column);
}
std::shared_ptr<ColumnVisitableContext> Aggregate::_create_aggregate_context(const DataType data_type,
const AggregateFunction function) const {
std::shared_ptr<ColumnVisitableContext> context;
resolve_data_type(data_type, [&](auto type) {
using ColumnDataType = typename decltype(type)::type;
switch (function) {
case AggregateFunction::Min:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Min>();
break;
case AggregateFunction::Max:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Max>();
break;
case AggregateFunction::Sum:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Sum>();
break;
case AggregateFunction::Avg:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Avg>();
break;
case AggregateFunction::Count:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Count>();
break;
case AggregateFunction::CountDistinct:
context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::CountDistinct>();
break;
}
});
return context;
}
template <typename ColumnDataType, AggregateFunction aggregate_function>
std::shared_ptr<ColumnVisitableContext> Aggregate::_create_aggregate_context_impl() const {
const auto context = std::make_shared<
AggregateContext<ColumnDataType, typename AggregateTraits<ColumnDataType, aggregate_function>::AggregateType>>();
context->results = std::make_shared<typename decltype(context->results)::element_type>();
return context;
}
} // namespace opossum
| 42.056423 | 120 | 0.706277 | IanJamesMcKay |
d0b8ce1cfba602d6ad9bd5cffcca7c37ee3c3ec9 | 442 | cpp | C++ | samples/unit_test/test.cpp | vagran/adk | 1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2 | [
"BSD-3-Clause"
] | 3 | 2015-10-12T06:06:00.000Z | 2020-01-17T18:16:18.000Z | samples/unit_test/test.cpp | vagran/adk | 1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2 | [
"BSD-3-Clause"
] | null | null | null | samples/unit_test/test.cpp | vagran/adk | 1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2 | [
"BSD-3-Clause"
] | null | null | null | /* This file is a part of ADK library.
* Copyright (c) 2012-2015, Artyom Lebedev <artyom.lebedev@gmail.com>
* All rights reserved.
* See LICENSE file for copyright details.
*/
/** @file test.cpp
* Sample unit test implementation.
*/
#include <adk_ut.h>
#include "component/component.h"
UT_TEST("Sample test")
{
UT(SampleString()) == UT("Sample string");
UT_CKPOINT("Multiplication");
UT(SampleMult(5, 3)) == UT(15);
}
| 19.217391 | 69 | 0.667421 | vagran |
d0b9ab84b7453162a1bceeee651d4ad7befcbb19 | 714 | cpp | C++ | JAL/PAT/Medium/1021.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | JAL/PAT/Medium/1021.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | JAL/PAT/Medium/1021.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2020-04-20T11:16:53.000Z | 2021-01-02T15:58:35.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using piir = pair<int, int>;
template <typename T = int>
inline void oo(string str, T val) {
cerr << str << val << endl;
}
template <typename T = int>
inline T read() {
T x;
cin >> x;
return x;
}
#define endl '\n'
#define FOR(i, x, y) \
for (decay<decltype(y)>::type i = (x), _##i = (y); i < _##i; ++i)
#define FORD(i, x, y) \
for (decay<decltype(x)>::type i = (x), _##i = (y); i > _##i; --i)
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string s(read<string>());
map<char, int> M;
for (char c : s) M[c]++;
for (auto p : M) cout << p.first << ":" << p.second << endl;
return 0;
}
| 21 | 67 | 0.558824 | webturing |
d0c2975064906077a5fc556f6d0a1756bbc3a948 | 565 | cc | C++ | test/mocks/upstream/cluster.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 17,703 | 2017-09-14T18:23:43.000Z | 2022-03-31T22:04:17.000Z | test/mocks/upstream/cluster.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 15,957 | 2017-09-14T16:38:22.000Z | 2022-03-31T23:56:30.000Z | test/mocks/upstream/cluster.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 3,780 | 2017-09-14T18:58:47.000Z | 2022-03-31T17:10:47.000Z | #include "cluster.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Upstream {
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
MockCluster::MockCluster() {
ON_CALL(*this, info()).WillByDefault(Return(info_));
ON_CALL(*this, initialize(_))
.WillByDefault(Invoke([this](std::function<void()> callback) -> void {
EXPECT_EQ(nullptr, initialize_callback_);
initialize_callback_ = callback;
}));
}
MockCluster::~MockCluster() = default;
} // namespace Upstream
} // namespace Envoy
| 23.541667 | 76 | 0.686726 | dcillera |
d0c327df56e5ab30e0b0660b5d1ce80c5951629c | 52,074 | cpp | C++ | tests/RoundRectTest.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | tests/RoundRectTest.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | tests/RoundRectTest.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkMatrix.h"
#include "include/core/SkRRect.h"
#include "include/pathops/SkPathOps.h"
#include "include/utils/SkRandom.h"
#include "src/core/SkPointPriv.h"
#include "src/core/SkRRectPriv.h"
#include "tests/Test.h"
static void test_tricky_radii(skiatest::Reporter* reporter) {
{
// crbug.com/458522
SkRRect rr;
const SkRect bounds = {3709, 3709, 3709 + 7402, 3709 + 29825};
const SkScalar rad = 12814;
const SkVector vec[] = {{rad, rad}, {0, rad}, {rad, rad}, {0, rad}};
rr.setRectRadii(bounds, vec);
}
{
// crbug.com//463920
SkRect r = SkRect::MakeLTRB(0, 0, 1009, 33554432.0);
SkVector radii[4] = {{13.0f, 8.0f}, {170.0f, 2.0}, {256.0f, 33554432.0}, {110.0f, 5.0f}};
SkRRect rr;
rr.setRectRadii(r, radii);
REPORTER_ASSERT(
reporter, (double)rr.radii(SkRRect::kUpperRight_Corner).fY +
(double)rr.radii(SkRRect::kLowerRight_Corner).fY <=
rr.height());
}
}
static void test_empty_crbug_458524(skiatest::Reporter* reporter) {
SkRRect rr;
const SkRect bounds = {3709, 3709, 3709 + 7402, 3709 + 29825};
const SkScalar rad = 40;
rr.setRectXY(bounds, rad, rad);
SkRRect other;
SkMatrix matrix;
matrix.setScale(0, 1);
rr.transform(matrix, &other);
REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == other.getType());
}
// Test that all the SkRRect entry points correctly handle un-sorted and
// zero-sized input rects
static void test_empty(skiatest::Reporter* reporter) {
static const SkRect oooRects[] = {
// out of order
{100, 0, 0, 100}, // ooo horizontal
{0, 100, 100, 0}, // ooo vertical
{100, 100, 0, 0}, // ooo both
};
static const SkRect emptyRects[] = {
{100, 100, 100, 200}, // empty horizontal
{100, 100, 200, 100}, // empty vertical
{100, 100, 100, 100}, // empty both
{0, 0, 0, 0} // setEmpty-empty
};
static const SkVector radii[4] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}};
SkRRect r;
for (size_t i = 0; i < SK_ARRAY_COUNT(oooRects); ++i) {
r.setRect(oooRects[i]);
REPORTER_ASSERT(reporter, !r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted());
r.setOval(oooRects[i]);
REPORTER_ASSERT(reporter, !r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted());
r.setRectXY(oooRects[i], 1, 2);
REPORTER_ASSERT(reporter, !r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted());
r.setNinePatch(oooRects[i], 0, 1, 2, 3);
REPORTER_ASSERT(reporter, !r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted());
r.setRectRadii(oooRects[i], radii);
REPORTER_ASSERT(reporter, !r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted());
}
for (size_t i = 0; i < SK_ARRAY_COUNT(emptyRects); ++i) {
r.setRect(emptyRects[i]);
REPORTER_ASSERT(reporter, r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]);
r.setOval(emptyRects[i]);
REPORTER_ASSERT(reporter, r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]);
r.setRectXY(emptyRects[i], 1, 2);
REPORTER_ASSERT(reporter, r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]);
r.setNinePatch(emptyRects[i], 0, 1, 2, 3);
REPORTER_ASSERT(reporter, r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]);
r.setRectRadii(emptyRects[i], radii);
REPORTER_ASSERT(reporter, r.isEmpty());
REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]);
}
r.setRect({SK_ScalarNaN, 10, 10, 20});
REPORTER_ASSERT(reporter, r == SkRRect::MakeEmpty());
r.setRect({0, 10, 10, SK_ScalarInfinity});
REPORTER_ASSERT(reporter, r == SkRRect::MakeEmpty());
}
static const SkScalar kWidth = 100.0f;
static const SkScalar kHeight = 100.0f;
static void test_inset(skiatest::Reporter* reporter) {
SkRRect rr, rr2;
SkRect r = {0, 0, 100, 100};
rr.setRect(r);
rr.inset(-20, -20, &rr2);
REPORTER_ASSERT(reporter, rr2.isRect());
rr.inset(20, 20, &rr2);
REPORTER_ASSERT(reporter, rr2.isRect());
rr.inset(r.width() / 2, r.height() / 2, &rr2);
REPORTER_ASSERT(reporter, rr2.isEmpty());
rr.setRectXY(r, 20, 20);
rr.inset(19, 19, &rr2);
REPORTER_ASSERT(reporter, rr2.isSimple());
rr.inset(20, 20, &rr2);
REPORTER_ASSERT(reporter, rr2.isRect());
}
static void test_9patch_rrect(
skiatest::Reporter* reporter, const SkRect& rect, SkScalar l, SkScalar t, SkScalar r,
SkScalar b, bool checkRadii) {
SkRRect rr;
rr.setNinePatch(rect, l, t, r, b);
REPORTER_ASSERT(reporter, SkRRect::kNinePatch_Type == rr.type());
REPORTER_ASSERT(reporter, rr.rect() == rect);
if (checkRadii) {
// This test doesn't hold if the radii will be rescaled by SkRRect
SkRect ninePatchRadii = {l, t, r, b};
SkPoint rquad[4];
ninePatchRadii.toQuad(rquad);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, rquad[i] == rr.radii((SkRRect::Corner)i));
}
}
SkRRect rr2; // construct the same RR using the most general set function
SkVector radii[4] = {{l, t}, {r, t}, {r, b}, {l, b}};
rr2.setRectRadii(rect, radii);
REPORTER_ASSERT(reporter, rr2 == rr && rr2.getType() == rr.getType());
}
// Test out the basic API entry points
static void test_round_rect_basic(skiatest::Reporter* reporter) {
// Test out initialization methods
SkPoint zeroPt = {0, 0};
SkRRect empty;
empty.setEmpty();
REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == empty.type());
REPORTER_ASSERT(reporter, empty.rect().isEmpty());
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, zeroPt == empty.radii((SkRRect::Corner)i));
}
//----
SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight);
SkRRect rr1;
rr1.setRect(rect);
REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr1.type());
REPORTER_ASSERT(reporter, rr1.rect() == rect);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, zeroPt == rr1.radii((SkRRect::Corner)i));
}
SkRRect rr1_2; // construct the same RR using the most general set function
SkVector rr1_2_radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
rr1_2.setRectRadii(rect, rr1_2_radii);
REPORTER_ASSERT(reporter, rr1_2 == rr1 && rr1_2.getType() == rr1.getType());
SkRRect rr1_3; // construct the same RR using the nine patch set function
rr1_3.setNinePatch(rect, 0, 0, 0, 0);
REPORTER_ASSERT(reporter, rr1_3 == rr1 && rr1_3.getType() == rr1.getType());
//----
SkPoint halfPoint = {SkScalarHalf(kWidth), SkScalarHalf(kHeight)};
SkRRect rr2;
rr2.setOval(rect);
REPORTER_ASSERT(reporter, SkRRect::kOval_Type == rr2.type());
REPORTER_ASSERT(reporter, rr2.rect() == rect);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(
reporter, SkPointPriv::EqualsWithinTolerance(rr2.radii((SkRRect::Corner)i), halfPoint));
}
SkRRect rr2_2; // construct the same RR using the most general set function
SkVector rr2_2_radii[4] = {
{halfPoint.fX, halfPoint.fY},
{halfPoint.fX, halfPoint.fY},
{halfPoint.fX, halfPoint.fY},
{halfPoint.fX, halfPoint.fY}};
rr2_2.setRectRadii(rect, rr2_2_radii);
REPORTER_ASSERT(reporter, rr2_2 == rr2 && rr2_2.getType() == rr2.getType());
SkRRect rr2_3; // construct the same RR using the nine patch set function
rr2_3.setNinePatch(rect, halfPoint.fX, halfPoint.fY, halfPoint.fX, halfPoint.fY);
REPORTER_ASSERT(reporter, rr2_3 == rr2 && rr2_3.getType() == rr2.getType());
//----
SkPoint p = {5, 5};
SkRRect rr3;
rr3.setRectXY(rect, p.fX, p.fY);
REPORTER_ASSERT(reporter, SkRRect::kSimple_Type == rr3.type());
REPORTER_ASSERT(reporter, rr3.rect() == rect);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, p == rr3.radii((SkRRect::Corner)i));
}
SkRRect rr3_2; // construct the same RR using the most general set function
SkVector rr3_2_radii[4] = {{5, 5}, {5, 5}, {5, 5}, {5, 5}};
rr3_2.setRectRadii(rect, rr3_2_radii);
REPORTER_ASSERT(reporter, rr3_2 == rr3 && rr3_2.getType() == rr3.getType());
SkRRect rr3_3; // construct the same RR using the nine patch set function
rr3_3.setNinePatch(rect, 5, 5, 5, 5);
REPORTER_ASSERT(reporter, rr3_3 == rr3 && rr3_3.getType() == rr3.getType());
//----
test_9patch_rrect(reporter, rect, 10, 9, 8, 7, true);
{
// Test out the rrect from skia:3466
SkRect rect2 = SkRect::MakeLTRB(0.358211994f, 0.755430222f, 0.872866154f, 0.806214333f);
test_9patch_rrect(
reporter, rect2, 0.926942348f, 0.642850280f, 0.529063463f, 0.587844372f, false);
}
//----
SkPoint radii2[4] = {{0, 0}, {0, 0}, {50, 50}, {20, 50}};
SkRRect rr5;
rr5.setRectRadii(rect, radii2);
REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr5.type());
REPORTER_ASSERT(reporter, rr5.rect() == rect);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, radii2[i] == rr5.radii((SkRRect::Corner)i));
}
// Test out == & !=
REPORTER_ASSERT(reporter, empty != rr3);
REPORTER_ASSERT(reporter, rr3 != rr5);
}
// Test out the cases when the RR degenerates to a rect
static void test_round_rect_rects(skiatest::Reporter* reporter) {
SkRect r;
//----
SkRRect empty;
empty.setEmpty();
REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == empty.type());
r = empty.rect();
REPORTER_ASSERT(reporter, 0 == r.fLeft && 0 == r.fTop && 0 == r.fRight && 0 == r.fBottom);
//----
SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight);
SkRRect rr1;
rr1.setRectXY(rect, 0, 0);
REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr1.type());
r = rr1.rect();
REPORTER_ASSERT(reporter, rect == r);
//----
SkPoint radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
SkRRect rr2;
rr2.setRectRadii(rect, radii);
REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr2.type());
r = rr2.rect();
REPORTER_ASSERT(reporter, rect == r);
//----
SkPoint radii2[4] = {{0, 0}, {20, 20}, {50, 50}, {20, 50}};
SkRRect rr3;
rr3.setRectRadii(rect, radii2);
REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr3.type());
}
// Test out the cases when the RR degenerates to an oval
static void test_round_rect_ovals(skiatest::Reporter* reporter) {
//----
SkRect oval;
SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight);
SkRRect rr1;
rr1.setRectXY(rect, SkScalarHalf(kWidth), SkScalarHalf(kHeight));
REPORTER_ASSERT(reporter, SkRRect::kOval_Type == rr1.type());
oval = rr1.rect();
REPORTER_ASSERT(reporter, oval == rect);
}
// Test out the non-degenerate RR cases
static void test_round_rect_general(skiatest::Reporter* reporter) {
//----
SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight);
SkRRect rr1;
rr1.setRectXY(rect, 20, 20);
REPORTER_ASSERT(reporter, SkRRect::kSimple_Type == rr1.type());
//----
SkPoint radii[4] = {{0, 0}, {20, 20}, {50, 50}, {20, 50}};
SkRRect rr2;
rr2.setRectRadii(rect, radii);
REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr2.type());
}
// Test out questionable-parameter handling
static void test_round_rect_iffy_parameters(skiatest::Reporter* reporter) {
// When the radii exceed the base rect they are proportionally scaled down
// to fit
SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight);
SkPoint radii[4] = {{50, 100}, {100, 50}, {50, 100}, {100, 50}};
SkRRect rr1;
rr1.setRectRadii(rect, radii);
REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr1.type());
const SkPoint& p = rr1.radii(SkRRect::kUpperLeft_Corner);
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(p.fX, 33.33333f));
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(p.fY, 66.66666f));
// Negative radii should be capped at zero
SkRRect rr2;
rr2.setRectXY(rect, -10, -20);
REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr2.type());
const SkPoint& p2 = rr2.radii(SkRRect::kUpperLeft_Corner);
REPORTER_ASSERT(reporter, 0.0f == p2.fX);
REPORTER_ASSERT(reporter, 0.0f == p2.fY);
}
// Move a small box from the start position by (stepX, stepY) 'numSteps' times
// testing for containment in 'rr' at each step.
static void test_direction(
skiatest::Reporter* reporter, const SkRRect& rr, SkScalar initX, int stepX, SkScalar initY,
int stepY, int numSteps, const bool* contains) {
SkScalar x = initX, y = initY;
for (int i = 0; i < numSteps; ++i) {
SkRect test = SkRect::MakeXYWH(
x, y, stepX ? SkIntToScalar(stepX) : SK_Scalar1, stepY ? SkIntToScalar(stepY) : SK_Scalar1);
test.sort();
REPORTER_ASSERT(reporter, contains[i] == rr.contains(test));
x += stepX;
y += stepY;
}
}
// Exercise the RR's contains rect method
static void test_round_rect_contains_rect(skiatest::Reporter* reporter) {
static const int kNumRRects = 4;
static const SkVector gRadii[kNumRRects][4] = {
{{0, 0}, {0, 0}, {0, 0}, {0, 0}}, // rect
{{20, 20}, {20, 20}, {20, 20}, {20, 20}}, // circle
{{10, 10}, {10, 10}, {10, 10}, {10, 10}}, // simple
{{0, 0}, {20, 20}, {10, 10}, {30, 30}} // complex
};
SkRRect rrects[kNumRRects];
for (int i = 0; i < kNumRRects; ++i) {
rrects[i].setRectRadii(SkRect::MakeWH(40, 40), gRadii[i]);
}
// First test easy outs - boxes that are obviously out on
// each corner and edge
static const SkRect easyOuts[] = {
{-5, -5, 5, 5}, // NW
{15, -5, 20, 5}, // N
{35, -5, 45, 5}, // NE
{35, 15, 45, 20}, // E
{35, 45, 35, 45}, // SE
{15, 35, 20, 45}, // S
{-5, 35, 5, 45}, // SW
{-5, 15, 5, 20} // W
};
for (int i = 0; i < kNumRRects; ++i) {
for (size_t j = 0; j < SK_ARRAY_COUNT(easyOuts); ++j) {
REPORTER_ASSERT(reporter, !rrects[i].contains(easyOuts[j]));
}
}
// Now test non-trivial containment. For each compass
// point walk a 1x1 rect in from the edge of the bounding
// rect
static const int kNumSteps = 15;
bool answers[kNumRRects][8][kNumSteps] = {
// all the test rects are inside the degenerate rrect
{
// rect
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
},
// for the circle we expect 6 blocks to be out on the
// corners (then the rest in) and only the first block
// out on the vertical and horizontal axes (then
// the rest in)
{
// circle
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
},
// for the simple round rect we expect 3 out on
// the corners (then the rest in) and no blocks out
// on the vertical and horizontal axes
{
// simple RR
{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
},
// for the complex case the answer is different for each direction
{
// complex RR
// all in for NW (rect) corner (same as rect case)
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// only first block out for N (same as circle case)
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// first 6 blocks out for NE (same as circle case)
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// only first block out for E (same as circle case)
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// first 3 blocks out for SE (same as simple case)
{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// first two blocks out for S
{0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// first 9 blocks out for SW
{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1},
// first two blocks out for W (same as S)
{0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
}};
for (int i = 0; i < kNumRRects; ++i) {
test_direction(reporter, rrects[i], 0, 1, 0, 1, kNumSteps, answers[i][0]); // NW
test_direction(reporter, rrects[i], 19.5f, 0, 0, 1, kNumSteps, answers[i][1]); // N
test_direction(reporter, rrects[i], 40, -1, 0, 1, kNumSteps, answers[i][2]); // NE
test_direction(reporter, rrects[i], 40, -1, 19.5f, 0, kNumSteps, answers[i][3]); // E
test_direction(reporter, rrects[i], 40, -1, 40, -1, kNumSteps, answers[i][4]); // SE
test_direction(reporter, rrects[i], 19.5f, 0, 40, -1, kNumSteps, answers[i][5]); // S
test_direction(reporter, rrects[i], 0, 1, 40, -1, kNumSteps, answers[i][6]); // SW
test_direction(reporter, rrects[i], 0, 1, 19.5f, 0, kNumSteps, answers[i][7]); // W
}
}
// Called for a matrix that should cause SkRRect::transform to fail.
static void assert_transform_failure(
skiatest::Reporter* reporter, const SkRRect& orig, const SkMatrix& matrix) {
// The test depends on the fact that the original is not empty.
SkASSERT(!orig.isEmpty());
SkRRect dst;
dst.setEmpty();
const SkRRect copyOfDst = dst;
const SkRRect copyOfOrig = orig;
bool success = orig.transform(matrix, &dst);
// This transform should fail.
REPORTER_ASSERT(reporter, !success);
// Since the transform failed, dst should be unchanged.
REPORTER_ASSERT(reporter, copyOfDst == dst);
// original should not be modified.
REPORTER_ASSERT(reporter, copyOfOrig == orig);
REPORTER_ASSERT(reporter, orig != dst);
}
#define GET_RADII \
const SkVector& origUL = orig.radii(SkRRect::kUpperLeft_Corner); \
const SkVector& origUR = orig.radii(SkRRect::kUpperRight_Corner); \
const SkVector& origLR = orig.radii(SkRRect::kLowerRight_Corner); \
const SkVector& origLL = orig.radii(SkRRect::kLowerLeft_Corner); \
const SkVector& dstUL = dst.radii(SkRRect::kUpperLeft_Corner); \
const SkVector& dstUR = dst.radii(SkRRect::kUpperRight_Corner); \
const SkVector& dstLR = dst.radii(SkRRect::kLowerRight_Corner); \
const SkVector& dstLL = dst.radii(SkRRect::kLowerLeft_Corner)
// Called to test various transforms on a single SkRRect.
static void test_transform_helper(skiatest::Reporter* reporter, const SkRRect& orig) {
SkRRect dst;
dst.setEmpty();
// The identity matrix will duplicate the rrect.
bool success = orig.transform(SkMatrix::I(), &dst);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, orig == dst);
// Skew and Perspective make transform fail.
SkMatrix matrix;
matrix.reset();
matrix.setSkewX(SkIntToScalar(2));
assert_transform_failure(reporter, orig, matrix);
matrix.reset();
matrix.setSkewY(SkIntToScalar(3));
assert_transform_failure(reporter, orig, matrix);
matrix.reset();
matrix.setPerspX(4);
assert_transform_failure(reporter, orig, matrix);
matrix.reset();
matrix.setPerspY(5);
assert_transform_failure(reporter, orig, matrix);
// Rotation fails.
matrix.reset();
matrix.setRotate(SkIntToScalar(37));
assert_transform_failure(reporter, orig, matrix);
// Translate will keep the rect moved, but otherwise the same.
matrix.reset();
SkScalar translateX = SkIntToScalar(32);
SkScalar translateY = SkIntToScalar(15);
matrix.setTranslateX(translateX);
matrix.setTranslateY(translateY);
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, orig.radii((SkRRect::Corner)i) == dst.radii((SkRRect::Corner)i));
}
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height());
REPORTER_ASSERT(reporter, dst.rect().left() == orig.rect().left() + translateX);
REPORTER_ASSERT(reporter, dst.rect().top() == orig.rect().top() + translateY);
// Keeping the translation, but adding skew will make transform fail.
matrix.setSkewY(SkIntToScalar(7));
assert_transform_failure(reporter, orig, matrix);
// Scaling in -x will flip the round rect horizontally.
matrix.reset();
matrix.setScaleX(SkIntToScalar(-1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
// Radii have swapped in x.
REPORTER_ASSERT(reporter, origUL == dstUR);
REPORTER_ASSERT(reporter, origUR == dstUL);
REPORTER_ASSERT(reporter, origLR == dstLL);
REPORTER_ASSERT(reporter, origLL == dstLR);
}
// Width and height remain the same.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height());
// Right and left have swapped (sort of)
REPORTER_ASSERT(reporter, orig.rect().right() == -dst.rect().left());
// Top has stayed the same.
REPORTER_ASSERT(reporter, orig.rect().top() == dst.rect().top());
// Keeping the scale, but adding a persp will make transform fail.
matrix.setPerspX(7);
assert_transform_failure(reporter, orig, matrix);
// Scaling in -y will flip the round rect vertically.
matrix.reset();
matrix.setScaleY(SkIntToScalar(-1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
// Radii have swapped in y.
REPORTER_ASSERT(reporter, origUL == dstLL);
REPORTER_ASSERT(reporter, origUR == dstLR);
REPORTER_ASSERT(reporter, origLR == dstUR);
REPORTER_ASSERT(reporter, origLL == dstUL);
}
// Width and height remain the same.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height());
// Top and bottom have swapped (sort of)
REPORTER_ASSERT(reporter, orig.rect().top() == -dst.rect().bottom());
// Left has stayed the same.
REPORTER_ASSERT(reporter, orig.rect().left() == dst.rect().left());
// Scaling in -x and -y will swap in both directions.
matrix.reset();
matrix.setScaleY(SkIntToScalar(-1));
matrix.setScaleX(SkIntToScalar(-1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
REPORTER_ASSERT(reporter, origUL == dstLR);
REPORTER_ASSERT(reporter, origUR == dstLL);
REPORTER_ASSERT(reporter, origLR == dstUL);
REPORTER_ASSERT(reporter, origLL == dstUR);
}
// Width and height remain the same.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height());
REPORTER_ASSERT(reporter, orig.rect().top() == -dst.rect().bottom());
REPORTER_ASSERT(reporter, orig.rect().right() == -dst.rect().left());
// Scale in both directions.
SkScalar xScale = SkIntToScalar(3);
SkScalar yScale = 3.2f;
matrix.reset();
matrix.setScaleX(xScale);
matrix.setScaleY(yScale);
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
// Radii are scaled.
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(
reporter,
SkScalarNearlyEqual(
dst.radii((SkRRect::Corner)i).fX, orig.radii((SkRRect::Corner)i).fX * xScale));
REPORTER_ASSERT(
reporter,
SkScalarNearlyEqual(
dst.radii((SkRRect::Corner)i).fY, orig.radii((SkRRect::Corner)i).fY * yScale));
}
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().width(), orig.rect().width() * xScale));
REPORTER_ASSERT(
reporter, SkScalarNearlyEqual(dst.rect().height(), orig.rect().height() * yScale));
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().left(), orig.rect().left() * xScale));
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().top(), orig.rect().top() * yScale));
// a-----b d-----a
// | | -> | |
// | | Rotate 90 | |
// d-----c c-----b
matrix.reset();
matrix.setRotate(SkIntToScalar(90));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
// Radii have cycled clockwise and swapped their x and y axis.
REPORTER_ASSERT(reporter, dstUL.x() == origLL.y());
REPORTER_ASSERT(reporter, dstUL.y() == origLL.x());
REPORTER_ASSERT(reporter, dstUR.x() == origUL.y());
REPORTER_ASSERT(reporter, dstUR.y() == origUL.x());
REPORTER_ASSERT(reporter, dstLR.x() == origUR.y());
REPORTER_ASSERT(reporter, dstLR.y() == origUR.x());
REPORTER_ASSERT(reporter, dstLL.x() == origLR.y());
REPORTER_ASSERT(reporter, dstLL.y() == origLR.x());
}
// Width and height would get swapped.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width());
// a-----b b-----a c-----b
// | | -> | | -> | |
// | | Flip X | | Rotate 90 | |
// d-----c c-----d d-----a
matrix.reset();
matrix.setRotate(SkIntToScalar(90));
matrix.postScale(SkIntToScalar(-1), SkIntToScalar(1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
REPORTER_ASSERT(reporter, dstUL.x() == origLR.y());
REPORTER_ASSERT(reporter, dstUL.y() == origLR.x());
REPORTER_ASSERT(reporter, dstUR.x() == origUR.y());
REPORTER_ASSERT(reporter, dstUR.y() == origUR.x());
REPORTER_ASSERT(reporter, dstLR.x() == origUL.y());
REPORTER_ASSERT(reporter, dstLR.y() == origUL.x());
REPORTER_ASSERT(reporter, dstLL.x() == origLL.y());
REPORTER_ASSERT(reporter, dstLL.y() == origLL.x());
}
// Width and height would get swapped.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width());
// a-----b d-----a c-----b
// | | -> | | -> | |
// | | Rotate 90 | | Flip Y | |
// d-----c c-----b d-----a
//
// This is the same as Flip X and Rotate 90.
matrix.reset();
matrix.setScale(SkIntToScalar(1), SkIntToScalar(-1));
matrix.postRotate(SkIntToScalar(90));
SkRRect dst2;
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b b-----c c-----b
// | | -> | | -> | |
// | | Rotate 270 | | Flip X | |
// d-----c a-----d d-----a
matrix.reset();
matrix.setScale(SkIntToScalar(-1), SkIntToScalar(1));
matrix.postRotate(SkIntToScalar(270));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b d-----c c-----b
// | | -> | | -> | |
// | | Flip Y | | Rotate 270 | |
// d-----c a-----b d-----a
matrix.reset();
matrix.setRotate(SkIntToScalar(270));
matrix.postScale(SkIntToScalar(1), SkIntToScalar(-1));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b d-----a a-----d
// | | -> | | -> | |
// | | Rotate 90 | | Flip X | |
// d-----c c-----b b-----c
matrix.reset();
matrix.setScale(SkIntToScalar(-1), SkIntToScalar(1));
matrix.postRotate(SkIntToScalar(90));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
REPORTER_ASSERT(reporter, dstUL.x() == origUL.y());
REPORTER_ASSERT(reporter, dstUL.y() == origUL.x());
REPORTER_ASSERT(reporter, dstUR.x() == origLL.y());
REPORTER_ASSERT(reporter, dstUR.y() == origLL.x());
REPORTER_ASSERT(reporter, dstLR.x() == origLR.y());
REPORTER_ASSERT(reporter, dstLR.y() == origLR.x());
REPORTER_ASSERT(reporter, dstLL.x() == origUR.y());
REPORTER_ASSERT(reporter, dstLL.y() == origUR.x());
}
// Width and height would get swapped.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width());
// a-----b d-----c a-----d
// | | -> | | -> | |
// | | Flip Y | | Rotate 90 | |
// d-----c a-----b b-----c
// This is the same as rotate 90 and flip x.
matrix.reset();
matrix.setRotate(SkIntToScalar(90));
matrix.postScale(SkIntToScalar(1), SkIntToScalar(-1));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b b-----a a-----d
// | | -> | | -> | |
// | | Flip X | | Rotate 270 | |
// d-----c c-----d b-----c
matrix.reset();
matrix.setRotate(SkIntToScalar(270));
matrix.postScale(SkIntToScalar(-1), SkIntToScalar(1));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b b-----c a-----d
// | | -> | | -> | |
// | | Rotate 270 | | Flip Y | |
// d-----c a-----d b-----c
matrix.reset();
matrix.setScale(SkIntToScalar(1), SkIntToScalar(-1));
matrix.postRotate(SkIntToScalar(270));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b b-----a c-----d b-----c
// | | -> | | -> | | -> | |
// | | Flip X | | Flip Y | | Rotate 90 | |
// d-----c c-----d b-----a a-----d
//
// This is the same as rotation by 270.
matrix.reset();
matrix.setRotate(SkIntToScalar(90));
matrix.postScale(SkIntToScalar(-1), SkIntToScalar(-1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
{
GET_RADII;
// Radii have cycled clockwise and swapped their x and y axis.
REPORTER_ASSERT(reporter, dstUL.x() == origUR.y());
REPORTER_ASSERT(reporter, dstUL.y() == origUR.x());
REPORTER_ASSERT(reporter, dstUR.x() == origLR.y());
REPORTER_ASSERT(reporter, dstUR.y() == origLR.x());
REPORTER_ASSERT(reporter, dstLR.x() == origLL.y());
REPORTER_ASSERT(reporter, dstLR.y() == origLL.x());
REPORTER_ASSERT(reporter, dstLL.x() == origUL.y());
REPORTER_ASSERT(reporter, dstLL.y() == origUL.x());
}
// Width and height would get swapped.
REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height());
REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width());
// a-----b b-----c
// | | -> | |
// | | Rotate 270 | |
// d-----c a-----d
//
dst2.setEmpty();
matrix.reset();
matrix.setRotate(SkIntToScalar(270));
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, dst == dst2);
// a-----b b-----a c-----d d-----a
// | | -> | | -> | | -> | |
// | | Flip X | | Flip Y | | Rotate 270 | |
// d-----c c-----d b-----a c-----b
//
// This is the same as rotation by 90 degrees.
matrix.reset();
matrix.setRotate(SkIntToScalar(270));
matrix.postScale(SkIntToScalar(-1), SkIntToScalar(-1));
dst.setEmpty();
success = orig.transform(matrix, &dst);
REPORTER_ASSERT(reporter, success);
matrix.reset();
matrix.setRotate(SkIntToScalar(90));
dst2.setEmpty();
success = orig.transform(matrix, &dst2);
REPORTER_ASSERT(reporter, dst == dst2);
}
static void test_round_rect_transform(skiatest::Reporter* reporter) {
SkRRect rrect;
{
SkRect r = {0, 0, kWidth, kHeight};
rrect.setRectXY(r, SkIntToScalar(4), SkIntToScalar(7));
test_transform_helper(reporter, rrect);
}
{
SkRect r = {SkIntToScalar(5), SkIntToScalar(15), SkIntToScalar(27), SkIntToScalar(34)};
SkVector radii[4] = {
{0, SkIntToScalar(1)},
{SkIntToScalar(2), SkIntToScalar(3)},
{SkIntToScalar(4), SkIntToScalar(5)},
{SkIntToScalar(6), SkIntToScalar(7)}};
rrect.setRectRadii(r, radii);
test_transform_helper(reporter, rrect);
}
}
// Test out the case where an oval already off in space is translated/scaled
// further off into space - yielding numerical issues when the rect & radii
// are transformed separatly
// BUG=skia:2696
static void test_issue_2696(skiatest::Reporter* reporter) {
SkRRect rrect;
SkRect r = {28443.8594f, 53.1428604f, 28446.7148f, 56.0000038f};
rrect.setOval(r);
SkMatrix xform;
xform.setAll(2.44f, 0.0f, 485411.7f, 0.0f, 2.44f, -438.7f, 0.0f, 0.0f, 1.0f);
SkRRect dst;
bool success = rrect.transform(xform, &dst);
REPORTER_ASSERT(reporter, success);
SkScalar halfWidth = SkScalarHalf(dst.width());
SkScalar halfHeight = SkScalarHalf(dst.height());
for (int i = 0; i < 4; ++i) {
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.radii((SkRRect::Corner)i).fX, halfWidth));
REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.radii((SkRRect::Corner)i).fY, halfHeight));
}
}
void test_read_rrect(skiatest::Reporter* reporter, const SkRRect& rrect, bool shouldEqualSrc) {
// It would be cleaner to call rrect.writeToMemory into a buffer. However, writeToMemory asserts
// that the rrect is valid and our caller may have fiddled with the internals of rrect to make
// it invalid.
const void* buffer = reinterpret_cast<const void*>(&rrect);
SkRRect deserialized;
size_t size = deserialized.readFromMemory(buffer, sizeof(SkRRect));
REPORTER_ASSERT(reporter, size == SkRRect::kSizeInMemory);
REPORTER_ASSERT(reporter, deserialized.isValid());
if (shouldEqualSrc) {
REPORTER_ASSERT(reporter, rrect == deserialized);
}
}
static void test_read(skiatest::Reporter* reporter) {
static const SkRect kRect = {10.f, 10.f, 20.f, 20.f};
static const SkRect kNaNRect = {10.f, 10.f, 20.f, SK_ScalarNaN};
static const SkRect kInfRect = {10.f, 10.f, SK_ScalarInfinity, 20.f};
SkRRect rrect;
test_read_rrect(reporter, SkRRect::MakeEmpty(), true);
test_read_rrect(reporter, SkRRect::MakeRect(kRect), true);
// These get coerced to empty.
test_read_rrect(reporter, SkRRect::MakeRect(kInfRect), true);
test_read_rrect(reporter, SkRRect::MakeRect(kNaNRect), true);
rrect.setRect(kRect);
SkRect* innerRect = reinterpret_cast<SkRect*>(&rrect);
SkASSERT(*innerRect == kRect);
*innerRect = kInfRect;
test_read_rrect(reporter, rrect, false);
*innerRect = kNaNRect;
test_read_rrect(reporter, rrect, false);
test_read_rrect(reporter, SkRRect::MakeOval(kRect), true);
test_read_rrect(reporter, SkRRect::MakeOval(kInfRect), true);
test_read_rrect(reporter, SkRRect::MakeOval(kNaNRect), true);
rrect.setOval(kRect);
*innerRect = kInfRect;
test_read_rrect(reporter, rrect, false);
*innerRect = kNaNRect;
test_read_rrect(reporter, rrect, false);
test_read_rrect(reporter, SkRRect::MakeRectXY(kRect, 5.f, 5.f), true);
// rrect should scale down the radii to make this legal
test_read_rrect(reporter, SkRRect::MakeRectXY(kRect, 5.f, 400.f), true);
static const SkVector kRadii[4] = {{0.5f, 1.f}, {1.5f, 2.f}, {2.5f, 3.f}, {3.5f, 4.f}};
rrect.setRectRadii(kRect, kRadii);
test_read_rrect(reporter, rrect, true);
SkScalar* innerRadius = reinterpret_cast<SkScalar*>(&rrect) + 6;
SkASSERT(*innerRadius == 1.5f);
*innerRadius = 400.f;
test_read_rrect(reporter, rrect, false);
*innerRadius = SK_ScalarInfinity;
test_read_rrect(reporter, rrect, false);
*innerRadius = SK_ScalarNaN;
test_read_rrect(reporter, rrect, false);
*innerRadius = -10.f;
test_read_rrect(reporter, rrect, false);
}
static void test_inner_bounds(skiatest::Reporter* reporter) {
// Because InnerBounds() insets the computed bounds slightly to correct for numerical inaccuracy
// when finding the maximum inscribed point on a curve, we use a larger epsilon for comparing
// expected areas.
static constexpr SkScalar kEpsilon = 0.005f;
// Test that an empty rrect reports empty inner bounds
REPORTER_ASSERT(reporter, SkRRectPriv::InnerBounds(SkRRect::MakeEmpty()).isEmpty());
// Test that a rect rrect reports itself as the inner bounds
SkRect r = SkRect::MakeLTRB(0, 1, 2, 3);
REPORTER_ASSERT(reporter, SkRRectPriv::InnerBounds(SkRRect::MakeRect(r)) == r);
// Test that a circle rrect has an inner bounds area equal to 2*radius^2
float radius = 5.f;
SkRect inner =
SkRRectPriv::InnerBounds(SkRRect::MakeOval(SkRect::MakeWH(2.f * radius, 2.f * radius)));
REPORTER_ASSERT(
reporter,
SkScalarNearlyEqual(inner.width() * inner.height(), 2.f * radius * radius, kEpsilon));
float width = 20.f;
float height = 25.f;
r = SkRect::MakeWH(width, height);
// Test that a rrect with circular corners has an area equal to:
float expectedArea =
(2.f * radius * radius) + // area in the 4 circular corners
(width - 2.f * radius) * (height - 2.f * radius) + // inner area excluding corners and edges
SK_ScalarSqrt2 * radius * (width - 2.f * radius) + // two horiz. rects between corners
SK_ScalarSqrt2 * radius * (height - 2.f * radius); // two vert. rects between corners
inner = SkRRectPriv::InnerBounds(SkRRect::MakeRectXY(r, radius, radius));
REPORTER_ASSERT(
reporter, SkScalarNearlyEqual(inner.width() * inner.height(), expectedArea, kEpsilon));
// Test that a rrect with a small y radius but large x radius selects the horizontal interior
SkRRect rr = SkRRect::MakeRectXY(r, 2.f * radius, 0.1f * radius);
REPORTER_ASSERT(
reporter, SkRRectPriv::InnerBounds(rr) ==
SkRect::MakeLTRB(0.f, 0.1f * radius, width, height - 0.1f * radius));
// And vice versa with large y and small x radii
rr = SkRRect::MakeRectXY(r, 0.1f * radius, 2.f * radius);
REPORTER_ASSERT(
reporter, SkRRectPriv::InnerBounds(rr) ==
SkRect::MakeLTRB(0.1f * radius, 0.f, width - 0.1f * radius, height));
// Test a variety of complex round rects produce a non-empty rect that is at least contained,
// and larger than the inner area avoiding all corners.
SkRandom rng;
for (int i = 0; i < 1000; ++i) {
float maxRadiusX = rng.nextRangeF(0.f, 40.f);
float maxRadiusY = rng.nextRangeF(0.f, 40.f);
float innerWidth = rng.nextRangeF(0.f, 40.f);
float innerHeight = rng.nextRangeF(0.f, 40.f);
SkVector radii[4] = {
{rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)},
{rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)},
{rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)},
{rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)}};
float maxLeft = std::max(radii[0].fX, radii[3].fX);
float maxTop = std::max(radii[0].fY, radii[1].fY);
float maxRight = std::max(radii[1].fX, radii[2].fX);
float maxBottom = std::max(radii[2].fY, radii[3].fY);
SkRect outer =
SkRect::MakeWH(maxLeft + maxRight + innerWidth, maxTop + maxBottom + innerHeight);
rr.setRectRadii(outer, radii);
SkRect maxInner = SkRRectPriv::InnerBounds(rr);
// Test upper limit on the size of 'maxInner'
REPORTER_ASSERT(reporter, outer.contains(maxInner));
REPORTER_ASSERT(reporter, rr.contains(maxInner));
// Test lower limit on the size of 'maxInner'
SkRect inner = SkRect::MakeXYWH(maxLeft, maxTop, innerWidth, innerHeight);
inner.inset(kEpsilon, kEpsilon);
if (inner.isSorted()) {
REPORTER_ASSERT(reporter, maxInner.contains(inner));
} else {
// Flipped from the inset, just test two points of inner
float midX = maxLeft + 0.5f * innerWidth;
float midY = maxTop + 0.5f * innerHeight;
REPORTER_ASSERT(reporter, maxInner.contains(midX, maxTop));
REPORTER_ASSERT(reporter, maxInner.contains(midX, maxTop + innerHeight));
REPORTER_ASSERT(reporter, maxInner.contains(maxLeft, midY));
REPORTER_ASSERT(reporter, maxInner.contains(maxLeft + innerWidth, midY));
}
}
}
namespace {
// Helper to test expected intersection, relying on the fact that all round rect intersections
// will have their bounds equal to the intersection of the bounds of the input round rects, and
// their corner radii will be a one of A's, B's, or rectangular.
enum CornerChoice : uint8_t { kA, kB, kRect };
static void verify_success(
skiatest::Reporter* reporter, const SkRRect& a, const SkRRect& b, CornerChoice tl,
CornerChoice tr, CornerChoice br, CornerChoice bl) {
static const SkRRect kRect = SkRRect::MakeEmpty(); // has (0,0) for all corners
// Compute expected round rect intersection given bounds of A and B, and the specified
// corner choices for the 4 corners.
SkRect expectedBounds;
SkAssertResult(expectedBounds.intersect(a.rect(), b.rect()));
SkVector radii[4] = {
(tl == kA ? a : (tl == kB ? b : kRect)).radii(SkRRect::kUpperLeft_Corner),
(tr == kA ? a : (tr == kB ? b : kRect)).radii(SkRRect::kUpperRight_Corner),
(br == kA ? a : (br == kB ? b : kRect)).radii(SkRRect::kLowerRight_Corner),
(bl == kA ? a : (bl == kB ? b : kRect)).radii(SkRRect::kLowerLeft_Corner)};
SkRRect expected;
expected.setRectRadii(expectedBounds, radii);
SkRRect actual = SkRRectPriv::ConservativeIntersect(a, b);
// Intersections are commutative so ba and ab should be the same
REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(b, a));
// Intersection of the result with either A or B should remain the intersection
REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(actual, a));
REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(actual, b));
// Bounds of intersection round rect should equal intersection of bounds of a and b
REPORTER_ASSERT(reporter, actual.rect() == expectedBounds);
// Use PathOps to confirm that the explicit round rect is correct.
SkPath aPath, bPath, expectedPath;
aPath.addRRect(a);
bPath.addRRect(b);
SkAssertResult(Op(aPath, bPath, kIntersect_SkPathOp, &expectedPath));
// The isRRect() heuristics in SkPath are based on having called addRRect(), so a path from
// path ops that is a rounded rectangle will return false. However, if test XOR expected is
// empty, then we know that the shapes were the same.
SkPath testPath;
testPath.addRRect(actual);
SkPath empty;
SkAssertResult(Op(testPath, expectedPath, kXOR_SkPathOp, &empty));
REPORTER_ASSERT(reporter, empty.isEmpty());
}
static void verify_failure(skiatest::Reporter* reporter, const SkRRect& a, const SkRRect& b) {
SkRRect intersection = SkRRectPriv::ConservativeIntersect(a, b);
// Expected the intersection to fail (no intersection or complex intersection is not
// disambiguated).
REPORTER_ASSERT(reporter, intersection.isEmpty());
REPORTER_ASSERT(reporter, SkRRectPriv::ConservativeIntersect(b, a).isEmpty());
}
} // namespace
static void test_conservative_intersection(skiatest::Reporter* reporter) {
// Helper to inline making an inset round rect
auto make_inset = [](const SkRRect& r, float dx, float dy) {
SkRRect i = r;
i.inset(dx, dy);
return i;
};
// A is a wide, short round rect
SkRRect a = SkRRect::MakeRectXY({0.f, 4.f, 16.f, 12.f}, 2.f, 2.f);
// B is a narrow, tall round rect
SkRRect b = SkRRect::MakeRectXY({4.f, 0.f, 12.f, 16.f}, 3.f, 3.f);
// NOTE: As positioned by default, A and B intersect as the rectangle {4, 4, 12, 12}.
// There is a 2 px buffer between the corner curves of A and the vertical edges of B, and
// a 1 px buffer between the corner curves of B and the horizontal edges of A. Since the shapes
// form a symmetric rounded cross, we can easily test edge and corner combinations by simply
// flipping signs and/or swapping x and y offsets.
// Successful intersection operations:
// - for clarity these are formed by moving A around to intersect with B in different ways.
// - the expected bounds of the round rect intersection is calculated automatically
// in check_success, so all we have to specify are the expected corner radii
// A and B intersect as a rectangle
verify_success(reporter, a, b, kRect, kRect, kRect, kRect);
// Move A to intersect B on a vertical edge, preserving two corners of A inside B
verify_success(reporter, a.makeOffset(6.f, 0.f), b, kA, kRect, kRect, kA);
verify_success(reporter, a.makeOffset(-6.f, 0.f), b, kRect, kA, kA, kRect);
// Move B to intersect A on a horizontal edge, preserving two corners of B inside A
verify_success(reporter, a, b.makeOffset(0.f, 6.f), kB, kB, kRect, kRect);
verify_success(reporter, a, b.makeOffset(0.f, -6.f), kRect, kRect, kB, kB);
// Move A to intersect B on a corner, preserving one corner of A and one of B
verify_success(reporter, a.makeOffset(-7.f, -8.f), b, kB, kRect, kA, kRect); // TL of B
verify_success(reporter, a.makeOffset(7.f, -8.f), b, kRect, kB, kRect, kA); // TR of B
verify_success(reporter, a.makeOffset(7.f, 8.f), b, kA, kRect, kB, kRect); // BR of B
verify_success(reporter, a.makeOffset(-7.f, 8.f), b, kRect, kA, kRect, kB); // BL of B
// An inset is contained inside the original (note that SkRRect::inset modifies radii too) so
// is returned unmodified when intersected.
verify_success(reporter, a, make_inset(a, 1.f, 1.f), kB, kB, kB, kB);
verify_success(reporter, make_inset(b, 2.f, 2.f), b, kA, kA, kA, kA);
// A rectangle exactly matching the corners of the rrect bounds keeps the rrect radii,
// regardless of whether or not it's the 1st or 2nd arg to ConservativeIntersect.
SkRRect c = SkRRect::MakeRectXY({0.f, 0.f, 10.f, 10.f}, 2.f, 2.f);
SkRRect cT = SkRRect::MakeRect({0.f, 0.f, 10.f, 5.f});
verify_success(reporter, c, cT, kA, kA, kRect, kRect);
verify_success(reporter, cT, c, kB, kB, kRect, kRect);
SkRRect cB = SkRRect::MakeRect({0.f, 5.f, 10.f, 10.});
verify_success(reporter, c, cB, kRect, kRect, kA, kA);
verify_success(reporter, cB, c, kRect, kRect, kB, kB);
SkRRect cL = SkRRect::MakeRect({0.f, 0.f, 5.f, 10.f});
verify_success(reporter, c, cL, kA, kRect, kRect, kA);
verify_success(reporter, cL, c, kB, kRect, kRect, kB);
SkRRect cR = SkRRect::MakeRect({5.f, 0.f, 10.f, 10.f});
verify_success(reporter, c, cR, kRect, kA, kA, kRect);
verify_success(reporter, cR, c, kRect, kB, kB, kRect);
// Failed intersection operations:
// A and B's bounds do not intersect
verify_failure(reporter, a.makeOffset(32.f, 0.f), b);
// A and B's bounds intersect, but corner curves do not -> no intersection
verify_failure(reporter, a.makeOffset(11.5f, -11.5f), b);
// A is empty -> no intersection
verify_failure(reporter, SkRRect::MakeEmpty(), b);
// A is contained in B, but is too close to the corner curves for the conservative
// approximations to construct a valid round rect intersection.
verify_failure(reporter, make_inset(b, 0.3f, 0.3f), b);
// A intersects a straight edge, but not far enough for B to contain A's corners
verify_failure(reporter, a.makeOffset(2.5f, 0.f), b);
verify_failure(reporter, a.makeOffset(-2.5f, 0.f), b);
// And vice versa for B into A
verify_failure(reporter, a, b.makeOffset(0.f, 1.5f));
verify_failure(reporter, a, b.makeOffset(0.f, -1.5f));
// A intersects a straight edge and part of B's corner
verify_failure(reporter, a.makeOffset(5.f, -2.f), b);
verify_failure(reporter, a.makeOffset(-5.f, -2.f), b);
verify_failure(reporter, a.makeOffset(5.f, 2.f), b);
verify_failure(reporter, a.makeOffset(-5.f, 2.f), b);
// And vice versa
verify_failure(reporter, a, b.makeOffset(3.f, -5.f));
verify_failure(reporter, a, b.makeOffset(-3.f, -5.f));
verify_failure(reporter, a, b.makeOffset(3.f, 5.f));
verify_failure(reporter, a, b.makeOffset(-3.f, 5.f));
// A intersects B on a corner, but the corner curves overlap each other
verify_failure(reporter, a.makeOffset(8.f, 10.f), b);
verify_failure(reporter, a.makeOffset(-8.f, 10.f), b);
verify_failure(reporter, a.makeOffset(8.f, -10.f), b);
verify_failure(reporter, a.makeOffset(-8.f, -10.f), b);
// Another variant of corners overlapping, this is two circles of radius r that overlap by r
// pixels (e.g. the leftmost point of the right circle touches the center of the left circle).
// The key difference with the above case is that the intersection of the circle bounds have
// corners that are contained in both circles, but because it is only r wide, can not satisfy
// all corners having radii = r.
float r = 100.f;
a = SkRRect::MakeOval(SkRect::MakeWH(2 * r, 2 * r));
verify_failure(reporter, a, a.makeOffset(r, 0.f));
}
DEF_TEST(RoundRect, reporter) {
test_round_rect_basic(reporter);
test_round_rect_rects(reporter);
test_round_rect_ovals(reporter);
test_round_rect_general(reporter);
test_round_rect_iffy_parameters(reporter);
test_inset(reporter);
test_round_rect_contains_rect(reporter);
test_round_rect_transform(reporter);
test_issue_2696(reporter);
test_tricky_radii(reporter);
test_empty_crbug_458524(reporter);
test_empty(reporter);
test_read(reporter);
test_inner_bounds(reporter);
test_conservative_intersection(reporter);
}
DEF_TEST(RRect_fuzzer_regressions, r) {
{
unsigned char buf[] = {0x0a, 0x00, 0x00, 0xff, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f,
0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
0x7f, 0x7f, 0x7f, 0x02, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x02, 0x00};
REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf)));
}
{
unsigned char buf[] = {0x5d, 0xff, 0xff, 0x5d, 0x0a, 0x60, 0x0a, 0x0a, 0x0a, 0x7e, 0x0a, 0x5a,
0x0a, 0x12, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a,
0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x00, 0x00, 0x00, 0x0a,
0x0a, 0x0a, 0x0a, 0x26, 0x0a, 0x0a, 0x0a, 0x0a, 0xff, 0xff, 0x0a, 0x0a};
REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf)));
}
{
unsigned char buf[] = {0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x04, 0xdd, 0xdd, 0x15,
0xfe, 0x00, 0x00, 0x04, 0x05, 0x7e, 0x00, 0x00, 0x00, 0xff, 0x08, 0x04,
0xff, 0xff, 0xfe, 0xfe, 0xff, 0x32, 0x32, 0x32, 0x32, 0x00, 0x32, 0x32,
0x04, 0xdd, 0x3d, 0x1c, 0xfe, 0x89, 0x04, 0x0a, 0x0e, 0x05, 0x7e, 0x0a};
REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf)));
}
}
| 40.026134 | 100 | 0.634002 | NearTox |
d0c577cd46beffe2d8a2321287d9a7881fe253aa | 1,777 | cpp | C++ | project/src/Leaderboard.cpp | lorenzovngl/progetto-grafica | 0f222e62da703c323cdc0f7edb39ee89d3fe566a | [
"MIT"
] | null | null | null | project/src/Leaderboard.cpp | lorenzovngl/progetto-grafica | 0f222e62da703c323cdc0f7edb39ee89d3fe566a | [
"MIT"
] | null | null | null | project/src/Leaderboard.cpp | lorenzovngl/progetto-grafica | 0f222e62da703c323cdc0f7edb39ee89d3fe566a | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#endif
#include "headers/Leaderboard.h"
Leaderboard::Leaderboard(char *username){
setUsename(username);
}
char *Leaderboard::getUsename() {
return mUsername;
}
void Leaderboard::setUsename(char *username) {
strcpy(mUsername, username);
}
void Leaderboard::setNumBuoys(int num){
mNumBuoys = num;
}
Leaderboard::LBItem** Leaderboard::read(){
char name[50];
int num, score;
FILE *file = fopen("leaderboard.txt","r");
int i = 0;
while (fscanf(file, "%s\t%d\t%d\n", name, &num, &score) != EOF && i < LEADERBOARD_LENGHT){
int millis = score;
int sec = millis/1000;
int min = sec/60;
items[i] = new LBItem(name, num, score);
i++;
};
while (i < LEADERBOARD_LENGHT){
items[i] = nullptr;
i++;
}
fclose(file);
return items;
}
void Leaderboard::insert(int timeScore) {
read();
int i = 0, j;
// Inserisco il punteggio nella posizione giusta per mantenere l'ordinamento decrescente
while (i < LEADERBOARD_LENGHT && items[i] != nullptr && items[i]->time/items[i]->numBuoys <= timeScore/mNumBuoys){
i++;
}
for (j = LEADERBOARD_LENGHT - 1; j > i; j--){
items[j] = items[j-1];
}
items[j] = new LBItem(mUsername, mNumBuoys, timeScore);
FILE *file = fopen("leaderboard.txt","w");
for (i = 0; i < LEADERBOARD_LENGHT && items[i] != nullptr; i++){
fprintf(file, "%s\t%d\t%d\n", items[i]->name, items[i]->numBuoys, items[i]->time);
}
fclose(file);
} | 24.342466 | 118 | 0.608329 | lorenzovngl |
d0c69747e40715b632f725eaaa10ec3221eca15b | 2,506 | cc | C++ | rxcppuniq/base/monitoring.cc | google/rxcppuniq | 2c21f54de1d0d9c3ddb392f2cb83a3de540ba72a | [
"Apache-2.0"
] | 9 | 2019-09-11T17:16:29.000Z | 2022-02-26T07:02:38.000Z | rxcppuniq/base/monitoring.cc | google/rxcppuniq | 2c21f54de1d0d9c3ddb392f2cb83a3de540ba72a | [
"Apache-2.0"
] | 1 | 2019-09-11T17:51:25.000Z | 2019-09-11T18:10:26.000Z | rxcppuniq/base/monitoring.cc | google/rxcppuniq | 2c21f54de1d0d9c3ddb392f2cb83a3de540ba72a | [
"Apache-2.0"
] | 6 | 2019-11-06T17:20:49.000Z | 2021-10-14T16:08:05.000Z | /*
* Copyright 2017 Google LLC
*
* 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 "rxcppuniq/base/monitoring.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> /* for abort() */
#include <string.h>
#include <cstring>
#include "absl/strings/str_cat.h"
#include "rxcppuniq/base/platform.h"
namespace rx {
namespace internal {
Logger* logger = new Logger();
const char* LogSeverityString(absl::LogSeverity severity) {
switch (severity) {
case absl::LogSeverity::kInfo:
return "I";
case absl::LogSeverity::kWarning:
return "W";
case absl::LogSeverity::kError:
return "E";
case absl::LogSeverity::kFatal:
return "F";
default:
return "U";
}
}
void Logger::Log(const char* file, int line, absl::LogSeverity severity,
const char* message) {
auto base_file_name = BaseName(file);
fprintf(stderr, "%c %s:%d %s\n", absl::LogSeverityName(severity)[0],
base_file_name.c_str(), line, message);
}
StatusBuilder::StatusBuilder(StatusCode code, const char* file, int line)
: file_(file), line_(line), code_(code), message_() {}
StatusBuilder::StatusBuilder(StatusBuilder const& other)
: file_(other.file_),
line_(other.line_),
code_(other.code_),
message_(other.message_.str()) {}
StatusBuilder::operator Status() {
Status result;
result.set_code(code_);
const auto message_str = message_.str();
if (code_ != OK) {
result.set_message(absl::StrCat("(at ", BaseName(file_), ":",
std::to_string(line_), ") ", message_str));
if (log_severity_ != kNoLog) {
logger->Log(file_, line_, log_severity_,
absl::StrCat("[", code_, "] ", message_str).c_str());
if (log_severity_ == absl::LogSeverity::kFatal) {
abort();
}
}
}
return result;
}
const Status* kOkStatus = new Status();
Status const* OkStatus() { return kOkStatus; }
} // namespace internal
} // namespace rx
| 27.844444 | 79 | 0.655626 | google |
d0c98eb31a226532c4a5029954799c1c75cf8359 | 906 | cpp | C++ | CSES/Sorting And Searching/ArrayDivision.cpp | ShraxO1/OneDayOneAlgo | 68fe90f642985680e4014fdd1fe2ecd30097661d | [
"MIT"
] | 32 | 2020-05-23T07:40:31.000Z | 2021-02-02T18:14:30.000Z | CSES/Sorting And Searching/ArrayDivision.cpp | ShraxO1/OneDayOneAlgo | 68fe90f642985680e4014fdd1fe2ecd30097661d | [
"MIT"
] | 45 | 2020-05-22T10:30:51.000Z | 2020-12-28T08:17:13.000Z | CSES/Sorting And Searching/ArrayDivision.cpp | ShraxO1/OneDayOneAlgo | 68fe90f642985680e4014fdd1fe2ecd30097661d | [
"MIT"
] | 31 | 2020-05-22T10:18:16.000Z | 2020-10-23T07:52:35.000Z | #include <iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define OJ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
#define FIO \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define ll long long int
int n,k,a[500000];
bool ok(ll mid) {
int num = 0, cur = 0;
while (num < k && cur < n) {
ll sum = 0;
while (cur < n && sum+a[cur] <= mid) sum += a[cur++];
num ++;
}
return cur == n;
}
int main(){
//OJ;
cin >> n >> k;
ll sum = 0;
for(ll i=0; i<n; i++){
cin >> a[i];
sum+=a[i];
}
ll lo = 0, hi = 1e18;
while (lo < hi) {
ll mid = (lo+hi)/2;
if (ok(mid)) hi = mid;
else lo = mid+1;
}
cout << lo << endl;;
return 0;
}
| 19.695652 | 61 | 0.442605 | ShraxO1 |
d0ca3b6854e3be3a7201824ce806213f065e94ad | 26,020 | cpp | C++ | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenManifest.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenManifest.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenManifest.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BlueprintNativeCodeGenManifest.h"
#include "UObject/Package.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Misc/App.h"
#include "Engine/Blueprint.h"
#include "Dom/JsonObject.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
#include "PlatformInfo.h"
#include "IBlueprintCompilerCppBackendModule.h"
#include "JsonObjectConverter.h"
DEFINE_LOG_CATEGORY_STATIC(LogNativeCodeGenManifest, Log, All);
/*******************************************************************************
* BlueprintNativeCodeGenManifestImpl
******************************************************************************/
namespace BlueprintNativeCodeGenManifestImpl
{
static const int64 CPF_NoFlags = 0x00;
static const FString ManifestFileExt = TEXT(".BpCodeGenManifest.json");
static const FString CppFileExt = TEXT(".cpp");
static const FString HeaderFileExt = TEXT(".h");
static const FString HeaderSubDir = TEXT("Public");
static const FString CppSubDir = TEXT("Private");
static const FString ModuleBuildFileExt = TEXT(".Build.cs");
static const FString PreviewFilePostfix = TEXT("-Preview");
static const FString PluginFileExt = TEXT(".uplugin");
static const FString SourceSubDir = TEXT("Source");
static const FString EditorModulePostfix = TEXT("Editor");
static const int32 RootManifestId = -1;
/**
* Populates the provided manifest object with data from the specified file.
*
* @param FilePath A json file path, denoting the file you want loaded and serialized in.
* @param Manifest The target object that you want filled out with data from the file.
* @return True if the manifest was successfully loaded, otherwise false.
*/
static bool LoadManifest(const FString& FilePath, FBlueprintNativeCodeGenManifest* Manifest);
/**
* Helper function that homogenizes file/directory paths so that they can be
* compared for equivalence against others.
*
* @param DirectoryPath The path that you want sanitized.
* @return A equivalent file/directory path, standardized for comparisons.
*/
static FString GetComparibleDirPath(const FString& DirectoryPath);
/**
* Retrieves the sub-directory for either header or cpp source files
* (depending on which was requested).
*
* @param SourceType Defines the type of source file to return for (header or cpp).
* @return A directory name for the specified source file type.
*/
static const FString& GetSourceSubDir(const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType);
/**
* Retrieves the extension for either header or cpp source files (depending
* on which was requested).
*
* @param SourceType Defines the type of source file to return for (header or cpp).
* @return A file extension (including the leading dot), for the specified source file type.
*/
static const FString& GetSourceFileExt(const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType);
/**
* Constructs a source file path for the specified asset.
*
* @param TargetPaths Specified the destination directory for the file.
* @param Asset The asset you want a header file for.
* @param SourceType Defines the type of source file to generate for (header or cpp).
* @return A target file path for the specified asset to save a header to.
*/
static FString GenerateSourceFileSavePath(const FBlueprintNativeCodeGenPaths& TargetPaths, const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions, const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType);
/**
*
*
* @param TargetPaths
* @param Asset
* @return
*/
static FString GenerateUnconvertedWrapperPath(const FBlueprintNativeCodeGenPaths& TargetPaths, const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions);
/**
* Coordinates with the code-gen backend, to produce a base filename (one
* without a file extension).
*
* @param Asset The asset you want a filename for.
* @return A filename (without extension) that matches the #include statements generated by the backend.
*/
static FString GetBaseFilename(const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions);
/**
* Collects native packages (which reflect distinct modules) that the
* specified object relies upon.
*
* @param AssetObj The object you want dependencies for.
* @param DependenciesOut An output array, which will be filled out with module packages that the target object relies upon.
* @return False if the function failed to collect dependencies for the specified object.
*/
static bool GatherModuleDependencies(const UObject* AssetObj, TArray<UPackage*>& DependenciesOut);
/**
* Obtains the reflected name for the native field (class/enum/struct) that
* we'll generate to replace the specified asset.
*
* @param Asset The asset you want a name from.
* @return The name of the asset field (class/enum/struct).
*/
static FString GetFieldName(const FAssetData& Asset);
/**
* The object returned by FAssetData::GetAsset() doesn't always give us the
* target object that will be replaced (for Blueprint's, it would be the
* class instead). So this helper function will suss out the right object
* for you.
*
* @param Asset The asset you want an object for.
* @return A pointer to the targeted object from the asset's package.
*/
static UField* GetTargetAssetObject(const FAssetData& Asset);
/**
* Returns the object path for the field from the specified asset's package
* that is being replaced (Asset.ObjectPath will not suffice, as that
* does not always reflect the object that is being replaced).
*
* @param Asset The asset you want an object-path for.
* @return An object-path for the target field-object within the asset's package.
*/
static FString GetTargetObjectPath(const FAssetData& Asset);
}
//------------------------------------------------------------------------------
static bool BlueprintNativeCodeGenManifestImpl::LoadManifest(const FString& FilePath, FBlueprintNativeCodeGenManifest* Manifest)
{
FString ManifestStr;
if (FFileHelper::LoadFileToString(ManifestStr, *FilePath))
{
TSharedRef< TJsonReader<> > JsonReader = TJsonReaderFactory<>::Create(ManifestStr);
TSharedPtr<FJsonObject> JsonObject;
if (FJsonSerializer::Deserialize(JsonReader, JsonObject))
{
return FJsonObjectConverter::JsonObjectToUStruct<FBlueprintNativeCodeGenManifest>(JsonObject.ToSharedRef(), Manifest,
/*CheckFlags =*/CPF_NoFlags, /*SkipFlags =*/CPF_NoFlags);
}
}
return false;
}
//------------------------------------------------------------------------------
static const FString& BlueprintNativeCodeGenManifestImpl::GetSourceSubDir(const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType)
{
return (SourceType == FBlueprintNativeCodeGenPaths::HFile) ? HeaderSubDir : CppSubDir;
}
//------------------------------------------------------------------------------
static const FString& BlueprintNativeCodeGenManifestImpl::GetSourceFileExt(const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType)
{
return (SourceType == FBlueprintNativeCodeGenPaths::HFile) ? HeaderFileExt : CppFileExt;
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GenerateSourceFileSavePath(const FBlueprintNativeCodeGenPaths& TargetPaths, const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions, const FBlueprintNativeCodeGenPaths::ESourceFileType SourceType)
{
return FPaths::Combine(*TargetPaths.RuntimeSourceDir(SourceType), *GetBaseFilename(Asset, NativizationOptions)) + GetSourceFileExt(SourceType);
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GenerateUnconvertedWrapperPath(const FBlueprintNativeCodeGenPaths& TargetPaths, const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions)
{
const FBlueprintNativeCodeGenPaths::ESourceFileType WrapperFileType = FBlueprintNativeCodeGenPaths::HFile;
return FPaths::Combine(*TargetPaths.RuntimeSourceDir(WrapperFileType), *GetBaseFilename(Asset, NativizationOptions)) + GetSourceFileExt(WrapperFileType);
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GetBaseFilename(const FAssetData& Asset, const FCompilerNativizationOptions& NativizationOptions)
{
IBlueprintCompilerCppBackendModule& CodeGenBackend = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
return CodeGenBackend.ConstructBaseFilename(Asset.GetAsset(), NativizationOptions);
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GetComparibleDirPath(const FString& DirectoryPath)
{
FString NormalizedPath = DirectoryPath;
const FString PathDelim = TEXT("/");
if (!NormalizedPath.EndsWith(PathDelim))
{
// to account for the case where the relative path would resolve to X:
// (when we want "X:/")... ConvertRelativePathToFull() leaves the
// trailing slash, and NormalizeDirectoryName() will remove it (if it is
// not a drive letter)
NormalizedPath += PathDelim;
}
if (FPaths::IsRelative(NormalizedPath))
{
NormalizedPath = FPaths::ConvertRelativePathToFull(NormalizedPath);
}
FPaths::NormalizeDirectoryName(NormalizedPath);
return NormalizedPath;
}
//------------------------------------------------------------------------------
static bool BlueprintNativeCodeGenManifestImpl::GatherModuleDependencies(const UObject* AssetObj, TArray<UPackage*>& DependenciesOut)
{
UPackage* AssetPackage = AssetObj->GetOutermost();
const FLinkerLoad* PkgLinker = FLinkerLoad::FindExistingLinkerForPackage(AssetPackage);
const bool bFoundLinker = (PkgLinker != nullptr);
if (ensureMsgf(bFoundLinker, TEXT("Failed to identify the asset package that '%s' belongs to."), *AssetObj->GetName()))
{
for (const FObjectImport& PkgImport : PkgLinker->ImportMap)
{
if (PkgImport.ClassName != NAME_Package)
{
continue;
}
UPackage* DependentPackage = FindObject<UPackage>(/*Outer =*/nullptr, *PkgImport.ObjectName.ToString(), /*ExactClass =*/true);
if (DependentPackage == nullptr)
{
continue;
}
// we want only native packages, ones that are not editor-only
if ((DependentPackage->GetPackageFlags() & (PKG_CompiledIn | PKG_EditorOnly | PKG_Developer)) == PKG_CompiledIn)
{
DependenciesOut.AddUnique(DependentPackage);// PkgImport.ObjectName.ToString());
}
}
}
return bFoundLinker;
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GetFieldName(const FAssetData& Asset)
{
UField* AssetField = GetTargetAssetObject(Asset);
return (AssetField != nullptr) ? AssetField->GetName() : TEXT("");
}
//------------------------------------------------------------------------------
static UField* BlueprintNativeCodeGenManifestImpl::GetTargetAssetObject(const FAssetData& Asset)
{
UObject* AssetObj = Asset.GetAsset();
UField* AssetField = nullptr;
if (UBlueprint* BlueprintAsset = Cast<UBlueprint>(AssetObj))
{
AssetField = BlueprintAsset->GeneratedClass;
if (!AssetField)
{
UE_LOG(LogNativeCodeGenManifest, Warning, TEXT("null BPGC in %s"), *BlueprintAsset->GetPathName());
}
}
else
{
// only other asset types that we should be converting are enums and
// structs (both UFields)
AssetField = CastChecked<UField>(AssetObj);
}
return AssetField;
}
//------------------------------------------------------------------------------
static FString BlueprintNativeCodeGenManifestImpl::GetTargetObjectPath(const FAssetData& Asset)
{
UField* AssetField = GetTargetAssetObject(Asset);
return (AssetField != nullptr) ? AssetField->GetPathName() : TEXT("");
}
/*******************************************************************************
* FConvertedAssetRecord
******************************************************************************/
//------------------------------------------------------------------------------
FConvertedAssetRecord::FConvertedAssetRecord(const FAssetData& AssetInfo, const FBlueprintNativeCodeGenPaths& TargetPaths, const FCompilerNativizationOptions& NativizationOptions)
: AssetType(AssetInfo.GetClass())
, TargetObjPath(BlueprintNativeCodeGenManifestImpl::GetTargetObjectPath(AssetInfo))
{
GeneratedCppPath = BlueprintNativeCodeGenManifestImpl::GenerateSourceFileSavePath(TargetPaths, AssetInfo, NativizationOptions, FBlueprintNativeCodeGenPaths::CppFile);
GeneratedHeaderPath = BlueprintNativeCodeGenManifestImpl::GenerateSourceFileSavePath(TargetPaths, AssetInfo, NativizationOptions, FBlueprintNativeCodeGenPaths::HFile);
}
/*******************************************************************************
* FUnconvertedDependencyRecord
******************************************************************************/
//------------------------------------------------------------------------------
FUnconvertedDependencyRecord::FUnconvertedDependencyRecord(const FString& InGeneratedWrapperPath)
: GeneratedWrapperPath(InGeneratedWrapperPath)
{
}
/*******************************************************************************
* FBlueprintNativeCodeGenPaths
******************************************************************************/
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenPaths FBlueprintNativeCodeGenPaths::GetDefaultCodeGenPaths(const FName PlatformName)
{
static const FString DefaultPluginName = TEXT("NativizedAssets");
FString DefaultPluginPath = FPaths::Combine(*FPaths::ProjectIntermediateDir(), TEXT("Plugins"), *DefaultPluginName);
if (!PlatformName.IsNone())
{
for (PlatformInfo::FPlatformEnumerator PlatformIt = PlatformInfo::EnumeratePlatformInfoArray(); PlatformIt; ++PlatformIt)
{
if (PlatformIt->TargetPlatformName == PlatformName)
{
static const FName UBTTargetId_Win32 = FName(TEXT("Win32"));
static const FName UBTTargetId_Win64 = FName(TEXT("Win64"));
static const FName UBTTargetId_Windows = FName(TEXT("Windows"));
const FName UBTTargetId = (PlatformIt->UBTTargetId == UBTTargetId_Win32 || PlatformIt->UBTTargetId == UBTTargetId_Win64) ? UBTTargetId_Windows : PlatformIt->UBTTargetId;
DefaultPluginPath = FPaths::Combine(*DefaultPluginPath, *Lex::ToString(UBTTargetId), *Lex::ToString(PlatformIt->PlatformType));
break;
}
}
}
return FBlueprintNativeCodeGenPaths(DefaultPluginName, DefaultPluginPath, PlatformName);
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::GetDefaultPluginPath(const FName PlatformName)
{
return GetDefaultCodeGenPaths(PlatformName).PluginFilePath();
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::GetDefaultManifestFilePath(const FName PlatformName, const int32 ChunkId)
{
return GetDefaultCodeGenPaths(PlatformName).ManifestFilename(ChunkId);
}
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenPaths::FBlueprintNativeCodeGenPaths(const FString& PluginNameIn, const FString& TargetDirIn, const FName PlatformNameIn)
: PluginsDir(TargetDirIn)
, PluginName(PluginNameIn)
, PlatformName(PlatformNameIn)
{
// PluginsDir is expected to be the generic 'Plugins' directory (we'll add our own subfolder matching the plugin name)
if (FPaths::GetBaseFilename(PluginsDir) == PluginNameIn)
{
PluginsDir = FPaths::GetPath(PluginsDir);
}
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::ManifestFilename(const int32 ChunkId) const
{
using namespace BlueprintNativeCodeGenManifestImpl;
FString Filename = FApp::GetProjectName() + (TEXT("_") + PlatformName.ToString());
if (ChunkId != RootManifestId)
{
Filename += FString::Printf(TEXT("-%02d"), ChunkId);
}
return Filename + ManifestFileExt;
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::ManifestFilePath(const int32 ChunkId) const
{
return FPaths::Combine(*RuntimeModuleDir(), *ManifestFilename(ChunkId));
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::PluginRootDir() const
{
return PluginsDir;
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::PluginFilePath() const
{
return FPaths::Combine(*PluginRootDir(), *PluginName) + BlueprintNativeCodeGenManifestImpl::PluginFileExt;
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::PluginSourceDir() const
{
return FPaths::Combine(*PluginRootDir(), *BlueprintNativeCodeGenManifestImpl::SourceSubDir);
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimeModuleDir() const
{
return FPaths::Combine(*PluginSourceDir(), *RuntimeModuleName());
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimeModuleName() const
{
FString ModuleName = PluginName;
// if (!PlatformName.IsNone())
// {
// ModuleName += TEXT("_") + PlatformName.ToString();
// }
return ModuleName;
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimeBuildFile() const
{
return FPaths::Combine(*RuntimeModuleDir(), *RuntimeModuleName()) + BlueprintNativeCodeGenManifestImpl::ModuleBuildFileExt;
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimeSourceDir(ESourceFileType SourceType) const
{
return FPaths::Combine(*RuntimeModuleDir(), *BlueprintNativeCodeGenManifestImpl::GetSourceSubDir(SourceType));
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimeModuleFile(ESourceFileType SourceType) const
{
// use the "cpp" (private) directory for the header too (which acts as a PCH)
return FPaths::Combine(*RuntimeSourceDir(ESourceFileType::CppFile), *RuntimeModuleName()) + BlueprintNativeCodeGenManifestImpl::GetSourceFileExt(SourceType);
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenPaths::RuntimePCHFilename() const
{
return FPaths::GetCleanFilename(RuntimeModuleFile(HFile));
}
/*******************************************************************************
* FBlueprintNativeCodeGenManifest
******************************************************************************/
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenManifest::FBlueprintNativeCodeGenManifest(int32 ManifestId)
: ManifestChunkId(ManifestId)
{
InitDestPaths(FBlueprintNativeCodeGenPaths::GetDefaultPluginPath(NAME_None));
}
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenManifest::FBlueprintNativeCodeGenManifest(const FCompilerNativizationOptions& InCompilerNativizationOptions, int32 ManifestId)
: ManifestChunkId(ManifestId)
, NativizationOptions(InCompilerNativizationOptions)
{
InitDestPaths(FBlueprintNativeCodeGenPaths::GetDefaultPluginPath(InCompilerNativizationOptions.PlatformName));
}
FBlueprintNativeCodeGenManifest::FBlueprintNativeCodeGenManifest(const FString& PluginPath, const FCompilerNativizationOptions& InCompilerNativizationOptions, int32 ManifestId)
: ManifestChunkId(ManifestId)
, NativizationOptions(InCompilerNativizationOptions)
{
InitDestPaths(PluginPath);
}
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenManifest::FBlueprintNativeCodeGenManifest(const FString& ManifestFilePathIn)
{
ensureAlwaysMsgf( BlueprintNativeCodeGenManifestImpl::LoadManifest(ManifestFilePathIn, this), TEXT("Missing Manifest for Blueprint code generation: %s"), *ManifestFilePathIn);
}
//------------------------------------------------------------------------------
FBlueprintNativeCodeGenPaths FBlueprintNativeCodeGenManifest::GetTargetPaths() const
{
return FBlueprintNativeCodeGenPaths(PluginName, GetTargetDir(), NativizationOptions.PlatformName);
}
//------------------------------------------------------------------------------
FConvertedAssetRecord& FBlueprintNativeCodeGenManifest::CreateConversionRecord(const FAssetId Key, const FAssetData& AssetInfo)
{
// It is an error to consider a record converted and unconverted. This is probably not negotiable. In order to leave the door
// open for parallelism we need to be able to trivially and consistently determine whether an asset will be converted without
// discovering things as we go.
check(UnconvertedDependencies.Find(Key) == nullptr);
// Similarly we should not convert things over and over and over:
if (FConvertedAssetRecord* Existing = ConvertedAssets.Find(Key))
{
return *Existing;
}
const FBlueprintNativeCodeGenPaths TargetPaths = GetTargetPaths();
UClass* AssetType = AssetInfo.GetClass();
// load the asset (if it isn't already)
const UObject* AssetObj = AssetInfo.GetAsset();
FConvertedAssetRecord* ConversionRecord = &ConvertedAssets.Add(Key, FConvertedAssetRecord(AssetInfo, TargetPaths, NativizationOptions));
return *ConversionRecord;
}
//------------------------------------------------------------------------------
FUnconvertedDependencyRecord& FBlueprintNativeCodeGenManifest::CreateUnconvertedDependencyRecord(const FAssetId UnconvertedAssetKey, const FAssetData& AssetInfo)
{
// It is an error to create a record multiple times because it is not obvious what the client wants to happen.
check(ConvertedAssets.Find(UnconvertedAssetKey) == nullptr);
if (FUnconvertedDependencyRecord* Existing = UnconvertedDependencies.Find(UnconvertedAssetKey))
{
return *Existing;
}
const FBlueprintNativeCodeGenPaths TargetPaths = GetTargetPaths();
FUnconvertedDependencyRecord* RecordPtr = &UnconvertedDependencies.Add(UnconvertedAssetKey, FUnconvertedDependencyRecord(BlueprintNativeCodeGenManifestImpl::GenerateUnconvertedWrapperPath(TargetPaths, AssetInfo, NativizationOptions)));
return *RecordPtr;
}
//------------------------------------------------------------------------------
void FBlueprintNativeCodeGenManifest::GatherModuleDependencies(UPackage* Package)
{
BlueprintNativeCodeGenManifestImpl::GatherModuleDependencies(Package, ModuleDependencies);
}
//------------------------------------------------------------------------------
void FBlueprintNativeCodeGenManifest::AddSingleModuleDependency(UPackage* Package)
{
ModuleDependencies.AddUnique(Package);
}
//------------------------------------------------------------------------------
bool FBlueprintNativeCodeGenManifest::Save() const
{
const FString FullFilename = GetTargetPaths().ManifestFilePath(ManifestChunkId);
TSharedRef<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
if (FJsonObjectConverter::UStructToJsonObject(FBlueprintNativeCodeGenManifest::StaticStruct(), this, JsonObject,
/*CheckFlags =*/BlueprintNativeCodeGenManifestImpl::CPF_NoFlags, /*SkipFlags =*/BlueprintNativeCodeGenManifestImpl::CPF_NoFlags))
{
FString FileContents;
TSharedRef< TJsonWriter<> > JsonWriter = TJsonWriterFactory<>::Create(&FileContents);
if (FJsonSerializer::Serialize(JsonObject, JsonWriter))
{
JsonWriter->Close();
return FFileHelper::SaveStringToFile(FileContents, *FullFilename);
}
}
return false;
}
void FBlueprintNativeCodeGenManifest::Merge(const FBlueprintNativeCodeGenManifest& OtherManifest)
{
for (auto& Entry : OtherManifest.ModuleDependencies)
{
ModuleDependencies.AddUnique(Entry);
}
for (auto& Entry : OtherManifest.ConvertedAssets)
{
ConvertedAssets.Add(Entry.Key, Entry.Value);
}
for (auto& Entry : OtherManifest.UnconvertedDependencies)
{
UnconvertedDependencies.Add(Entry.Key, Entry.Value);
}
}
//------------------------------------------------------------------------------
void FBlueprintNativeCodeGenManifest::InitDestPaths(const FString& PluginPath)
{
using namespace BlueprintNativeCodeGenManifestImpl;
if (ensure(!PluginPath.IsEmpty()))
{
PluginName = FPaths::GetBaseFilename(PluginPath);
if (ensure(PluginPath.EndsWith(PluginFileExt)))
{
OutputDir = FPaths::GetPath(PluginPath);
}
else
{
OutputDir = PluginPath;
}
if (FPaths::IsRelative(OutputDir))
{
FPaths::MakePathRelativeTo(OutputDir, *FPaths::ProjectDir());
}
}
else
{
FBlueprintNativeCodeGenPaths DefaultPaths = FBlueprintNativeCodeGenPaths::GetDefaultCodeGenPaths(NAME_None);
PluginName = DefaultPaths.GetPluginName();
OutputDir = DefaultPaths.PluginRootDir();
}
// there's some sanitation that FBlueprintNativeCodeGenPaths does that we
// can avoid in the future, if we pass this through it once
OutputDir = GetTargetPaths().PluginRootDir();
}
//------------------------------------------------------------------------------
FString FBlueprintNativeCodeGenManifest::GetTargetDir() const
{
FString TargetPath = OutputDir;
if (FPaths::IsRelative(TargetPath))
{
TargetPath = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir(), TargetPath);
TargetPath = FPaths::ConvertRelativePathToFull(TargetPath);
}
return TargetPath;
}
//------------------------------------------------------------------------------
void FBlueprintNativeCodeGenManifest::Clear()
{
ConvertedAssets.Empty();
}
| 41.76565 | 272 | 0.664796 | windystrife |
d0cbb04c1d00f83a39b1d1ab3677595c2e9d10ec | 1,521 | cpp | C++ | Model-View/DataRole/main.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | Model-View/DataRole/main.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | Model-View/DataRole/main.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | #include <QApplication>
#include <QDebug>
#include <QStandardItemModel>
#include <QTreeView>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QStandardItemModel model;
QStandardItem *parentItem = model.invisibleRootItem();
QStandardItem *item0 = new QStandardItem;
item0->setText("A");
QPixmap pixmap0(50, 50);
pixmap0.fill("red");
item0->setIcon(QIcon(pixmap0));
item0->setToolTip("indexA");
parentItem->appendRow(item0);
parentItem = item0;
QStandardItem *item1 = new QStandardItem;
item1->setText("B");
QPixmap pixmap1(50, 50);
pixmap1.fill("blue");
item1->setIcon(QIcon(pixmap1));
item1->setToolTip("indexB");
parentItem->appendRow(item1);
QStandardItem *item2 = new QStandardItem;
QPixmap pixmap2(50, 50);
pixmap2.fill("green");
item2->setData("C", Qt::EditRole);
item2->setData("indexC", Qt::ToolTipRole);
item2->setData(QIcon(pixmap2), Qt::DisplayRole);
parentItem->appendRow(item2);
QTreeView treeView;
treeView.setModel(&model);
treeView.show();
QModelIndex indexA = model.index(0, 0, QModelIndex());
qDebug() << "indexA row count: " << model.rowCount(indexA);
QModelIndex indexB = model.index(0, 0, indexA);
qDebug() << "indexB row count: " << model.rowCount(indexB);
qDebug() << "indexB text:" << model.data(indexB, Qt::EditRole).toString();
qDebug() << "indexB toolTip: " << model.data(indexB, Qt::ToolTipRole).toString();
return app.exec();
}
| 29.823529 | 85 | 0.65812 | BigWhiteCat |
d0cf57e8f7a16229a3cd5592a4f6af0830658218 | 12,406 | hpp | C++ | include/scrollgrid/scrollgrid2.hpp | castacks/scrollgrid | 710324173907a182eb688effcf1c9ec998ade1e0 | [
"BSD-3-Clause"
] | 9 | 2017-07-20T23:04:49.000Z | 2021-11-12T08:03:10.000Z | include/scrollgrid/scrollgrid2.hpp | castacks/scrollgrid | 710324173907a182eb688effcf1c9ec998ade1e0 | [
"BSD-3-Clause"
] | null | null | null | include/scrollgrid/scrollgrid2.hpp | castacks/scrollgrid | 710324173907a182eb688effcf1c9ec998ade1e0 | [
"BSD-3-Clause"
] | 3 | 2018-04-06T16:41:58.000Z | 2022-03-12T01:39:22.000Z | /**
* Copyright (c) 2015 Carnegie Mellon University, Daniel Maturana <dimatura@cmu.edu>
*
* For License information please see the LICENSE file in the root directory.
*
*/
#ifndef SCROLLGRID2_HPP_YPBBYE5Q
#define SCROLLGRID2_HPP_YPBBYE5Q
#include <math.h>
#include <stdint.h>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <ros/ros.h>
#include <ros/console.h>
#include <pcl_util/point_types.hpp>
#include <geom_cast/geom_cast.hpp>
#include "scrollgrid/mod_wrap.hpp"
#include "scrollgrid/grid_types.hpp"
#include "scrollgrid/box.hpp"
namespace ca
{
template<class Scalar>
class ScrollGrid2 {
public:
typedef Eigen::Matrix<Scalar, 2, 1> Vec2;
typedef boost::shared_ptr<ScrollGrid2> Ptr;
typedef boost::shared_ptr<const ScrollGrid2> ConstPtr;
public:
ScrollGrid2() :
box_(),
origin_(0, 0),
min_world_corner_ij_(0, 0),
dimension_(0, 0),
num_cells_(0),
strides_(0, 0),
scroll_offset_(0, 0),
last_ij_(0, 0),
wrap_ij_min_(0, 0),
wrap_ij_max_(0, 0),
resolution_(0)
{ }
ScrollGrid2(const Vec2& center,
const Vec2Ix& dimension,
Scalar resolution,
bool x_fastest=false) :
box_(center-(dimension.cast<Scalar>()*resolution)/2,
center+(dimension.cast<Scalar>()*resolution)/2),
origin_(center-box_.radius()),
dimension_(dimension),
num_cells_(dimension.prod()),
strides_(dimension[1], 1),
scroll_offset_(0, 0, 0),
last_ij_(scroll_offset_ + dimension_),
resolution_(resolution)
{
Vec2 m;
m[0] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;
m[1] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;
min_world_corner_ij_ = this->world_to_grid(m);
if (x_fastest) {
strides_ = Vec2Ix(1, dimension[0]);
}
this->update_wrap_ij();
}
virtual ~ScrollGrid2() { }
ScrollGrid2(const ScrollGrid2& other) :
box_(other.box_),
origin_(other.origin_),
min_world_corner_ij_(other.min_world_corner_ij_),
dimension_(other.dimension_),
num_cells_(other.num_cells_),
strides_(other.strides_),
scroll_offset_(other.scroll_offset_),
last_ij_(other.last_ij_),
wrap_ij_min_(other.wrap_ij_min_),
wrap_ij_max_(other.wrap_ij_max_),
resolution_(other.resolution_)
{
}
ScrollGrid2& operator=(const ScrollGrid2& other) {
if (*this==other) { return *this; }
box_ = other.box_;
origin_ = other.origin_;
min_world_corner_ij_ = other.min_world_corner_ij_;
dimension_ = other.dimension_;
num_cells_ = other.num_cells_;
strides_ = other.strides_;
scroll_offset_ = other.scroll_offset_;
last_ij_ = other.last_ij_;
wrap_ij_min_ = other.wrap_ij_min_;
wrap_ij_max_ = other.wrap_ij_max_;
resolution_ = other.resolution_;
return *this;
}
public:
void reset(const Vec2& center,
const Vec2Ix& dimension,
Scalar resolution,
bool x_fastest=false) {
box_.set_center(center);
box_.set_radius((dimension.cast<Scalar>()*resolution)/2);
origin_ = center - box_.radius();
dimension_ = dimension;
num_cells_ = dimension.prod();
if (x_fastest) {
strides_ = Vec2Ix(1, dimension[0]);
} else {
strides_ = Vec2Ix(dimension[1], 1);
}
scroll_offset_.setZero();
last_ij_ = scroll_offset_ + dimension_;
this->update_wrap_ij();
resolution_ = resolution;
Vec2 m;
m[0] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;
m[1] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;
min_world_corner_ij_ = this->world_to_grid(m);
}
/**
* Is inside 3D box containing grid?
* @param pt point in same frame as center (probably world_view)
*/
bool is_inside_box(const Vec2& pt) const {
return box_.contains(pt);
}
template<class PointT>
bool is_inside_box(const PointT& pt) const {
return box_.contains(ca::point_cast<Vec2>(pt));
}
/**
* is i, j, k inside the grid limits?
*/
bool is_inside_grid(const Vec2Ix& grid_ix) const {
return ((grid_ix.array() >= scroll_offset_.array()).all() &&
(grid_ix.array() < (scroll_offset_+dimension_).array()).all());
}
bool is_inside_grid(grid_ix_t i, grid_ix_t j) const {
return this->is_inside_grid(Vec2Ix(i, j));
}
/**
* scroll grid.
* updates bounding box and offset_cells.
* @param offset_cells. how much to scroll. offset_cells is a signed integral.
*
*/
void scroll(const Vec2Ix& offset_cells) {
Vec2Ix new_offset = scroll_offset_ + offset_cells;
box_.translate((offset_cells.cast<Scalar>()*resolution_));
scroll_offset_ = new_offset;
last_ij_ = scroll_offset_ + dimension_;
this->update_wrap_ij();
}
/**
* get boxes to clear if scrolling by offset_cells.
* call this *before* scroll().
* @param clear_i_min min corner of obsolete region in grid
* @param clear_i_max max corner of obsolete region in grid
* same for j and k
* Note that boxes may overlap.
*/
void get_clear_boxes(const Vec2Ix& offset_cells,
Vec2Ix& clear_i_min, Vec2Ix& clear_i_max,
Vec2Ix& clear_j_min, Vec2Ix& clear_j_max) {
Vec2Ix new_offset = scroll_offset_ + offset_cells;
clear_i_min.setZero();
clear_j_min.setZero();
clear_i_max.setZero();
clear_j_max.setZero();
// X axis
if (offset_cells[0] > 0) {
clear_i_min = scroll_offset_;
clear_i_max = Vec2Ix(new_offset[0],
scroll_offset_[1]+dimension_[1]);
} else if (offset_cells[0] < 0) {
clear_i_min = Vec2Ix(scroll_offset_[0]+dimension_[0]+offset_cells[0],
scroll_offset_[1]);
clear_i_max = scroll_offset_ + dimension_;
}
// Y axis
if (offset_cells[1] > 0) {
clear_j_min = scroll_offset_;
clear_j_max = Vec2Ix(scroll_offset_[0]+dimension_[0],
new_offset[1]);
} else if (offset_cells[1] < 0) {
clear_j_min = Vec2Ix(scroll_offset_[0],
scroll_offset_[1]+dimension_[1]+offset_cells[1]);
clear_j_max = scroll_offset_ + dimension_;
}
}
/**
* Given position in world coordinates, return grid coordinates.
* (grid coordinates are not wrapped to be inside grid!)
* Note: does not check if point is inside grid.
*/
Vec2Ix world_to_grid(const Vec2& xy) const {
Vec2 tmp = ((xy - origin_).array() - 0.5*resolution_)/resolution_;
//ROS_INFO_STREAM("tmp = " << tmp);
//return tmp.cast<grid_ix_t>();
return Vec2Ix(round(tmp.x()), round(tmp.y()));
}
Vec2Ix world_to_grid(Scalar x, Scalar y) const {
return this->world_to_grid(Vec2(x, y));
}
Vec2 grid_to_world(const Vec2Ix& grid_ix) const {
Vec2 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);
return w;
}
Vec2 grid_to_world(grid_ix_t i, grid_ix_t j) const {
return this->grid_to_world(Vec2Ix(i, j));
}
/**
* Translate grid indices to an address in linear memory.
* Does not check if grid_ix is inside current grid box.
* Assumes C-order, x the slowest and z the fastest.
*/
mem_ix_t grid_to_mem(const Vec2Ix& grid_ix) const {
Vec2Ix grid_ix2(ca::mod_wrap(grid_ix[0], dimension_[0]),
ca::mod_wrap(grid_ix[1], dimension_[1]));
return strides_.dot(grid_ix2);
}
/**
* This is faster than grid_to_mem, as it avoids modulo.
* But it only works if the grid_ix are inside the bounding box.
* Hopefully branch prediction kicks in
*/
mem_ix_t grid_to_mem2(const Vec2Ix& grid_ix) const {
Vec2Ix grid_ix2(grid_ix);
if (grid_ix2[0] >= wrap_ij_max_[0]) { grid_ix2[0] -= wrap_ij_max_[0]; } else { grid_ix2[0] -= wrap_ij_min_[0]; }
if (grid_ix2[1] >= wrap_ij_max_[1]) { grid_ix2[1] -= wrap_ij_max_[1]; } else { grid_ix2[1] -= wrap_ij_min_[1]; }
mem_ix_t mem_ix2 = strides_.dot(grid_ix2);
return mem_ix2;
}
mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j) const {
return this->grid_to_mem(Vec2Ix(i, j));
}
mem_ix_t grid_to_mem2(grid_ix_t i, grid_ix_t j) const {
return grid_to_mem2(Vec2Ix(i, j));
}
uint64_t grid_to_hash(const Vec2Ix& grid_ix) const {
// grid2 should be all positive
Vec2Ix grid2(grid_ix - min_world_corner_ij_);
uint64_t hi = static_cast<uint64_t>(grid2[0]);
uint64_t hj = static_cast<uint64_t>(grid2[1]);
uint64_t h = (hi << 48) | (hj << 32);
return h;
}
Vec2Ix hash_to_grid(uint64_t hix) const {
uint64_t hi = (hix & 0xffff000000000000) >> 48;
uint64_t hj = (hix & 0x0000ffff00000000) >> 32;
Vec2Ix grid_ix(hi, hj);
grid_ix += min_world_corner_ij_;
return grid_ix;
}
/**
* Note that no bound check is performed!
*/
mem_ix_t world_to_mem(const Vec2& xy) const {
Vec2 tmp(((xy - origin_).array() - 0.5*resolution_)/resolution_);
Vec2Ix gix(round(tmp.x()), round(tmp.y()), round(tmp.z()));
ca::inplace_mod_wrap(gix[0], dimension_[0]);
ca::inplace_mod_wrap(gix[1], dimension_[1]);
return strides_.dot(gix);
}
mem_ix_t world_to_mem2(const Vec2& xy) const {
Vec2Ix gix(this->world_to_grid(xy));
return this->world_to_mem2(gix);
}
Vec2Ix mem_to_grid(grid_ix_t mem_ix) const {
// TODO does this work for x-fastest strides?
grid_ix_t i = mem_ix/strides_[0];
mem_ix -= i*strides_[0];
grid_ix_t j = mem_ix/strides_[1];
mem_ix -= j*strides_[1];
// undo wrapping
grid_ix_t ax = floor(static_cast<Scalar>(scroll_offset_[0])/dimension_[0])*dimension_[0];
grid_ix_t ay = floor(static_cast<Scalar>(scroll_offset_[1])/dimension_[1])*dimension_[1];
Vec2Ix fixed_ij;
fixed_ij[0] = i + ax + (i<(scroll_offset_[0]-ax))*dimension_[0];
fixed_ij[1] = j + ay + (j<(scroll_offset_[1]-ay))*dimension_[1];
return fixed_ij;
}
public:
grid_ix_t dim_i() const { return dimension_[0]; }
grid_ix_t dim_j() const { return dimension_[1]; }
grid_ix_t first_i() const { return scroll_offset_[0]; }
grid_ix_t first_j() const { return scroll_offset_[1]; }
grid_ix_t last_i() const { return last_ij_[0]; }
grid_ix_t last_j() const { return last_ij_[1]; }
const Vec2Ix& dimension() const { return dimension_; }
const Vec2& radius() const { return box_.radius(); }
const Vec2& origin() const { return origin_; }
Vec2 min_pt() const { return box_.min_pt(); }
Vec2 max_pt() const { return box_.max_pt(); }
const Vec2& center() const { return box_.center(); }
Scalar resolution() const { return resolution_; }
const ca::scrollgrid::Box<Scalar, 2>& box() const { return box_; }
grid_ix_t num_cells() const { return num_cells_; }
Vec2Ix scroll_offset() const { return scroll_offset_; }
private:
void update_wrap_ij() {
wrap_ij_min_[0] = floor(static_cast<float>(scroll_offset_[0])/dimension_[0])*dimension_[0];
wrap_ij_min_[1] = floor(static_cast<float>(scroll_offset_[1])/dimension_[1])*dimension_[1];
wrap_ij_max_[0] = floor(static_cast<float>(scroll_offset_[0]+dimension_[0])/dimension_[0])*dimension_[0];
wrap_ij_max_[1] = floor(static_cast<float>(scroll_offset_[1]+dimension_[1])/dimension_[1])*dimension_[1];
}
private:
// 2d box enclosing grid. In whatever coordinates were given (probably
// world_view)
ca::scrollgrid::Box<Scalar, 2> box_;
// static origin of the grid coordinate system. does not move when scrolling
// it's center - box.radius
Vec2 origin_;
// minimum world corner in ij. used for hash
Vec2Ix min_world_corner_ij_;
// number of grid cells along each axis
Vec2Ix dimension_;
// number of cells
grid_ix_t num_cells_;
// grid strides to translate from linear to 3D layout.
// C-ordering, ie x slowest, z fastest.
Vec2Ix strides_;
// to keep track of scrolling along z.
Vec2Ix scroll_offset_;
// redundant but actually seems to have a performance benefit
// should always be dimension + offset
Vec2Ix last_ij_;
// for grid_to_mem2. the points where the grid crosses modulo boundaries.
Vec2Ix wrap_ij_min_;
Vec2Ix wrap_ij_max_;
// size of grid cells
Scalar resolution_;
};
typedef ScrollGrid2<float> ScrollGrid2f;
typedef ScrollGrid2<double> ScrollGrid2d;
} /* ca */
#endif /* end of include guard: SCROLLGRID2_HPP_YPBBYE5Q */
| 30.258537 | 116 | 0.664759 | castacks |
d0d3fb20075e27b3eff9598a173568f29a0d07f8 | 4,613 | cc | C++ | asylo/test/loader/loader_test.cc | qinkunbao/asylo | 6c6c4a185a1ee927996b43a060d924a49548d999 | [
"Apache-2.0"
] | null | null | null | asylo/test/loader/loader_test.cc | qinkunbao/asylo | 6c6c4a185a1ee927996b43a060d924a49548d999 | [
"Apache-2.0"
] | null | null | null | asylo/test/loader/loader_test.cc | qinkunbao/asylo | 6c6c4a185a1ee927996b43a060d924a49548d999 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2017 Asylo 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 <iostream>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "asylo/client.h"
#include "asylo/test/util/status_matchers.h"
#include "asylo/util/status.h"
#include "asylo/util/statusor.h"
namespace asylo {
namespace {
using ::testing::Not;
// Placeholder client implementation for a debug enclave.
class TestClient : public EnclaveClient {
public:
TestClient() : EnclaveClient("test") {}
Status EnterAndRun(const EnclaveInput &input,
EnclaveOutput *output) override {
return Status::OkStatus();
}
private:
Status EnterAndInitialize(const EnclaveConfig &config) override {
return Status::OkStatus();
}
Status EnterAndFinalize(const EnclaveFinal &final_input) override {
return Status::OkStatus();
}
Status DestroyEnclave() override { return Status::OkStatus(); }
};
// Loader which always fails for testing.
class FailingLoader : public EnclaveLoader {
protected:
StatusOr<std::unique_ptr<EnclaveClient>> LoadEnclave(
absl::string_view name, void *base_address, const size_t enclave_size,
const EnclaveConfig &config) const override {
return Status(absl::StatusCode::kInvalidArgument,
"Could not load enclave.");
}
EnclaveLoadConfig GetEnclaveLoadConfig() const override {
EnclaveLoadConfig loader_config;
return loader_config;
}
};
// Loads clients by default constructing T.
template <typename T>
class FakeLoader : public EnclaveLoader {
public:
~FakeLoader() override = default;
FakeLoader() = default;
protected:
StatusOr<std::unique_ptr<EnclaveClient>> LoadEnclave(
absl::string_view name, void *base_address, const size_t enclave_size,
const EnclaveConfig &config) const override {
return std::unique_ptr<EnclaveClient>(new T());
}
EnclaveLoadConfig GetEnclaveLoadConfig() const override {
EnclaveLoadConfig loader_config;
return loader_config;
}
};
class LoaderTest : public ::testing::Test {
protected:
void SetUp() override {
EnclaveManager::Configure(EnclaveManagerOptions());
StatusOr<EnclaveManager *> manager_result = EnclaveManager::Instance();
if (!manager_result.ok()) {
LOG(FATAL) << manager_result.status();
}
manager_ = manager_result.ValueOrDie();
}
EnclaveManager *manager_;
FakeLoader<TestClient> loader_;
};
// Basic overall test and demonstration of enclave lifecyle.
TEST_F(LoaderTest, Overall) {
Status status = manager_->LoadEnclave("/fake", loader_);
ASSERT_THAT(status, IsOk());
EnclaveClient *client = manager_->GetClient("/fake");
ASSERT_NE(client, nullptr);
EnclaveInput einput;
status = client->EnterAndRun(einput, nullptr);
ASSERT_THAT(status, IsOk());
EnclaveFinal efinal_input;
status = manager_->DestroyEnclave(client, efinal_input);
ASSERT_THAT(status, IsOk());
}
// Ensure an enclave name cannot be reused.
TEST_F(LoaderTest, DuplicateNamesFail) {
Status status = manager_->LoadEnclave("/duplicate_names", loader_);
ASSERT_THAT(status, IsOk());
// Check we can't load another enclave with the same path.
status = manager_->LoadEnclave("/duplicate_names", loader_);
ASSERT_THAT(status, Not(IsOk()));
}
// Ensure we can not fetch a client for a destroyed enclave.
TEST_F(LoaderTest, FetchAfterDestroy) {
Status status = manager_->LoadEnclave("/fetch_after_destroy", loader_);
ASSERT_THAT(status, IsOk());
auto client = manager_->GetClient("/fetch_after_destroy");
ASSERT_NE(client, nullptr);
EnclaveFinal final_input;
status = manager_->DestroyEnclave(client, final_input);
ASSERT_THAT(status, IsOk());
// Check we can't fetch a client to a destroyed enclave.
client = manager_->GetClient("/fetch_after_destroy");
ASSERT_EQ(client, nullptr);
}
// Ensure that an error is reported on loading.
TEST_F(LoaderTest, PropagateLoaderFailure) {
FailingLoader loader;
auto status = manager_->LoadEnclave("/fake", loader);
ASSERT_THAT(status, Not(IsOk()));
}
}; // namespace
}; // namespace asylo
| 28.83125 | 76 | 0.725775 | qinkunbao |
d0d687d7117b4d3bca1064af8409fc259ebbbb2f | 2,149 | cpp | C++ | totp/TOTP.cpp | galilov/youtube-microcontrollers | 0c02e335eb01b5675e9aaadf664e4b7c0517a4fa | [
"Unlicense"
] | null | null | null | totp/TOTP.cpp | galilov/youtube-microcontrollers | 0c02e335eb01b5675e9aaadf664e4b7c0517a4fa | [
"Unlicense"
] | null | null | null | totp/TOTP.cpp | galilov/youtube-microcontrollers | 0c02e335eb01b5675e9aaadf664e4b7c0517a4fa | [
"Unlicense"
] | null | null | null | // OpenAuthentication Time-based One-time Password Algorithm (RFC 6238)
// For the complete description of the algorithm see
// http://tools.ietf.org/html/rfc4226#section-5.3
//
// Luca Dentella (http://www.lucadentella.it)
#include "TOTP.h"
#include "Sha1.h"
// Init the library with the private key, its length and the timeStep duration
void TOTPClass::setup(uint8_t *hmacKey, int keyLength, int timeStep) {
_prevSteps = -1;
_hmacKey = hmacKey;
_keyLength = keyLength;
_timeStep = timeStep;
};
// Generate a code, using the timestamp provided
char *TOTPClass::getCode(long timeStamp, uint8_t length) {
long steps = timeStamp / _timeStep;
if (steps == _prevSteps) return _code;
_prevSteps = steps;
return getCodeFromSteps(steps, length);
}
// Generate a code, using the number of steps provided
char *TOTPClass::getCodeFromSteps(long steps, uint8_t length) {
const static long dividers[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
// STEP 0, map the number of steps in a 8-bytes array (counter value)
static uint8_t byteArray[8];
byteArray[0] = 0x00;
byteArray[1] = 0x00;
byteArray[2] = 0x00;
byteArray[3] = 0x00;
byteArray[4] = (int) ((steps >> 24) & 0xFF);
byteArray[5] = (int) ((steps >> 16) & 0xFF);
byteArray[6] = (int) ((steps >> 8) & 0XFF);
byteArray[7] = (int) ((steps & 0XFF));
// STEP 1, get the HMAC-SHA1 hash from counter and key
Sha1.initHmac(_hmacKey, _keyLength);
Sha1.write(byteArray, 8);
uint8_t *hash = Sha1.resultHmac();
// STEP 2, apply dynamic truncation to obtain a 4-bytes string
_offset = hash[20 - 1] & 0xF;
_truncatedHash = 0;
for (int j = 0; j < 4; ++j) {
_truncatedHash <<= 8;
_truncatedHash |= hash[_offset + j];
}
// STEP 3, compute the OTP value
_truncatedHash &= 0x7FFFFFFF;
_truncatedHash %= dividers[length % (sizeof(dividers) / sizeof(dividers[0]))];
// convert the value in string, with heading zeroes
char fmt[8];
sprintf(fmt, "%%0%dld", length);
sprintf(_code, fmt, _truncatedHash);
return _code;
}
TOTPClass TOTP;
| 32.074627 | 99 | 0.657515 | galilov |
d0d7621e0178cdd4706c0cc2f5144a7b83515a48 | 5,487 | cpp | C++ | src/database/models.cpp | ogoes/hash | a2cf27e1fe0ba6bb78b1008fd32a4b06e60cd7c6 | [
"MIT"
] | null | null | null | src/database/models.cpp | ogoes/hash | a2cf27e1fe0ba6bb78b1008fd32a4b06e60cd7c6 | [
"MIT"
] | null | null | null | src/database/models.cpp | ogoes/hash | a2cf27e1fe0ba6bb78b1008fd32a4b06e60cd7c6 | [
"MIT"
] | null | null | null | #include "database/models.h"
using namespace models;
Player::Player () {}
Player::~Player () {}
Player* Player::set_id ( uint id ) {
this->id = id;
this->has_id = true;
return this;
}
Player* Player::set_username ( std::string username ) {
this->username = username;
this->has_username = true;
return this;
}
Player* Player::set_password ( std::string password ) {
this->password = password;
this->has_password = true;
return this;
}
Player* Player::set_wins ( uint wins ) {
this->wins = wins;
this->has_wins = true;
return this;
}
Player* Player::set_tieds ( uint tieds ) {
this->tieds = tieds;
this->has_tieds = true;
return this;
}
Player* Player::set_lost ( uint lost ) {
this->lost = lost;
this->has_lost = true;
return this;
}
uint Player::get_id () { return this->has_id ? this->id : 0; }
std::string Player::get_username () {
return this->has_username ? this->username : std::string ( "" );
}
uint Player::get_wins () { return this->has_wins ? this->wins : 0; }
uint Player::get_tieds () { return this->has_tieds ? this->tieds : 0; }
uint Player::get_lost () { return this->has_lost ? this->lost : 0; }
std::string Player::insert_into () {
std::string query (
"INSERT INTO Player (id, username, password, wins, tieds, lost) VALUES "
"(NULL" );
std::string attr;
query += std::string ( "," );
attr = this->has_username ? this->username : std::string ( "NULL" );
query += attr;
query += std::string ( "," );
attr = this->has_password ? this->password : std::string ( "NULL" );
query += attr;
query += std::string ( "," );
attr = this->has_wins ? std::to_string ( this->wins ) : std::string ( "0" );
query += attr;
query += std::string ( "," );
attr = this->has_tieds ? std::to_string ( this->tieds ) : std::string ( "0" );
query += attr;
query += std::string ( "," );
attr = this->has_lost ? std::to_string ( this->lost ) : std::string ( "0" );
query += attr;
query += std::string ( ");" );
return query;
}
std::string Player::query_builder ( const char* columns = "*" ) {
std::string query ( "SELECT " );
query += std::string ( columns );
query += std::string ( " FROM Player" );
if ( this->has_id || this->has_username ) {
query += " WHERE ";
std::string where;
where = this->has_id ? std::string ( "id = " ) + std::to_string ( this->id )
: std::string ( "" );
query += where;
where = this->has_id && this->has_username ? std::string ( " AND " )
: std::string ( "" );
query += where;
where = this->has_username ? std::string ( "username = " ) + this->username
: std::string ( "" );
query += where;
}
query += std::string ( ";" );
return query;
}
std::string Player::update () {
std::string query ( "UPDATE Player SET " );
bool has_prev_attr = false;
std::string set;
std::string where;
if ( this->has_username ) {
set = std::string ( "username = " ) + this->username;
where = this->has_id
? std::string ( " WHERE id = " ) + std::to_string ( this->id ) +
std::string ( " AND " )
: std::string ( " WHERE " );
where += set;
has_prev_attr = true;
}
if ( where.size () == 0 ) {
std::cerr << "Operação necessita de uma parâmetro WHERE" << std::endl;
return NULL;
}
query += set;
if ( this->has_password ) {
set = has_prev_attr ? std::string ( ", " ) : std::string ( "" );
set += std::string ( "password = " ) + this->password;
has_prev_attr = true;
}
query += set;
if ( this->has_wins ) {
set = has_prev_attr ? std::string ( ", " ) : std::string ( "" );
set += std::string ( "wins = " ) + std::to_string ( this->wins );
has_prev_attr = true;
}
query += set;
if ( this->has_tieds ) {
set = has_prev_attr ? std::string ( ", " ) : std::string ( "" );
set += std::string ( "tieds = " ) + std::to_string ( this->tieds );
has_prev_attr = true;
}
query += set;
if ( this->has_lost ) {
set = has_prev_attr ? std::string ( ", " ) : std::string ( "" );
set += std::string ( "lost = " ) + std::to_string ( this->lost );
}
query += set;
return query + std::string ( ";" );
}
std::string Player::delete () {
std::string query ( "DELETE FROM Player WHERE " );
std::string where;
if ( !this->has_id && !this->has_username ) {
td::cerr << "Operação necessita de uma parâmetro WHERE" << std::endl;
return NULL;
}
if ( this->has_id ) {
where = std::string ( "id = " ) + std::to_string ( this->id );
}
query += where;
if ( this->has_username ) {
where = this->has_id ? std::string ( " AND " ) : std::string ( "" );
where += std::string ( "username = " ) + this->username;
}
query += where;
return query + std::string ( ";" )
}
bool Player::check_password ( std::string pass ) {
if ( !this->has_password ) return false;
return this->password == pass;
}
Player* Player::from_db ( db_data_t data ) {
Player* player = new Player ();
return player->set_id ( std::atoi ( data.at ( 0 ).c_str () ) )
->set_username ( data.at ( 1 ) )
->set_password ( data.at ( 2 ) )
->set_wins ( std::atoi ( data.at ( 3 ).c_str () ) )
->set_tieds ( std::atoi ( data.at ( 4 ).c_str () ) )
->set_lost ( std::atoi ( data.at ( 5 ).c_str () ) );
}
| 23.650862 | 80 | 0.549116 | ogoes |
d0e2fd2f550b346519cc9e222304baaa651d8683 | 1,299 | cpp | C++ | ejercicios/cocineros/chef.cpp | jrinconada/cpp-examples | 069e3cc910b2c2d0716af36bef28336003fb6d9e | [
"MIT"
] | 1 | 2018-02-22T12:33:44.000Z | 2018-02-22T12:33:44.000Z | ejercicios/cocineros/chef.cpp | jrinconada/cpp-examples | 069e3cc910b2c2d0716af36bef28336003fb6d9e | [
"MIT"
] | null | null | null | ejercicios/cocineros/chef.cpp | jrinconada/cpp-examples | 069e3cc910b2c2d0716af36bef28336003fb6d9e | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <mutex>
#include "../../hilos/semaphore.cpp"
#include "recipe.cpp"
mutex knife;
mutex oven;
Semaphore semaphore;
class Chef {
void cut(Recipe* r) {
lock_guard<mutex> guard(knife);
for (int i = 0; i < r->cuttingTime; i++) {
std::cout << name + " cortando " + r->name
+ ", " + to_string(i + 1) + " seg\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void bake(Recipe* r) {
lock_guard<mutex> guard(oven);
for (int i = 0; i < r->bakingTime; i++) {
std::cout << name + " horneando " + r->name
+ ", " + to_string(i + 1) + " seg\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
r->prom.set_value(r->name);
}
public:
vector<Recipe*> recipes;
string name;
string type;
Chef(string n, string t = "") : name(n), type(t) {}
void cook() {
for (auto& r : recipes) {
if (type == "cutter") {
cut(r);
semaphore.notify();
} else if (type == "baker") {
semaphore.wait();
bake(r);
} else {
cut(r);
bake(r);
}
}
}
};
| 24.980769 | 65 | 0.458814 | jrinconada |
d0e8105c9fc484adf8a360f7427a674672bb6d84 | 9,379 | cpp | C++ | src/chainsim/PuyoField.cpp | puyogg/puyo-chain-detector | b71811759c31dc5041d4f3b2d1c89bf7bec0d89f | [
"MIT"
] | 5 | 2020-09-14T14:03:58.000Z | 2022-01-21T04:03:08.000Z | src/chainsim/PuyoField.cpp | puyogg/puyo-chain-detector | b71811759c31dc5041d4f3b2d1c89bf7bec0d89f | [
"MIT"
] | 5 | 2021-02-13T03:11:13.000Z | 2022-03-12T00:54:25.000Z | src/chainsim/PuyoField.cpp | puyogg/puyo-chain-detector | b71811759c31dc5041d4f3b2d1c89bf7bec0d89f | [
"MIT"
] | 2 | 2020-08-15T14:59:14.000Z | 2020-08-15T16:34:53.000Z | #include "Fields.hpp"
#include <queue>
#include <iostream>
namespace Chainsim {
// Puyo Field class
PuyoField::PuyoField()
: Field<Color>(DEFAULT_ROWS, DEFAULT_COLS),
m_hrows{ DEFAULT_HROWS },
m_puyoToPop{ DEFAULT_PUYOTOPOP }
{
m_data = std::vector<Color>(m_cols * m_rows, Color::NONE);
m_bool = BoolField(m_rows, m_cols);
m_chainLength = 0;
}
PuyoField::PuyoField(int rows, int cols)
: Field<Color>(rows, cols),
m_hrows{ DEFAULT_HROWS },
m_puyoToPop{ DEFAULT_PUYOTOPOP}
{
m_data = std::vector<Color>(m_cols * m_rows, Color::NONE);
m_chainLength = 0;
}
PuyoField::PuyoField(int rows, int cols, int hrows)
: Field<Color>(rows, cols),
m_hrows{ hrows },
m_puyoToPop{ DEFAULT_PUYOTOPOP}
{
m_data = std::vector<Color>(m_cols * m_rows, Color::NONE);
m_chainLength = 0;
}
PuyoField::PuyoField(int rows, int cols, int hrows, int puyoToPop)
: Field<Color>(rows, cols),
m_hrows{ hrows },
m_puyoToPop{ puyoToPop }
{
m_data = std::vector<Color>(m_cols * m_rows, Color::NONE);
m_chainLength = 0;
}
void PuyoField::setIntField(std::vector<std::vector<int>> intVec2d)
{
int rows { static_cast<int>(intVec2d.size()) };
int cols { static_cast<int>(intVec2d.at(0).size()) };
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
Field<Color>::set(r, c, static_cast<Color>(intVec2d[r][c]));
}
}
}
void PuyoField::reset()
{
std::fill(m_data.begin(), m_data.end(), Color::NONE);
}
void PuyoField::dropPuyos()
{
// In each column...
for (int c = 0; c < m_cols; c++)
{
int end = m_rows - 1;
// Traverse the rows bottom to top
for (int r = end; r >= 0; r--)
{
Color current = get(r, c);
// If the current cell isn't empty...
if (get(r, c) != Color::NONE)
{
// Move it to the cell currently marked as "end"
set(end, c, current);
// Empty the current cell
if (r != end) set(r, c, Color::NONE);
// Shift "end" to the next highest cell
end--;
}
}
}
}
bool PuyoField::isColoredAt(int row, int col)
{
Color cellColor{ get(row, col) };
return cellColor >= Color::RED && cellColor <= Color::PURPLE;
}
PopData PuyoField::checkPops()
{
PopCounts popCounts;
PopColors popColors;
PopPositions popPositions;
m_bool.reset();
std::queue<Pos> checkQueue{};
// Find connected components
for (int r = m_hrows; r < m_rows; r++)
{
for (int c = 0; c < m_cols; c++)
{
// If the cell has already been checked, or if it's empty, skip
if (m_bool.get(r, c)) continue;
Color color = get(r, c);
// If the cell is empty or a garbage Puyo, skip
if (color == Color::NONE || color == Color::GARBAGE) continue;
// Otherwise, the cell is colored. Start a group search, starting
// at the current position.
std::vector<Pos> groupPositions{};
checkQueue.push(Pos{r, c});
while (checkQueue.size() > 0)
{
Pos current = checkQueue.front();
if (!m_bool.get(current.r, current.c))
{
groupPositions.push_back(current);
if (current.r > m_hrows && get(current.r - 1, current.c) == color) checkQueue.push(Pos{ current.r - 1, current.c });
if (current.r < m_rows - 1 && get(current.r + 1, current.c) == color) checkQueue.push(Pos{ current.r + 1, current.c });
if (current.c > 0 && get(current.r, current.c - 1) == color) checkQueue.push(Pos{ current.r, current.c - 1 });
if (current.c < m_cols - 1 && get(current.r, current.c + 1) == color) checkQueue.push(Pos{ current.r, current.c + 1 });
}
checkQueue.pop();
// Mark the current cell as checked
m_bool.set(current.r, current.c, true);
}
// Add data to lists if it meets the pop size
if (static_cast<int>(groupPositions.size()) >= m_puyoToPop)
{
popCounts.push_back(static_cast<int>(groupPositions.size()));
popColors.insert(color);
popPositions.insert(popPositions.end(), groupPositions.begin(), groupPositions.end());
}
}
}
bool hasPops{ static_cast<int>(popCounts.size()) > 0 };
// Check for adjacent Garbage Puyos and add those to pop positions
std::vector<Pos> garbagePopPositions{};
for (Pos& pos : popPositions)
{
int r = pos.r;
int c = pos.c;
if (r > 0 && get(r - 1, c) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r - 1, c });
if (r < m_rows - 1 && get(r + 1, c) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r + 1, c });
if (c > 0 && get(r, c - 1) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r, c - 1 });
if (c < m_cols - 1 && get(r, c + 1) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r, c + 1 });
}
popPositions.insert(popPositions.end(), garbagePopPositions.begin(), garbagePopPositions.end());
PopData result{ hasPops, popCounts, popColors, popPositions };
return result;
}
void PuyoField::applyPops(PopPositions& positions)
{
for (Pos& pos: positions)
{
set(pos.r, pos.c, Color::NONE);
}
}
int PuyoField::simulate()
{
dropPuyos();
auto [hasPops, popCounts, popColors, popPositions] = checkPops();
if (hasPops)
{
m_chainLength++;
applyPops(popPositions);
simulate();
}
return m_chainLength;
}
void PuyoField::removeFloaters()
{
for (int64_t c = 0; c < m_cols; c++)
{
for (int64_t r = m_rows - 2; r >= 0; r--)
{
bool isPuyo = get(r, c) != Color::NONE;
bool belowIsNone = get(r + 1, c) == Color::NONE;
if (isPuyo && belowIsNone)
{
set(r, c, Color::NONE);
}
}
}
}
std::vector<Pos> PuyoField::surfacePositions()
{
// vector nesting: columns -> row
std::vector<Pos> inds;
for (int c = 0; c < m_cols; c++)
{
// Count the number of empty cells in a column
int nones { -1 };
for (int r = 0; r < m_rows; r++)
{
if (get(r, c) == Color::NONE) nones++;
}
// Don't add columns that are completely full (-1)
if (nones > -1)
{
Pos pos{ nones, c };
inds.push_back(pos);
}
}
return inds;
}
std::vector<std::tuple<Pos, Color>> PuyoField::tryColorsAtPositions(std::vector<Pos>& positions)
{
std::vector<std::tuple<Pos, Color>> result;
for (Pos& pos: positions)
{
int r = pos.r;
int c = pos.c;
// Try out colors based on the surrounding colors
// Look left
if (c > 0 && isColoredAt(r, c - 1))
{
Pos tryPos{ r, c };
Color tryColor{ get(r, c - 1 ) };
result.push_back(std::tuple(tryPos, tryColor));
}
// Look right
if (c < m_cols - 1 && isColoredAt(r, c + 1))
{
Pos tryPos{ r, c };
Color tryColor{ get(r, c + 1) };
result.push_back(std::tuple(tryPos, tryColor));
}
// Look down
if (r < m_rows - 1 && isColoredAt(r + 1, c))
{
Pos tryPos{ r, c };
Color tryColor{ get(r + 1, c) };
result.push_back(std::tuple(tryPos, tryColor));
}
}
return result;
}
std::vector<PuyoField> PuyoField::fieldsToTry(std::vector<std::tuple<Pos, Color>>& colorsAtPositions)
{
std::vector<PuyoField> fields;
for (auto& posCol : colorsAtPositions)
{
auto [pos, color] = posCol;
PuyoField testField(m_rows, m_cols, m_hrows, m_puyoToPop);
copyTo(testField);
testField.set(pos.r, pos.c, color);
// Try to add a second Puyo above to ensure a pop
if (pos.r > 1)
{
testField.set(pos.r - 1, pos.c, color);
}
fields.push_back(testField);
}
return fields;
}
std::vector<std::tuple<Pos, Color, int>> PuyoField::searchForChains()
{
// Ignore floating Puyos
removeFloaters();
// Calculate surface locations
std::vector<Pos> positions{ surfacePositions() };
// Use those surface locations to find what colors to try at them
std::vector<std::tuple<Pos, Color>> colorsAtPositions{ tryColorsAtPositions(positions) };
// Use the color+pos combination to generate fields.
// Vector should be the same length as colorsAtPositions
std::vector<PuyoField> tryFields{ fieldsToTry(colorsAtPositions) };
// Get the length of each chain
std::vector<std::tuple<Pos, Color, int>> results;
for (int i = 0; i < static_cast<int>(tryFields.size()); i++)
{
int length{ tryFields.at(i).simulate() };
if (length >= 2)
{
auto [pos, color] = colorsAtPositions.at(i);
std::tuple<Pos, Color, int> result{ pos, color, length };
results.push_back(result);
}
}
return results;
}
} // end Chainsim namespace
| 28.681957 | 139 | 0.549739 | puyogg |
d0e87fc80e8037fbf633aba724f01d79af7774ae | 189 | hh | C++ | extern/polymesh/src/polymesh/detail/math.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/detail/math.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/detail/math.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
namespace polymesh::detail
{
template <class ScalarT>
struct pos3
{
ScalarT x;
ScalarT y;
ScalarT z;
};
using pos3f = pos3<float>;
using pos3d = pos3<double>;
}
| 11.117647 | 27 | 0.666667 | rovedit |
d0ea73981db21847986e53689154cf0fbab6d01b | 365 | hpp | C++ | Lodestar/aux/AlgebraicOperators.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 4 | 2020-06-05T14:08:23.000Z | 2021-06-26T22:15:31.000Z | Lodestar/aux/AlgebraicOperators.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 2 | 2021-06-25T15:14:01.000Z | 2021-07-01T17:43:20.000Z | Lodestar/aux/AlgebraicOperators.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 1 | 2021-06-16T03:15:23.000Z | 2021-06-16T03:15:23.000Z | //
// Created by Hamza El-Kebir on 6/12/21.
//
#ifndef LODESTAR_ALGEBRAICOPERATORS_HPP
#define LODESTAR_ALGEBRAICOPERATORS_HPP
enum class AlgebraicOperators {
Addition,
Subtraction,
Multiplication,
Division,
Exponentiation
};
template <AlgebraicOperators... TOps>
struct AlgebraicOperatorsPack {
};
#endif //LODESTAR_ALGEBRAICOPERATORS_HPP
| 16.590909 | 40 | 0.761644 | helkebir |
d0ed33f29a6797137fd5f3b159c3b53a2111102c | 5,114 | cpp | C++ | LV5-Using virtual base class/Zadatci_LV5/Zadatci_LV5.cpp | MarioSomodi/Objektno-Orijentirano-Programiranje | f1aaa8162faddf6101721eafa413d00ccf6ff858 | [
"MIT"
] | null | null | null | LV5-Using virtual base class/Zadatci_LV5/Zadatci_LV5.cpp | MarioSomodi/Objektno-Orijentirano-Programiranje | f1aaa8162faddf6101721eafa413d00ccf6ff858 | [
"MIT"
] | null | null | null | LV5-Using virtual base class/Zadatci_LV5/Zadatci_LV5.cpp | MarioSomodi/Objektno-Orijentirano-Programiranje | f1aaa8162faddf6101721eafa413d00ccf6ff858 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include <iostream>
#include "Krug.h"
#include "Trokut.h"
#include "Kvadrat.h"
#include <vector>
#include "tinyxml2.h"
#include <iterator>
#include <algorithm>
using namespace tinyxml2;
using namespace std;
int main()
{
/* Testing
Krug k1(12.23, "plavi");
cout << k1.DajOpseg() << endl;
cout << k1.DajPovrsinu() << endl;
cout << k1.DajTip() << endl;
cout << k1.DajBoju() << endl;
k1.Crtaj();
Trokut t1(34.23, "crveni");
cout << t1.DajOpseg() << endl;
cout << t1.DajPovrsinu() << endl;
cout << t1.DajTip() << endl;
cout << t1.DajBoju() << endl;
t1.Crtaj();
Kvadrat kv1(16.23, "zeleni");
cout << kv1.DajOpseg() << endl;
cout << kv1.DajPovrsinu() << endl;
cout << kv1.DajTip() << endl;
cout << kv1.DajBoju() << endl;
kv1.Crtaj();
*/
vector<GrafObj*> vGrafOkjeti;
vector<string> vBoje;
vector<GrafObj*>::iterator itGrafObjekti;
XMLDocument oXmlDocument;
oXmlDocument.LoadFile("grafickiobjekti.xml");
XMLElement* pRoot = oXmlDocument.FirstChildElement("dataset");
XMLElement* pChild;
XMLElement* Krugovi;
XMLElement* Kvadrati;
XMLElement* Trokuti;
for (pChild = pRoot->FirstChildElement("Krugovi"); pChild != NULL; pChild = pChild->NextSiblingElement())
{
for (Krugovi = pChild->FirstChildElement("Krug"); Krugovi != NULL; Krugovi = Krugovi->NextSiblingElement())
{
double dPolumjer = stod(Krugovi->Attribute("polumjer"));
string sBoja = Krugovi->Attribute("boja");
vGrafOkjeti.push_back(new Krug(dPolumjer, sBoja));
}
for (Kvadrati = pChild->FirstChildElement("Kvadrat"); Kvadrati != NULL; Kvadrati = Kvadrati->NextSiblingElement())
{
double dStranica = stod(Kvadrati->Attribute("stranica"));
string sBoja = Kvadrati->Attribute("boja");
vGrafOkjeti.push_back(new Kvadrat(dStranica, sBoja));
}
for (Trokuti = pChild->FirstChildElement("Trokut"); Trokuti != NULL; Trokuti = Trokuti->NextSiblingElement())
{
double dStranica = stod(Trokuti->Attribute("stranica"));
string sBoja = Trokuti->Attribute("boja");
vGrafOkjeti.push_back(new Trokut(dStranica, sBoja));
}
}
for (itGrafObjekti = vGrafOkjeti.begin(); itGrafObjekti != vGrafOkjeti.end(); ++itGrafObjekti)
{
bool sadrzi = false;
(*itGrafObjekti)->Crtaj();
string b = (*itGrafObjekti)->DajBoju();
for (int i = 0; i < vBoje.size(); i++)
{
if (vBoje[i] == b)
{
sadrzi = true;
}
}
if (sadrzi == false)
{
vBoje.push_back(b);
}
}
double dMaxPovrsina = 0, dPovrsinaKrugova = 0, dPovrsinaKvadrata = 0, dPovrsinaTrokuta = 0;
double mPovrsina = 0, mOpseg = 0, nPovrsina = 1000000, nOpseg = 0;
string boja, nBoja, mBoja, mTip, nTip;
for (int i = 0; i < vBoje.size();i++)
{
double dUkupnaPovrsina = 0;
for (itGrafObjekti = vGrafOkjeti.begin(); itGrafObjekti != vGrafOkjeti.end(); ++itGrafObjekti)
{
if ((*itGrafObjekti)->DajBoju() == vBoje[i])
{
dUkupnaPovrsina += (*itGrafObjekti)->DajPovrsinu();
}
if ((*itGrafObjekti)->DajTip() == "Krug")
{
dPovrsinaKrugova += (*itGrafObjekti)->DajPovrsinu();
}
if ((*itGrafObjekti)->DajTip() == "kvadrat")
{
dPovrsinaKvadrata += (*itGrafObjekti)->DajPovrsinu();
}
if ((*itGrafObjekti)->DajTip() == "trokut")
{
dPovrsinaTrokuta += (*itGrafObjekti)->DajPovrsinu();
}
if (mPovrsina < (*itGrafObjekti)->DajPovrsinu())
{
mPovrsina = (*itGrafObjekti)->DajPovrsinu();
mOpseg = (*itGrafObjekti)->DajOpseg();
mTip = (*itGrafObjekti)->DajTip();
mBoja = (*itGrafObjekti)->DajBoju();
}
if (nPovrsina > (*itGrafObjekti)->DajPovrsinu())
{
nPovrsina = (*itGrafObjekti)->DajPovrsinu();
nOpseg = (*itGrafObjekti)->DajOpseg();
nTip = (*itGrafObjekti)->DajTip();
nBoja = (*itGrafObjekti)->DajBoju();
}
}
cout << vBoje[i] << " objekti zauzimaju povrsinu od " << dUkupnaPovrsina << " m2" << endl;
if (dMaxPovrsina < dUkupnaPovrsina)
{
dMaxPovrsina = dUkupnaPovrsina;
boja = vBoje[i];
}
}
cout << boja << " objekti zauzimaju najvise povrsine ukupno " << dMaxPovrsina << " m2" << endl;
if (dPovrsinaKrugova < dPovrsinaKvadrata && dPovrsinaKrugova < dPovrsinaTrokuta)
{
cout << "Najmanje zauzimaju krugovi sa povrsinom od " << dPovrsinaKrugova << endl;
}
else if(dPovrsinaKvadrata < dPovrsinaKrugova && dPovrsinaKvadrata < dPovrsinaTrokuta)
{
cout << "Najmanje zauzimaju kvadrati sa povrsinom od " << dPovrsinaKvadrata << endl;
}
else if (dPovrsinaTrokuta < dPovrsinaKrugova && dPovrsinaTrokuta < dPovrsinaKvadrata)
{
cout << "Najmanje zauzimaju kvadrati sa povrsinom od " << dPovrsinaTrokuta << endl;
}
cout << "Najveci objekt" << endl;
cout << "Tip: " << mTip << endl;
cout << "Povrsina: " << mPovrsina << endl;
cout << "Opseg: " << mOpseg << endl;
cout << "Boja: " << mBoja << endl;
cout << "Najmanji objekt" << endl;
cout << "Tip: " << nTip << endl;
cout << "Povrsina: " << nPovrsina << endl;
cout << "Opseg: " << nOpseg << endl;
cout << "Boja: " << nBoja << endl;
system("pause");
} | 30.993939 | 117 | 0.627689 | MarioSomodi |
d0edbcac303416aaf4fc111d7cbd0fde92d13908 | 250 | hpp | C++ | src/mbgl/style/bucket_parameters.hpp | kravtsun/mapbox-gl-native | ea8ec38df156c6683c886253dbb1f6bc828686ff | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/style/bucket_parameters.hpp | kravtsun/mapbox-gl-native | ea8ec38df156c6683c886253dbb1f6bc828686ff | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/style/bucket_parameters.hpp | kravtsun/mapbox-gl-native | ea8ec38df156c6683c886253dbb1f6bc828686ff | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <mbgl/map/mode.hpp>
#include <mbgl/tile/tile_id.hpp>
namespace mbgl {
namespace style {
class BucketParameters {
public:
const OverscaledTileID tileID;
const MapMode mode;
};
} // namespace style
} // namespace mbgl
| 14.705882 | 34 | 0.72 | kravtsun |
d0f2c99f0a9fda1ba2c1a8e3f35a6b492a5bacde | 47,143 | cpp | C++ | tools/IMFPlayer/src/hardware/dbopl.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 137 | 2015-01-01T21:04:51.000Z | 2022-03-30T01:41:10.000Z | tools/IMFPlayer/src/hardware/dbopl.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 154 | 2015-01-01T16:34:39.000Z | 2022-01-28T14:14:45.000Z | tools/IMFPlayer/src/hardware/dbopl.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 35 | 2015-03-24T02:20:54.000Z | 2021-05-13T11:44:22.000Z | /*
* Copyright (C) 2002-2010 The DOSBox Team
*
* 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) anyght 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.
*/
/*
DOSBox implementation of a combined Yamaha YMF262 and Yamaha YM3812 emulator.
Enabling the opl3 bit will switch the emulator to stereo opl3 output instead of regular mono opl2
Except for the table generation it's all integer math
Can choose different types of generators, using muls and bigger tables, try different ones for slower platforms
The generation was based on the MAME implementation but tried to have it use less memory and be faster in general
MAME uses much bigger envelope tables and this will be the biggest cause of it sounding different at times
//TODO Don't delay first operator 1 sample in opl3 mode
//TODO Maybe not use class method pointers but a regular function pointers with operator as first parameter
//TODO Fix panning for the Percussion channels, would any opl3 player use it and actually really change it though?
//TODO Check if having the same accuracy in all frequency multipliers sounds better or not
//DUNNO Keyon in 4op, switch to 2op without keyoff.
*/
/* $Id: dbopl.cpp,v 1.10 2009-06-10 19:54:51 harekiet Exp $ */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "dbopl.h"
#define GCC_UNLIKELY(x) x
#define TRUE 1
#define FALSE 0
#ifndef PI
#define PI 3.14159265358979323846
#endif
#define OPLRATE ((double)(14318180.0 / 288.0))
#define TREMOLO_TABLE 52
//Try to use most precision for frequencies
//Else try to keep different waves in synch
//#define WAVE_PRECISION 1
#ifndef WAVE_PRECISION
//Wave bits available in the top of the 32bit range
//Original adlib uses 10.10, we use 10.22
#define WAVE_BITS 10
#else
//Need some extra bits at the top to have room for octaves and frequency multiplier
//We support to 8 times lower rate
//128 * 15 * 8 = 15350, 2^13.9, so need 14 bits
#define WAVE_BITS 14
#endif
#define WAVE_SH ( 32 - WAVE_BITS )
#define WAVE_MASK ( ( 1 << WAVE_SH ) - 1 )
//Use the same accuracy as the waves
#define LFO_SH ( WAVE_SH - 10 )
//LFO is controlled by our tremolo 256 sample limit
#define LFO_MAX ( 256 << ( LFO_SH ) )
//Maximum amount of attenuation bits
//Envelope goes to 511, 9 bits
#if (DBOPL_WAVE == WAVE_TABLEMUL )
//Uses the value directly
#define ENV_BITS ( 9 )
#else
//Add 3 bits here for more accuracy and would have to be shifted up either way
#define ENV_BITS ( 9 )
#endif
//Limits of the envelope with those bits and when the envelope goes silent
#define ENV_MIN 0
#define ENV_EXTRA ( ENV_BITS - 9 )
#define ENV_MAX ( 511 << ENV_EXTRA )
#define ENV_LIMIT ( ( 12 * 256) >> ( 3 - ENV_EXTRA ) )
#define ENV_SILENT( _X_ ) ( (_X_) >= ENV_LIMIT )
//Attack/decay/release rate counter shift
#define RATE_SH 24
#define RATE_MASK ( ( 1 << RATE_SH ) - 1 )
//Has to fit within 16bit lookuptable
#define MUL_SH 16
//Check some ranges
#if ENV_EXTRA > 3
#error Too many envelope bits
#endif
static inline void Operator__SetState(Operator *self, Bit8u s );
static inline Bit32u Chip__ForwardNoise(Chip *self);
// C++'s template<> sure is useful sometimes.
static Channel* Channel__BlockTemplate(Channel *self, Chip* chip,
Bit32u samples, Bit32s* output,
SynthMode mode );
#define BLOCK_TEMPLATE(mode) \
static Channel* Channel__BlockTemplate_ ## mode(Channel *self, Chip* chip, \
Bit32u samples, Bit32s* output) \
{ \
return Channel__BlockTemplate(self, chip, samples, output, mode); \
}
BLOCK_TEMPLATE(sm2AM)
BLOCK_TEMPLATE(sm2FM)
BLOCK_TEMPLATE(sm3AM)
BLOCK_TEMPLATE(sm3FM)
BLOCK_TEMPLATE(sm3FMFM)
BLOCK_TEMPLATE(sm3AMFM)
BLOCK_TEMPLATE(sm3FMAM)
BLOCK_TEMPLATE(sm3AMAM)
BLOCK_TEMPLATE(sm2Percussion)
BLOCK_TEMPLATE(sm3Percussion)
//How much to substract from the base value for the final attenuation
static const Bit8u KslCreateTable[16] = {
//0 will always be be lower than 7 * 8
64, 32, 24, 19,
16, 12, 11, 10,
8, 6, 5, 4,
3, 2, 1, 0,
};
#define M(_X_) ((Bit8u)( (_X_) * 2))
static const Bit8u FreqCreateTable[16] = {
M(0.5), M(1 ), M(2 ), M(3 ), M(4 ), M(5 ), M(6 ), M(7 ),
M(8 ), M(9 ), M(10), M(10), M(12), M(12), M(15), M(15)
};
#undef M
//We're not including the highest attack rate, that gets a special value
static const Bit8u AttackSamplesTable[13] = {
69, 55, 46, 40,
35, 29, 23, 20,
19, 15, 11, 10,
9
};
//On a real opl these values take 8 samples to reach and are based upon larger tables
static const Bit8u EnvelopeIncreaseTable[13] = {
4, 5, 6, 7,
8, 10, 12, 14,
16, 20, 24, 28,
32,
};
#if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG )
static Bit16u ExpTable[ 256 ];
#endif
#if ( DBOPL_WAVE == WAVE_HANDLER )
//PI table used by WAVEHANDLER
static Bit16u SinTable[ 512 ];
#endif
#if ( DBOPL_WAVE > WAVE_HANDLER )
//Layout of the waveform table in 512 entry intervals
//With overlapping waves we reduce the table to half it's size
// | |//\\|____|WAV7|//__|/\ |____|/\/\|
// |\\//| | |WAV7| | \/| | |
// |06 |0126|17 |7 |3 |4 |4 5 |5 |
//6 is just 0 shifted and masked
static Bit16s WaveTable[ 8 * 512 ];
//Distance into WaveTable the wave starts
static const Bit16u WaveBaseTable[8] = {
0x000, 0x200, 0x200, 0x800,
0xa00, 0xc00, 0x100, 0x400,
};
//Mask the counter with this
static const Bit16u WaveMaskTable[8] = {
1023, 1023, 511, 511,
1023, 1023, 512, 1023,
};
//Where to start the counter on at keyon
static const Bit16u WaveStartTable[8] = {
512, 0, 0, 0,
0, 512, 512, 256,
};
#endif
#if ( DBOPL_WAVE == WAVE_TABLEMUL )
static Bit16u MulTable[ 384 ];
#endif
static Bit8u KslTable[ 8 * 16 ];
static Bit8u TremoloTable[ TREMOLO_TABLE ];
//Start of a channel behind the chip struct start
static Bit16u ChanOffsetTable[32];
//Start of an operator behind the chip struct start
static Bit16u OpOffsetTable[64];
//The lower bits are the shift of the operator vibrato value
//The highest bit is right shifted to generate -1 or 0 for negation
//So taking the highest input value of 7 this gives 3, 7, 3, 0, -3, -7, -3, 0
static const Bit8s VibratoTable[ 8 ] = {
1 - 0x00, 0 - 0x00, 1 - 0x00, 30 - 0x00,
1 - 0x80, 0 - 0x80, 1 - 0x80, 30 - 0x80
};
//Shift strength for the ksl value determined by ksl strength
static const Bit8u KslShiftTable[4] = {
31,1,2,0
};
//Generate a table index and table shift value using input value from a selected rate
static void EnvelopeSelect( Bit8u val, Bit8u *index, Bit8u *shift ) {
if ( val < 13 * 4 ) { //Rate 0 - 12
*shift = 12 - ( val >> 2 );
*index = val & 3;
} else if ( val < 15 * 4 ) { //rate 13 - 14
*shift = 0;
*index = val - 12 * 4;
} else { //rate 15 and up
*shift = 0;
*index = 12;
}
}
#if ( DBOPL_WAVE == WAVE_HANDLER )
/*
Generate the different waveforms out of the sine/exponetial table using handlers
*/
static inline Bits MakeVolume( Bitu wave, Bitu volume ) {
Bitu total = wave + volume;
Bitu index = total & 0xff;
Bitu sig = ExpTable[ index ];
Bitu exp = total >> 8;
#if 0
//Check if we overflow the 31 shift limit
if ( exp >= 32 ) {
LOG_MSG( "WTF %d %d", total, exp );
}
#endif
return (sig >> exp);
};
static Bits DB_FASTCALL WaveForm0( Bitu i, Bitu volume ) {
Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
Bitu wave = SinTable[i & 511];
return (MakeVolume( wave, volume ) ^ neg) - neg;
}
static Bits DB_FASTCALL WaveForm1( Bitu i, Bitu volume ) {
Bit32u wave = SinTable[i & 511];
wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
return MakeVolume( wave, volume );
}
static Bits DB_FASTCALL WaveForm2( Bitu i, Bitu volume ) {
Bitu wave = SinTable[i & 511];
return MakeVolume( wave, volume );
}
static Bits DB_FASTCALL WaveForm3( Bitu i, Bitu volume ) {
Bitu wave = SinTable[i & 255];
wave |= ( ( (i ^ 256 ) & 256) - 1) >> ( 32 - 12 );
return MakeVolume( wave, volume );
}
static Bits DB_FASTCALL WaveForm4( Bitu i, Bitu volume ) {
//Twice as fast
i <<= 1;
Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
Bitu wave = SinTable[i & 511];
wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
return (MakeVolume( wave, volume ) ^ neg) - neg;
}
static Bits DB_FASTCALL WaveForm5( Bitu i, Bitu volume ) {
//Twice as fast
i <<= 1;
Bitu wave = SinTable[i & 511];
wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
return MakeVolume( wave, volume );
}
static Bits DB_FASTCALL WaveForm6( Bitu i, Bitu volume ) {
Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
return (MakeVolume( 0, volume ) ^ neg) - neg;
}
static Bits DB_FASTCALL WaveForm7( Bitu i, Bitu volume ) {
//Negative is reversed here
Bits neg = (( i >> 9) & 1) - 1;
Bitu wave = (i << 3);
//When negative the volume also runs backwards
wave = ((wave ^ neg) - neg) & 4095;
return (MakeVolume( wave, volume ) ^ neg) - neg;
}
static const WaveHandler WaveHandlerTable[8] = {
WaveForm0, WaveForm1, WaveForm2, WaveForm3,
WaveForm4, WaveForm5, WaveForm6, WaveForm7
};
#endif
/*
Operator
*/
//We zero out when rate == 0
static inline void Operator__UpdateAttack(Operator *self, const Chip* chip ) {
Bit8u rate = self->reg60 >> 4;
if ( rate ) {
Bit8u val = (rate << 2) + self->ksr;
self->attackAdd = chip->attackRates[ val ];
self->rateZero &= ~(1 << ATTACK);
} else {
self->attackAdd = 0;
self->rateZero |= (1 << ATTACK);
}
}
static inline void Operator__UpdateDecay(Operator *self, const Chip* chip ) {
Bit8u rate = self->reg60 & 0xf;
if ( rate ) {
Bit8u val = (rate << 2) + self->ksr;
self->decayAdd = chip->linearRates[ val ];
self->rateZero &= ~(1 << DECAY);
} else {
self->decayAdd = 0;
self->rateZero |= (1 << DECAY);
}
}
static inline void Operator__UpdateRelease(Operator *self, const Chip* chip ) {
Bit8u rate = self->reg80 & 0xf;
if ( rate ) {
Bit8u val = (rate << 2) + self->ksr;
self->releaseAdd = chip->linearRates[ val ];
self->rateZero &= ~(1 << RELEASE);
if ( !(self->reg20 & MASK_SUSTAIN ) ) {
self->rateZero &= ~( 1 << SUSTAIN );
}
} else {
self->rateZero |= (1 << RELEASE);
self->releaseAdd = 0;
if ( !(self->reg20 & MASK_SUSTAIN ) ) {
self->rateZero |= ( 1 << SUSTAIN );
}
}
}
static inline void Operator__UpdateAttenuation(Operator *self) {
Bit8u kslBase = (Bit8u)((self->chanData >> SHIFT_KSLBASE) & 0xff);
Bit32u tl = self->reg40 & 0x3f;
Bit8u kslShift = KslShiftTable[ self->reg40 >> 6 ];
//Make sure the attenuation goes to the right bits
self->totalLevel = tl << ( ENV_BITS - 7 ); //Total level goes 2 bits below max
self->totalLevel += ( kslBase << ENV_EXTRA ) >> kslShift;
}
static void Operator__UpdateFrequency(Operator *self) {
Bit32u freq = self->chanData & (( 1 << 10 ) - 1);
Bit32u block = (self->chanData >> 10) & 0xff;
#ifdef WAVE_PRECISION
block = 7 - block;
self->waveAdd = ( freq * self->freqMul ) >> block;
#else
self->waveAdd = ( freq << block ) * self->freqMul;
#endif
if ( self->reg20 & MASK_VIBRATO ) {
self->vibStrength = (Bit8u)(freq >> 7);
#ifdef WAVE_PRECISION
self->vibrato = ( self->vibStrength * self->freqMul ) >> block;
#else
self->vibrato = ( self->vibStrength << block ) * self->freqMul;
#endif
} else {
self->vibStrength = 0;
self->vibrato = 0;
}
}
static void Operator__UpdateRates(Operator *self, const Chip* chip ) {
//Mame seems to reverse this where enabling ksr actually lowers
//the rate, but pdf manuals says otherwise?
Bit8u newKsr = (Bit8u)((self->chanData >> SHIFT_KEYCODE) & 0xff);
if ( !( self->reg20 & MASK_KSR ) ) {
newKsr >>= 2;
}
if ( self->ksr == newKsr )
return;
self->ksr = newKsr;
Operator__UpdateAttack( self, chip );
Operator__UpdateDecay( self, chip );
Operator__UpdateRelease( self, chip );
}
static inline Bit32s Operator__RateForward(Operator *self, Bit32u add ) {
self->rateIndex += add;
Bit32s ret = self->rateIndex >> RATE_SH;
self->rateIndex = self->rateIndex & RATE_MASK;
return ret;
}
static Bits Operator__TemplateVolume(Operator *self, OperatorState yes) {
Bit32s vol = self->volume;
Bit32s change;
switch ( yes ) {
case OFF:
return ENV_MAX;
case ATTACK:
change = Operator__RateForward( self, self->attackAdd );
if ( !change )
return vol;
vol += ( (~vol) * change ) >> 3;
if ( vol < ENV_MIN ) {
self->volume = ENV_MIN;
self->rateIndex = 0;
Operator__SetState( self, DECAY );
return ENV_MIN;
}
break;
case DECAY:
vol += Operator__RateForward( self, self->decayAdd );
if ( GCC_UNLIKELY(vol >= self->sustainLevel) ) {
//Check if we didn't overshoot max attenuation, then just go off
if ( GCC_UNLIKELY(vol >= ENV_MAX) ) {
self->volume = ENV_MAX;
Operator__SetState( self, OFF );
return ENV_MAX;
}
//Continue as sustain
self->rateIndex = 0;
Operator__SetState( self, SUSTAIN );
}
break;
case SUSTAIN:
if ( self->reg20 & MASK_SUSTAIN ) {
return vol;
}
//In sustain phase, but not sustaining, do regular release
case RELEASE:
vol += Operator__RateForward( self, self->releaseAdd );;
if ( GCC_UNLIKELY(vol >= ENV_MAX) ) {
self->volume = ENV_MAX;
Operator__SetState( self, OFF );
return ENV_MAX;
}
break;
}
self->volume = vol;
return vol;
}
#define TEMPLATE_VOLUME(mode) \
static Bits Operator__TemplateVolume ## mode(Operator *self) \
{ \
return Operator__TemplateVolume(self, mode); \
}
TEMPLATE_VOLUME(OFF)
TEMPLATE_VOLUME(RELEASE)
TEMPLATE_VOLUME(SUSTAIN)
TEMPLATE_VOLUME(ATTACK)
TEMPLATE_VOLUME(DECAY)
static const VolumeHandler VolumeHandlerTable[5] = {
&Operator__TemplateVolumeOFF,
&Operator__TemplateVolumeRELEASE,
&Operator__TemplateVolumeSUSTAIN,
&Operator__TemplateVolumeDECAY,
&Operator__TemplateVolumeATTACK,
};
static inline Bitu Operator__ForwardVolume(Operator *self) {
return self->currentLevel + (self->volHandler)(self);
}
static inline Bitu Operator__ForwardWave(Operator *self) {
self->waveIndex += self->waveCurrent;
return self->waveIndex >> WAVE_SH;
}
static void Operator__Write20(Operator *self, const Chip* chip, Bit8u val ) {
Bit8u change = (self->reg20 ^ val );
if ( !change )
return;
self->reg20 = val;
//Shift the tremolo bit over the entire register, saved a branch, YES!
self->tremoloMask = (Bit8s)(val) >> 7;
self->tremoloMask &= ~(( 1 << ENV_EXTRA ) -1);
//Update specific features based on changes
if ( change & MASK_KSR ) {
Operator__UpdateRates( self, chip );
}
//With sustain enable the volume doesn't change
if ( self->reg20 & MASK_SUSTAIN || ( !self->releaseAdd ) ) {
self->rateZero |= ( 1 << SUSTAIN );
} else {
self->rateZero &= ~( 1 << SUSTAIN );
}
//Frequency multiplier or vibrato changed
if ( change & (0xf | MASK_VIBRATO) ) {
self->freqMul = chip->freqMul[ val & 0xf ];
Operator__UpdateFrequency(self);
}
}
static void Operator__Write40(Operator *self, const Chip *chip, Bit8u val ) {
if (!(self->reg40 ^ val ))
return;
self->reg40 = val;
Operator__UpdateAttenuation( self );
}
static void Operator__Write60(Operator *self, const Chip* chip, Bit8u val ) {
Bit8u change = self->reg60 ^ val;
self->reg60 = val;
if ( change & 0x0f ) {
Operator__UpdateDecay( self, chip );
}
if ( change & 0xf0 ) {
Operator__UpdateAttack( self, chip );
}
}
static void Operator__Write80(Operator *self, const Chip* chip, Bit8u val ) {
Bit8u change = (self->reg80 ^ val );
if ( !change )
return;
self->reg80 = val;
Bit8u sustain = val >> 4;
//Turn 0xf into 0x1f
sustain |= ( sustain + 1) & 0x10;
self->sustainLevel = sustain << ( ENV_BITS - 5 );
if ( change & 0x0f ) {
Operator__UpdateRelease( self, chip );
}
}
static void Operator__WriteE0(Operator *self, const Chip* chip, Bit8u val ) {
if ( !(self->regE0 ^ val) )
return;
//in opl3 mode you can always selet 7 waveforms regardless of waveformselect
Bit8u waveForm = val & ( ( 0x3 & chip->waveFormMask ) | (0x7 & chip->opl3Active ) );
self->regE0 = val;
#if( DBOPL_WAVE == WAVE_HANDLER )
self->waveHandler = WaveHandlerTable[ waveForm ];
#else
self->waveBase = WaveTable + WaveBaseTable[ waveForm ];
self->waveStart = WaveStartTable[ waveForm ] << WAVE_SH;
self->waveMask = WaveMaskTable[ waveForm ];
#endif
}
static inline void Operator__SetState(Operator *self, Bit8u s ) {
self->state = s;
self->volHandler = VolumeHandlerTable[ s ];
}
static inline int Operator__Silent(Operator *self) {
if ( !ENV_SILENT( self->totalLevel + self->volume ) )
return FALSE;
if ( !(self->rateZero & ( 1 << self->state ) ) )
return FALSE;
return TRUE;
}
static inline void Operator__Prepare(Operator *self, const Chip* chip ) {
self->currentLevel = self->totalLevel + (chip->tremoloValue & self->tremoloMask);
self->waveCurrent = self->waveAdd;
if ( self->vibStrength >> chip->vibratoShift ) {
Bit32s add = self->vibrato >> chip->vibratoShift;
//Sign extend over the shift value
Bit32s neg = chip->vibratoSign;
//Negate the add with -1 or 0
add = ( add ^ neg ) - neg;
self->waveCurrent += add;
}
}
static void Operator__KeyOn(Operator *self, Bit8u mask ) {
if ( !self->keyOn ) {
//Restart the frequency generator
#if( DBOPL_WAVE > WAVE_HANDLER )
self->waveIndex = self->waveStart;
#else
self->waveIndex = 0;
#endif
self->rateIndex = 0;
Operator__SetState( self, ATTACK );
}
self->keyOn |= mask;
}
static void Operator__KeyOff(Operator *self, Bit8u mask ) {
self->keyOn &= ~mask;
if ( !self->keyOn ) {
if ( self->state != OFF ) {
Operator__SetState( self, RELEASE );
}
}
}
static inline Bits Operator__GetWave(Operator *self, Bitu index, Bitu vol ) {
#if( DBOPL_WAVE == WAVE_HANDLER )
return self->waveHandler( index, vol << ( 3 - ENV_EXTRA ) );
#elif( DBOPL_WAVE == WAVE_TABLEMUL )
return(self->waveBase[ index & self->waveMask ] * MulTable[ vol >> ENV_EXTRA ]) >> MUL_SH;
#elif( DBOPL_WAVE == WAVE_TABLELOG )
Bit32s wave = self->waveBase[ index & self->waveMask ];
Bit32u total = ( wave & 0x7fff ) + vol << ( 3 - ENV_EXTRA );
Bit32s sig = ExpTable[ total & 0xff ];
Bit32u exp = total >> 8;
Bit32s neg = wave >> 16;
return((sig ^ neg) - neg) >> exp;
#else
#error "No valid wave routine"
#endif
}
static inline Bits Operator__GetSample(Operator *self, Bits modulation ) {
Bitu vol = Operator__ForwardVolume(self);
if ( ENV_SILENT( vol ) ) {
//Simply forward the wave
self->waveIndex += self->waveCurrent;
return 0;
} else {
Bitu index = Operator__ForwardWave(self);
index += modulation;
return Operator__GetWave( self, index, vol );
}
}
static void Operator__Operator(Operator *self) {
self->chanData = 0;
self->freqMul = 0;
self->waveIndex = 0;
self->waveAdd = 0;
self->waveCurrent = 0;
self->keyOn = 0;
self->ksr = 0;
self->reg20 = 0;
self->reg40 = 0;
self->reg60 = 0;
self->reg80 = 0;
self->regE0 = 0;
Operator__SetState( self, OFF );
self->rateZero = (1 << OFF);
self->sustainLevel = ENV_MAX;
self->currentLevel = ENV_MAX;
self->totalLevel = ENV_MAX;
self->volume = ENV_MAX;
self->releaseAdd = 0;
}
/*
Channel
*/
static void Channel__Channel(Channel *self) {
Operator__Operator(&self->op[0]);
Operator__Operator(&self->op[1]);
self->old[0] = self->old[1] = 0;
self->chanData = 0;
self->regB0 = 0;
self->regC0 = 0;
self->maskLeft = -1;
self->maskRight = -1;
self->feedback = 31;
self->fourMask = 0;
self->synthHandler = Channel__BlockTemplate_sm2FM;
};
static inline Operator* Channel__Op( Channel *self, Bitu index ) {
return &( ( self + (index >> 1) )->op[ index & 1 ]);
}
static void Channel__SetChanData(Channel *self, const Chip* chip, Bit32u data ) {
Bit32u change = self->chanData ^ data;
self->chanData = data;
Channel__Op( self, 0 )->chanData = data;
Channel__Op( self, 1 )->chanData = data;
//Since a frequency update triggered this, always update frequency
Operator__UpdateFrequency(Channel__Op( self, 0 ));
Operator__UpdateFrequency(Channel__Op( self, 1 ));
if ( change & ( 0xff << SHIFT_KSLBASE ) ) {
Operator__UpdateAttenuation(Channel__Op( self, 0 ));
Operator__UpdateAttenuation(Channel__Op( self, 1 ));
}
if ( change & ( 0xff << SHIFT_KEYCODE ) ) {
Operator__UpdateRates(Channel__Op( self, 0 ), chip);
Operator__UpdateRates(Channel__Op( self, 1 ), chip);
}
}
static void Channel__UpdateFrequency(Channel *self, const Chip* chip, Bit8u fourOp ) {
//Extrace the frequency bits
Bit32u data = self->chanData & 0xffff;
Bit32u kslBase = KslTable[ data >> 6 ];
Bit32u keyCode = ( data & 0x1c00) >> 9;
if ( chip->reg08 & 0x40 ) {
keyCode |= ( data & 0x100)>>8; /* notesel == 1 */
} else {
keyCode |= ( data & 0x200)>>9; /* notesel == 0 */
}
//Add the keycode and ksl into the highest bits of chanData
data |= (keyCode << SHIFT_KEYCODE) | ( kslBase << SHIFT_KSLBASE );
Channel__SetChanData( self + 0, chip, data );
if ( fourOp & 0x3f ) {
Channel__SetChanData( self + 1, chip, data );
}
}
static void Channel__WriteA0(Channel *self, const Chip* chip, Bit8u val ) {
Bit8u fourOp = chip->reg104 & chip->opl3Active & self->fourMask;
//Don't handle writes to silent fourop channels
if ( fourOp > 0x80 )
return;
Bit32u change = (self->chanData ^ val ) & 0xff;
if ( change ) {
self->chanData ^= change;
Channel__UpdateFrequency( self, chip, fourOp );
}
}
static void Channel__WriteB0(Channel *self, const Chip* chip, Bit8u val ) {
Bit8u fourOp = chip->reg104 & chip->opl3Active & self->fourMask;
//Don't handle writes to silent fourop channels
if ( fourOp > 0x80 )
return;
Bitu change = (self->chanData ^ ( val << 8 ) ) & 0x1f00;
if ( change ) {
self->chanData ^= change;
Channel__UpdateFrequency( self, chip, fourOp );
}
//Check for a change in the keyon/off state
if ( !(( val ^ self->regB0) & 0x20))
return;
self->regB0 = val;
if ( val & 0x20 ) {
Operator__KeyOn( Channel__Op(self, 0), 0x1 );
Operator__KeyOn( Channel__Op(self, 1), 0x1 );
if ( fourOp & 0x3f ) {
Operator__KeyOn( Channel__Op(self + 1, 0), 1 );
Operator__KeyOn( Channel__Op(self + 1, 1), 1 );
}
} else {
Operator__KeyOff( Channel__Op(self, 0), 0x1 );
Operator__KeyOff( Channel__Op(self, 1), 0x1 );
if ( fourOp & 0x3f ) {
Operator__KeyOff( Channel__Op(self + 1, 0), 1 );
Operator__KeyOff( Channel__Op(self + 1, 1), 1 );
}
}
}
static void Channel__WriteC0(Channel *self, const Chip* chip, Bit8u val ) {
Bit8u change = val ^ self->regC0;
if ( !change )
return;
self->regC0 = val;
self->feedback = ( val >> 1 ) & 7;
if ( self->feedback ) {
//We shift the input to the right 10 bit wave index value
self->feedback = 9 - self->feedback;
} else {
self->feedback = 31;
}
//Select the new synth mode
if ( chip->opl3Active ) {
//4-op mode enabled for this channel
if ( (chip->reg104 & self->fourMask) & 0x3f ) {
Channel* chan0, *chan1;
//Check if it's the 2nd channel in a 4-op
if ( !(self->fourMask & 0x80 ) ) {
chan0 = self;
chan1 = self + 1;
} else {
chan0 = self - 1;
chan1 = self;
}
Bit8u synth = ( (chan0->regC0 & 1) << 0 )| (( chan1->regC0 & 1) << 1 );
switch ( synth ) {
case 0:
chan0->synthHandler = Channel__BlockTemplate_sm3FMFM;
break;
case 1:
chan0->synthHandler = Channel__BlockTemplate_sm3AMFM;
break;
case 2:
chan0->synthHandler = Channel__BlockTemplate_sm3FMAM ;
break;
case 3:
chan0->synthHandler = Channel__BlockTemplate_sm3AMAM ;
break;
}
//Disable updating percussion channels
} else if ((self->fourMask & 0x40) && ( chip->regBD & 0x20) ) {
//Regular dual op, am or fm
} else if ( val & 1 ) {
self->synthHandler = Channel__BlockTemplate_sm3AM;
} else {
self->synthHandler = Channel__BlockTemplate_sm3FM;
}
self->maskLeft = ( val & 0x10 ) ? -1 : 0;
self->maskRight = ( val & 0x20 ) ? -1 : 0;
//opl2 active
} else {
//Disable updating percussion channels
if ( (self->fourMask & 0x40) && ( chip->regBD & 0x20 ) ) {
//Regular dual op, am or fm
} else if ( val & 1 ) {
self->synthHandler = Channel__BlockTemplate_sm2AM;
} else {
self->synthHandler = Channel__BlockTemplate_sm2FM;
}
}
}
static void Channel__ResetC0(Channel *self, const Chip* chip ) {
Bit8u val = self->regC0;
self->regC0 ^= 0xff;
Channel__WriteC0( self, chip, val );
};
static inline void Channel__GeneratePercussion(Channel *self, Chip* chip,
Bit32s* output, int opl3Mode ) {
Channel* chan = self;
//BassDrum
Bit32s mod = (Bit32u)((self->old[0] + self->old[1])) >> self->feedback;
self->old[0] = self->old[1];
self->old[1] = Operator__GetSample( Channel__Op(self, 0), mod );
//When bassdrum is in AM mode first operator is ignoed
if ( chan->regC0 & 1 ) {
mod = 0;
} else {
mod = self->old[0];
}
Bit32s sample = Operator__GetSample( Channel__Op(self, 1), mod );
//Precalculate stuff used by other outputs
Bit32u noiseBit = Chip__ForwardNoise(chip) & 0x1;
Bit32u c2 = Operator__ForwardWave(Channel__Op(self, 2));
Bit32u c5 = Operator__ForwardWave(Channel__Op(self, 5));
Bit32u phaseBit = (((c2 & 0x88) ^ ((c2<<5) & 0x80)) | ((c5 ^ (c5<<2)) & 0x20)) ? 0x02 : 0x00;
//Hi-Hat
Bit32u hhVol = Operator__ForwardVolume(Channel__Op(self, 2));
if ( !ENV_SILENT( hhVol ) ) {
Bit32u hhIndex = (phaseBit<<8) | (0x34 << ( phaseBit ^ (noiseBit << 1 )));
sample += Operator__GetWave( Channel__Op(self, 2), hhIndex, hhVol );
}
//Snare Drum
Bit32u sdVol = Operator__ForwardVolume( Channel__Op(self, 3) );
if ( !ENV_SILENT( sdVol ) ) {
Bit32u sdIndex = ( 0x100 + (c2 & 0x100) ) ^ ( noiseBit << 8 );
sample += Operator__GetWave( Channel__Op(self, 3), sdIndex, sdVol );
}
//Tom-tom
sample += Operator__GetSample( Channel__Op(self, 4), 0 );
//Top-Cymbal
Bit32u tcVol = Operator__ForwardVolume(Channel__Op(self, 5));
if ( !ENV_SILENT( tcVol ) ) {
Bit32u tcIndex = (1 + phaseBit) << 8;
sample += Operator__GetWave( Channel__Op(self, 5), tcIndex, tcVol );
}
sample <<= 1;
if ( opl3Mode ) {
output[0] += sample;
output[1] += sample;
} else {
output[0] += sample;
}
}
Channel* Channel__BlockTemplate(Channel *self, Chip* chip,
Bit32u samples, Bit32s* output,
SynthMode mode ) {
Bitu i;
switch( mode ) {
case sm2AM:
case sm3AM:
if ( Operator__Silent(Channel__Op(self, 0))
&& Operator__Silent(Channel__Op(self, 1))) {
self->old[0] = self->old[1] = 0;
return(self + 1);
}
break;
case sm2FM:
case sm3FM:
if ( Operator__Silent(Channel__Op(self, 1))) {
self->old[0] = self->old[1] = 0;
return (self + 1);
}
break;
case sm3FMFM:
if ( Operator__Silent(Channel__Op(self, 3))) {
self->old[0] = self->old[1] = 0;
return (self + 2);
}
break;
case sm3AMFM:
if ( Operator__Silent( Channel__Op(self, 0) )
&& Operator__Silent( Channel__Op(self, 3) )) {
self->old[0] = self->old[1] = 0;
return (self + 2);
}
break;
case sm3FMAM:
if ( Operator__Silent( Channel__Op(self, 1))
&& Operator__Silent( Channel__Op(self, 3))) {
self->old[0] = self->old[1] = 0;
return (self + 2);
}
break;
case sm3AMAM:
if ( Operator__Silent( Channel__Op(self, 0) )
&& Operator__Silent( Channel__Op(self, 2) )
&& Operator__Silent( Channel__Op(self, 3) )) {
self->old[0] = self->old[1] = 0;
return (self + 2);
}
break;
default:
abort();
}
//Init the operators with the the current vibrato and tremolo values
Operator__Prepare( Channel__Op( self, 0 ), chip );
Operator__Prepare( Channel__Op( self, 1 ), chip );
if ( mode > sm4Start ) {
Operator__Prepare( Channel__Op( self, 2 ), chip );
Operator__Prepare( Channel__Op( self, 3 ), chip );
}
if ( mode > sm6Start ) {
Operator__Prepare( Channel__Op( self, 4 ), chip );
Operator__Prepare( Channel__Op( self, 5 ), chip );
}
for ( i = 0; i < samples; i++ ) {
//Early out for percussion handlers
if ( mode == sm2Percussion ) {
Channel__GeneratePercussion( self, chip, output + i, FALSE );
continue; //Prevent some unitialized value bitching
} else if ( mode == sm3Percussion ) {
Channel__GeneratePercussion( self, chip, output + i * 2, TRUE );
continue; //Prevent some unitialized value bitching
}
//Do unsigned shift so we can shift out all bits but still stay in 10 bit range otherwise
Bit32s mod = (Bit32u)((self->old[0] + self->old[1])) >> self->feedback;
self->old[0] = self->old[1];
self->old[1] = Operator__GetSample( Channel__Op(self, 0), mod );
Bit32s sample = 0;
Bit32s out0 = self->old[0];
if ( mode == sm2AM || mode == sm3AM ) {
sample = out0 + Operator__GetSample( Channel__Op(self, 1), 0 );
} else if ( mode == sm2FM || mode == sm3FM ) {
sample = Operator__GetSample( Channel__Op(self, 1), out0 );
} else if ( mode == sm3FMFM ) {
Bits next = Operator__GetSample( Channel__Op(self, 1), out0 );
next = Operator__GetSample( Channel__Op(self, 2), next );
sample = Operator__GetSample( Channel__Op(self, 3), next );
} else if ( mode == sm3AMFM ) {
sample = out0;
Bits next = Operator__GetSample( Channel__Op(self, 1), 0 );
next = Operator__GetSample( Channel__Op(self, 2), next );
sample += Operator__GetSample( Channel__Op(self, 3), next );
} else if ( mode == sm3FMAM ) {
sample = Operator__GetSample( Channel__Op(self, 1), out0 );
Bits next = Operator__GetSample( Channel__Op(self, 2), 0 );
sample += Operator__GetSample( Channel__Op(self, 3), next );
} else if ( mode == sm3AMAM ) {
sample = out0;
Bits next = Operator__GetSample( Channel__Op(self, 1), 0 );
sample += Operator__GetSample( Channel__Op(self, 2), next );
sample += Operator__GetSample( Channel__Op(self, 3), 0 );
}
switch( mode ) {
case sm2AM:
case sm2FM:
output[ i ] += sample;
break;
case sm3AM:
case sm3FM:
case sm3FMFM:
case sm3AMFM:
case sm3FMAM:
case sm3AMAM:
output[ i * 2 + 0 ] += sample & self->maskLeft;
output[ i * 2 + 1 ] += sample & self->maskRight;
break;
default:
abort();
}
}
switch( mode ) {
case sm2AM:
case sm2FM:
case sm3AM:
case sm3FM:
return ( self + 1 );
case sm3FMFM:
case sm3AMFM:
case sm3FMAM:
case sm3AMAM:
return ( self + 2 );
case sm2Percussion:
case sm3Percussion:
return( self + 3 );
default:
abort();
}
return 0;
}
/*
Chip
*/
void Chip__Chip(Chip *self) {
int i;
for (i=0; i<18; ++i) {
Channel__Channel(&self->chan[i]);
}
self->reg08 = 0;
self->reg04 = 0;
self->regBD = 0;
self->reg104 = 0;
self->opl3Active = 0;
}
static inline Bit32u Chip__ForwardNoise(Chip *self) {
self->noiseCounter += self->noiseAdd;
Bitu count = self->noiseCounter >> LFO_SH;
self->noiseCounter &= WAVE_MASK;
for ( ; count > 0; --count ) {
//Noise calculation from mame
self->noiseValue ^= ( 0x800302 ) & ( 0 - (self->noiseValue & 1 ) );
self->noiseValue >>= 1;
}
return self->noiseValue;
}
static inline Bit32u Chip__ForwardLFO(Chip *self, Bit32u samples ) {
//Current vibrato value, runs 4x slower than tremolo
self->vibratoSign = ( VibratoTable[ self->vibratoIndex >> 2] ) >> 7;
self->vibratoShift = ( VibratoTable[ self->vibratoIndex >> 2] & 7) + self->vibratoStrength;
self->tremoloValue = TremoloTable[ self->tremoloIndex ] >> self->tremoloStrength;
//Check hom many samples there can be done before the value changes
Bit32u todo = LFO_MAX - self->lfoCounter;
Bit32u count = (todo + self->lfoAdd - 1) / self->lfoAdd;
if ( count > samples ) {
count = samples;
self->lfoCounter += count * self->lfoAdd;
} else {
self->lfoCounter += count * self->lfoAdd;
self->lfoCounter &= (LFO_MAX - 1);
//Maximum of 7 vibrato value * 4
self->vibratoIndex = ( self->vibratoIndex + 1 ) & 31;
//Clip tremolo to the the table size
if ( self->tremoloIndex + 1 < TREMOLO_TABLE )
++self->tremoloIndex;
else
self->tremoloIndex = 0;
}
return count;
}
static void Chip__WriteBD(Chip *self, Bit8u val ) {
Bit8u change = self->regBD ^ val;
if ( !change )
return;
self->regBD = val;
//TODO could do this with shift and xor?
self->vibratoStrength = (val & 0x40) ? 0x00 : 0x01;
self->tremoloStrength = (val & 0x80) ? 0x00 : 0x02;
if ( val & 0x20 ) {
//Drum was just enabled, make sure channel 6 has the right synth
if ( change & 0x20 ) {
if ( self->opl3Active ) {
self->chan[6].synthHandler
= Channel__BlockTemplate_sm3Percussion;
} else {
self->chan[6].synthHandler
= Channel__BlockTemplate_sm2Percussion;
}
}
//Bass Drum
if ( val & 0x10 ) {
Operator__KeyOn( &self->chan[6].op[0], 0x2 );
Operator__KeyOn( &self->chan[6].op[1], 0x2 );
} else {
Operator__KeyOff( &self->chan[6].op[0], 0x2 );
Operator__KeyOff( &self->chan[6].op[1], 0x2 );
}
//Hi-Hat
if ( val & 0x1 ) {
Operator__KeyOn( &self->chan[7].op[0], 0x2 );
} else {
Operator__KeyOff( &self->chan[7].op[0], 0x2 );
}
//Snare
if ( val & 0x8 ) {
Operator__KeyOn( &self->chan[7].op[1], 0x2 );
} else {
Operator__KeyOff( &self->chan[7].op[1], 0x2 );
}
//Tom-Tom
if ( val & 0x4 ) {
Operator__KeyOn( &self->chan[8].op[0], 0x2 );
} else {
Operator__KeyOff( &self->chan[8].op[0], 0x2 );
}
//Top Cymbal
if ( val & 0x2 ) {
Operator__KeyOn( &self->chan[8].op[1], 0x2 );
} else {
Operator__KeyOff( &self->chan[8].op[1], 0x2 );
}
//Toggle keyoffs when we turn off the percussion
} else if ( change & 0x20 ) {
//Trigger a reset to setup the original synth handler
Channel__ResetC0( &self->chan[6], self );
Operator__KeyOff( &self->chan[6].op[0], 0x2 );
Operator__KeyOff( &self->chan[6].op[1], 0x2 );
Operator__KeyOff( &self->chan[7].op[0], 0x2 );
Operator__KeyOff( &self->chan[7].op[1], 0x2 );
Operator__KeyOff( &self->chan[8].op[0], 0x2 );
Operator__KeyOff( &self->chan[8].op[1], 0x2 );
}
}
#define REGOP( _FUNC_ ) \
index = ( ( reg >> 3) & 0x20 ) | ( reg & 0x1f ); \
if ( OpOffsetTable[ index ] ) { \
Operator* regOp = (Operator*)( ((char *)self ) + OpOffsetTable[ index ] ); \
Operator__ ## _FUNC_ (regOp, self, val); \
}
#define REGCHAN( _FUNC_ ) \
index = ( ( reg >> 4) & 0x10 ) | ( reg & 0xf ); \
if ( ChanOffsetTable[ index ] ) { \
Channel* regChan = (Channel*)( ((char *)self ) + ChanOffsetTable[ index ] ); \
Channel__ ## _FUNC_ (regChan, self, val); \
}
void Chip__WriteReg(Chip *self, Bit32u reg, Bit8u val ) {
Bitu index;
switch ( (reg & 0xf0) >> 4 ) {
case 0x00 >> 4:
if ( reg == 0x01 ) {
self->waveFormMask = ( val & 0x20 ) ? 0x7 : 0x0;
} else if ( reg == 0x104 ) {
//Only detect changes in lowest 6 bits
if ( !((self->reg104 ^ val) & 0x3f) )
return;
//Always keep the highest bit enabled, for checking > 0x80
self->reg104 = 0x80 | ( val & 0x3f );
} else if ( reg == 0x105 ) {
int i;
//MAME says the real opl3 doesn't reset anything on opl3 disable/enable till the next write in another register
if ( !((self->opl3Active ^ val) & 1 ) )
return;
self->opl3Active = ( val & 1 ) ? 0xff : 0;
//Update the 0xc0 register for all channels to signal the switch to mono/stereo handlers
for ( i = 0; i < 18;i++ ) {
Channel__ResetC0( &self->chan[i], self );
}
} else if ( reg == 0x08 ) {
self->reg08 = val;
}
case 0x10 >> 4:
break;
case 0x20 >> 4:
case 0x30 >> 4:
REGOP( Write20 );
break;
case 0x40 >> 4:
case 0x50 >> 4:
REGOP( Write40 );
break;
case 0x60 >> 4:
case 0x70 >> 4:
REGOP( Write60 );
break;
case 0x80 >> 4:
case 0x90 >> 4:
REGOP( Write80 );
break;
case 0xa0 >> 4:
REGCHAN( WriteA0 );
break;
case 0xb0 >> 4:
if ( reg == 0xbd ) {
Chip__WriteBD( self, val );
} else {
REGCHAN( WriteB0 );
}
break;
case 0xc0 >> 4:
REGCHAN( WriteC0 );
case 0xd0 >> 4:
break;
case 0xe0 >> 4:
case 0xf0 >> 4:
REGOP( WriteE0 );
break;
}
}
Bit32u Chip__WriteAddr(Chip *self, Bit32u port, Bit8u val ) {
switch ( port & 3 ) {
case 0:
return val;
case 2:
if ( self->opl3Active || (val == 0x05) )
return 0x100 | val;
else
return val;
}
return 0;
}
void Chip__GenerateBlock2(Chip *self, Bitu total, Bit32s* output ) {
while ( total > 0 ) {
Channel *ch;
int count;
Bit32u samples = Chip__ForwardLFO( self, total );
memset(output, 0, sizeof(Bit32s) * samples);
count = 0;
for ( ch = self->chan; ch < self->chan + 9; ) {
count++;
ch = (ch->synthHandler)( ch, self, samples, output );
}
total -= samples;
output += samples;
}
}
void Chip__GenerateBlock3(Chip *self, Bitu total, Bit32s* output ) {
while ( total > 0 ) {
int count;
Channel *ch;
Bit32u samples = Chip__ForwardLFO( self, total );
memset(output, 0, sizeof(Bit32s) * samples *2);
count = 0;
for ( ch = self->chan; ch < self->chan + 18; ) {
count++;
ch = (ch->synthHandler)( ch, self, samples, output );
}
total -= samples;
output += samples * 2;
}
}
void Chip__Setup(Chip *self, Bit32u rate ) {
double original = OPLRATE;
Bit32u i;
// double original = rate;
double scale = original / (double)rate;
//Noise counter is run at the same precision as general waves
self->noiseAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
self->noiseCounter = 0;
self->noiseValue = 1; //Make sure it triggers the noise xor the first time
//The low frequency oscillation counter
//Every time his overflows vibrato and tremoloindex are increased
self->lfoAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
self->lfoCounter = 0;
self->vibratoIndex = 0;
self->tremoloIndex = 0;
//With higher octave this gets shifted up
//-1 since the freqCreateTable = *2
#ifdef WAVE_PRECISION
double freqScale = ( 1 << 7 ) * scale * ( 1 << ( WAVE_SH - 1 - 10));
for ( i = 0; i < 16; i++ ) {
self->freqMul[i] = (Bit32u)( 0.5 + freqScale * FreqCreateTable[ i ] );
}
#else
Bit32u freqScale = (Bit32u)( 0.5 + scale * ( 1 << ( WAVE_SH - 1 - 10)));
for ( i = 0; i < 16; i++ ) {
self->freqMul[i] = freqScale * FreqCreateTable[ i ];
}
#endif
//-3 since the real envelope takes 8 steps to reach the single value we supply
for ( i = 0; i < 76; i++ ) {
Bit8u index, shift;
EnvelopeSelect( i, &index, &shift );
self->linearRates[i] = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH + ENV_EXTRA - shift - 3 )));
}
//Generate the best matching attack rate
for ( i = 0; i < 62; i++ ) {
Bit8u index, shift;
EnvelopeSelect( i, &index, &shift );
//Original amount of samples the attack would take
Bit32s original = (Bit32u)( (AttackSamplesTable[ index ] << shift) / scale);
Bit32s guessAdd = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH - shift - 3 )));
Bit32s bestAdd = guessAdd;
Bit32u bestDiff = 1 << 30;
Bit32u passes;
for ( passes = 0; passes < 16; passes ++ ) {
Bit32s volume = ENV_MAX;
Bit32s samples = 0;
Bit32u count = 0;
while ( volume > 0 && samples < original * 2 ) {
count += guessAdd;
Bit32s change = count >> RATE_SH;
count &= RATE_MASK;
if ( GCC_UNLIKELY(change) ) { // less than 1 %
volume += ( ~volume * change ) >> 3;
}
samples++;
}
Bit32s diff = original - samples;
Bit32u lDiff = labs( diff );
//Init last on first pass
if ( lDiff < bestDiff ) {
bestDiff = lDiff;
bestAdd = guessAdd;
if ( !bestDiff )
break;
}
//Below our target
if ( diff < 0 ) {
//Better than the last time
Bit32s mul = ((original - diff) << 12) / original;
guessAdd = ((guessAdd * mul) >> 12);
guessAdd++;
} else if ( diff > 0 ) {
Bit32s mul = ((original - diff) << 12) / original;
guessAdd = (guessAdd * mul) >> 12;
guessAdd--;
}
}
self->attackRates[i] = bestAdd;
}
for ( i = 62; i < 76; i++ ) {
//This should provide instant volume maximizing
self->attackRates[i] = 8 << RATE_SH;
}
//Setup the channels with the correct four op flags
//Channels are accessed through a table so they appear linear here
self->chan[ 0].fourMask = 0x00 | ( 1 << 0 );
self->chan[ 1].fourMask = 0x80 | ( 1 << 0 );
self->chan[ 2].fourMask = 0x00 | ( 1 << 1 );
self->chan[ 3].fourMask = 0x80 | ( 1 << 1 );
self->chan[ 4].fourMask = 0x00 | ( 1 << 2 );
self->chan[ 5].fourMask = 0x80 | ( 1 << 2 );
self->chan[ 9].fourMask = 0x00 | ( 1 << 3 );
self->chan[10].fourMask = 0x80 | ( 1 << 3 );
self->chan[11].fourMask = 0x00 | ( 1 << 4 );
self->chan[12].fourMask = 0x80 | ( 1 << 4 );
self->chan[13].fourMask = 0x00 | ( 1 << 5 );
self->chan[14].fourMask = 0x80 | ( 1 << 5 );
//mark the percussion channels
self->chan[ 6].fourMask = 0x40;
self->chan[ 7].fourMask = 0x40;
self->chan[ 8].fourMask = 0x40;
//Clear Everything in opl3 mode
Chip__WriteReg( self, 0x105, 0x1 );
for ( i = 0; i < 512; i++ ) {
if ( i == 0x105 )
continue;
Chip__WriteReg( self, i, 0xff );
Chip__WriteReg( self, i, 0x0 );
}
Chip__WriteReg( self, 0x105, 0x0 );
//Clear everything in opl2 mode
for ( i = 0; i < 255; i++ ) {
Chip__WriteReg( self, i, 0xff );
Chip__WriteReg( self, i, 0x0 );
}
}
static int doneTables = FALSE;
void DBOPL_InitTables( void ) {
int i, oct;
if ( doneTables )
return;
doneTables = TRUE;
#if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG )
//Exponential volume table, same as the real adlib
for ( i = 0; i < 256; i++ ) {
//Save them in reverse
ExpTable[i] = (int)( 0.5 + ( pow(2.0, ( 255 - i) * ( 1.0 /256 ) )-1) * 1024 );
ExpTable[i] += 1024; //or remove the -1 oh well :)
//Preshift to the left once so the final volume can shift to the right
ExpTable[i] *= 2;
}
#endif
#if ( DBOPL_WAVE == WAVE_HANDLER )
//Add 0.5 for the trunc rounding of the integer cast
//Do a PI sinetable instead of the original 0.5 PI
for ( i = 0; i < 512; i++ ) {
SinTable[i] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 );
}
#endif
#if ( DBOPL_WAVE == WAVE_TABLEMUL )
//Multiplication based tables
for ( i = 0; i < 384; i++ ) {
int s = i * 8;
//TODO maybe keep some of the precision errors of the original table?
double val = ( 0.5 + ( pow(2.0, -1.0 + ( 255 - s) * ( 1.0 /256 ) )) * ( 1 << MUL_SH ));
MulTable[i] = (Bit16u)(val);
}
//Sine Wave Base
for ( i = 0; i < 512; i++ ) {
WaveTable[ 0x0200 + i ] = (Bit16s)(sin( (i + 0.5) * (PI / 512.0) ) * 4084);
WaveTable[ 0x0000 + i ] = -WaveTable[ 0x200 + i ];
}
//Exponential wave
for ( i = 0; i < 256; i++ ) {
WaveTable[ 0x700 + i ] = (Bit16s)( 0.5 + ( pow(2.0, -1.0 + ( 255 - i * 8) * ( 1.0 /256 ) ) ) * 4085 );
WaveTable[ 0x6ff - i ] = -WaveTable[ 0x700 + i ];
}
#endif
#if ( DBOPL_WAVE == WAVE_TABLELOG )
//Sine Wave Base
for ( i = 0; i < 512; i++ ) {
WaveTable[ 0x0200 + i ] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 );
WaveTable[ 0x0000 + i ] = ((Bit16s)0x8000) | WaveTable[ 0x200 + i];
}
//Exponential wave
for ( i = 0; i < 256; i++ ) {
WaveTable[ 0x700 + i ] = i * 8;
WaveTable[ 0x6ff - i ] = ((Bit16s)0x8000) | i * 8;
}
#endif
// | |//\\|____|WAV7|//__|/\ |____|/\/\|
// |\\//| | |WAV7| | \/| | |
// |06 |0126|27 |7 |3 |4 |4 5 |5 |
#if (( DBOPL_WAVE == WAVE_TABLELOG ) || ( DBOPL_WAVE == WAVE_TABLEMUL ))
for ( i = 0; i < 256; i++ ) {
//Fill silence gaps
WaveTable[ 0x400 + i ] = WaveTable[0];
WaveTable[ 0x500 + i ] = WaveTable[0];
WaveTable[ 0x900 + i ] = WaveTable[0];
WaveTable[ 0xc00 + i ] = WaveTable[0];
WaveTable[ 0xd00 + i ] = WaveTable[0];
//Replicate sines in other pieces
WaveTable[ 0x800 + i ] = WaveTable[ 0x200 + i ];
//double speed sines
WaveTable[ 0xa00 + i ] = WaveTable[ 0x200 + i * 2 ];
WaveTable[ 0xb00 + i ] = WaveTable[ 0x000 + i * 2 ];
WaveTable[ 0xe00 + i ] = WaveTable[ 0x200 + i * 2 ];
WaveTable[ 0xf00 + i ] = WaveTable[ 0x200 + i * 2 ];
}
#endif
//Create the ksl table
for ( oct = 0; oct < 8; oct++ ) {
int base = oct * 8;
for ( i = 0; i < 16; i++ ) {
int val = base - KslCreateTable[i];
if ( val < 0 )
val = 0;
//*4 for the final range to match attenuation range
KslTable[ oct * 16 + i ] = val * 4;
}
}
//Create the Tremolo table, just increase and decrease a triangle wave
for ( i = 0; i < TREMOLO_TABLE / 2; i++ ) {
Bit8u val = i << ENV_EXTRA;
TremoloTable[i] = val;
TremoloTable[TREMOLO_TABLE - 1 - i] = val;
}
//Create a table with offsets of the channels from the start of the chip
Chip *chip = NULL;
for ( i = 0; i < 32; i++ ) {
Bitu index = i & 0xf;
if ( index >= 9 ) {
ChanOffsetTable[i] = 0;
continue;
}
//Make sure the four op channels follow eachother
if ( index < 6 ) {
index = (index % 3) * 2 + ( index / 3 );
}
//Add back the bits for highest ones
if ( i >= 16 )
index += 9;
Bitu blah = (Bitu) ( &(chip->chan[ index ]) );
ChanOffsetTable[i] = blah;
}
//Same for operators
for ( i = 0; i < 64; i++ ) {
if ( i % 8 >= 6 || ( (i / 8) % 4 == 3 ) ) {
OpOffsetTable[i] = 0;
continue;
}
Bitu chNum = (i / 8) * 3 + (i % 8) % 3;
//Make sure we use 16 and up for the 2nd range to match the chanoffset gap
if ( chNum >= 12 )
chNum += 16 - 12;
Bitu opNum = ( i % 8 ) / 3;
Channel* chan = NULL;
Bitu blah = (Bitu) ( &(chan->op[opNum]) );
OpOffsetTable[i] = ChanOffsetTable[ chNum ] + blah;
}
#if 0
//Stupid checks if table's are correct
for ( Bitu i = 0; i < 18; i++ ) {
Bit32u find = (Bit16u)( &(chip->chan[ i ]) );
for ( Bitu c = 0; c < 32; c++ ) {
if ( ChanOffsetTable[c] == find ) {
find = 0;
break;
}
}
if ( find ) {
find = find;
}
}
for ( Bitu i = 0; i < 36; i++ ) {
Bit32u find = (Bit16u)( &(chip->chan[ i / 2 ].op[i % 2]) );
for ( Bitu c = 0; c < 64; c++ ) {
if ( OpOffsetTable[c] == find ) {
find = 0;
break;
}
}
if ( find ) {
find = find;
}
}
#endif
}
| 30.161868 | 116 | 0.618841 | vogonsorg |
d0f692b7fa12559dfc2a02ac4e554c9e0949afcc | 7,103 | cpp | C++ | src/grpc/quick/qquickgrpcsubscription.cpp | ddobrev/qtprotobuf | c31170f47341c1da9988f7a660be8261d6cdcc6e | [
"MIT"
] | null | null | null | src/grpc/quick/qquickgrpcsubscription.cpp | ddobrev/qtprotobuf | c31170f47341c1da9988f7a660be8261d6cdcc6e | [
"MIT"
] | null | null | null | src/grpc/quick/qquickgrpcsubscription.cpp | ddobrev/qtprotobuf | c31170f47341c1da9988f7a660be8261d6cdcc6e | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
*
* This file is part of qtprotobuf project https://git.semlanik.org/semlanik/qtprotobuf
*
* 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 "qquickgrpcsubscription_p.h"
#include <QGrpcSubscription>
#include <QJSEngine>
#include <QQmlEngine>
using namespace QtProtobuf;
QQuickGrpcSubscription::QQuickGrpcSubscription(QObject *parent) : QObject(parent)
, m_enabled(false)
, m_returnValue(nullptr)
{
}
QQuickGrpcSubscription::~QQuickGrpcSubscription()
{
if (m_subscription) {
m_subscription->cancel();
}
delete m_returnValue;
}
void QQuickGrpcSubscription::updateSubscription()
{
if (m_subscription) {
m_subscription->cancel();
m_subscription.reset();
}
if (m_returnValue != nullptr) {
m_returnValue->deleteLater(); //TODO: probably need to take care about return value cleanup other way. It's just reminder about weak memory management.
m_returnValue = nullptr;
returnValueChanged();
}
if (m_client.isNull() || m_method.isEmpty() || !m_enabled || m_argument.isNull()) {
return;
}
if (!subscribe()) {
setEnabled(false);
}
}
bool QQuickGrpcSubscription::subscribe()
{
QString uppercaseMethodName = m_method;
uppercaseMethodName.replace(0, 1, m_method[0].toUpper());
const QMetaObject *metaObject = m_client->metaObject();
QMetaMethod method;
for (int i = 0; i < metaObject->methodCount(); i++) {
if (QString("qmlSubscribe%1Updates_p").arg(uppercaseMethodName) == metaObject->method(i).name()) {
method = metaObject->method(i);
break;
}
}
QString errorString;
if (!method.isValid()) {
errorString = m_method + "is not either server or bidirectional stream.";
qProtoWarning() << errorString;
error({QGrpcStatus::Unimplemented, errorString});
return false;
}
if (method.parameterCount() < 2) {
errorString = QString("Unable to call ") + method.name() + ". Invalid arguments set.";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
QMetaType argumentPointerMetaType(method.parameterType(0));
if (argumentPointerMetaType.metaObject() != m_argument->metaObject()) {
errorString = QString("Unable to call ") + method.name() + ". Argument type mismatch: '" + method.parameterTypes().at(0) + "' expected, '" + m_argument->metaObject()->className() + "' provided";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
QMetaType argumentMetaType(QMetaType::type(m_argument->metaObject()->className()));
if (!argumentMetaType.isValid()) {
errorString = QString("Argument of type '") + m_argument->metaObject()->className() + "' is not registred in metatype system";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
QObject *argument = reinterpret_cast<QObject*>(argumentMetaType.create(m_argument));
if (argument == nullptr) {
errorString = "Unable to create argument copy. Unknown metatype system error";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
argument->deleteLater(); //TODO: probably need to take care about temporary argument value cleanup other way. It's just reminder about weak memory management.
QMetaType returnPointerType(method.parameterType(1));
if (!returnPointerType.isValid()) {
errorString = QString("Return type argument of type '") + method.parameterTypes().at(1) + "' is not registred in metatype system";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
QMetaType returnMetaType(QMetaType::type(returnPointerType.metaObject()->className()));
if (!returnMetaType.isValid()) {
errorString = QString("Unable to allocate return value. '") + returnPointerType.metaObject()->className() + "' is not registred in metatype system";
qProtoWarning() << errorString;
error({QGrpcStatus::InvalidArgument, errorString});
return false;
}
m_returnValue = reinterpret_cast<QObject*>(returnMetaType.create());
qmlEngine(this)->setObjectOwnership(m_returnValue, QQmlEngine::CppOwnership);
returnValueChanged();
if (m_returnValue == nullptr) {
errorString = "Unable to allocate return value. Unknown metatype system error";
qProtoWarning() << errorString;
error({QGrpcStatus::Unknown, errorString});
return false;
}
QGrpcSubscriptionShared subscription = nullptr;
bool ok = method.invoke(m_client, Qt::DirectConnection,
QGenericReturnArgument("QtProtobuf::QGrpcSubscriptionShared", static_cast<void *>(&subscription)),
QGenericArgument(method.parameterTypes().at(0).data(), static_cast<const void *>(&argument)),
QGenericArgument(method.parameterTypes().at(1).data(), static_cast<const void *>(&m_returnValue)));
if (!ok || subscription == nullptr) {
errorString = QString("Unable to call ") + m_method + " invalidate subscription.";
qProtoWarning() << errorString;
error({QGrpcStatus::Unknown, errorString});
return false;
}
m_subscription = subscription;
connect(m_subscription.get(), &QGrpcSubscription::updated, this, [this](){
updated(qjsEngine(this)->toScriptValue(m_returnValue));
});
connect(m_subscription.get(), &QGrpcSubscription::error, this, &QQuickGrpcSubscription::error);//TODO: Probably it's good idea to disable subscription here
connect(m_subscription.get(), &QGrpcSubscription::finished, this, [this](){ m_subscription.reset(); setEnabled(false); });
return true;
}
| 40.129944 | 202 | 0.680276 | ddobrev |
d0fa11487a08b90b63fc74f7221e94519c49a59a | 784 | cpp | C++ | DeviceCode/Targets/Native/Interop/ManagedCode/CQ_NETMF_CQ_FRK_FM3_Hardware/Stubs/CQ_NETMF_CQ_FRK_FM3_Hardware.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/Native/Interop/ManagedCode/CQ_NETMF_CQ_FRK_FM3_Hardware/Stubs/CQ_NETMF_CQ_FRK_FM3_Hardware.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/Native/Interop/ManagedCode/CQ_NETMF_CQ_FRK_FM3_Hardware/Stubs/CQ_NETMF_CQ_FRK_FM3_Hardware.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | 1 | 2019-12-05T18:59:01.000Z | 2019-12-05T18:59:01.000Z | //-----------------------------------------------------------------------------
//
// ** DO NOT EDIT THIS FILE! **
// This file was generated by a tool
// re-running the tool will overwrite this file.
//
//-----------------------------------------------------------------------------
#include "CQ_NETMF_CQ_FRK_FM3_Hardware.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_CQ_NETMF_CQ_FRK_FM3_Hardware_CQ_NETMF_CQ_FRK_FM3_Hardware_FM3_I2CDevice::I2CDevice_SetChannel___STATIC__VOID__U4,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_CQ_NETMF_CQ_FRK_FM3_Hardware =
{
"CQ_NETMF_CQ_FRK_FM3_Hardware",
0xC1FE27AC,
method_lookup
};
| 22.4 | 125 | 0.572704 | Sirokujira |
d0fc826362cdafb1ef9725642c027f03f8041bf7 | 2,511 | hpp | C++ | include/range/v3/experimental/view/shared.hpp | berolinux/range-v3 | d8ce45f1698931399fb09a322307eb95567be832 | [
"MIT"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | include/range/v3/experimental/view/shared.hpp | berolinux/range-v3 | d8ce45f1698931399fb09a322307eb95567be832 | [
"MIT"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | include/range/v3/experimental/view/shared.hpp | berolinux/range-v3 | d8ce45f1698931399fb09a322307eb95567be832 | [
"MIT"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | /// \file
// Range v3 library
//
// Copyright Filip Matzner 2017
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_EXPERIMENTAL_VIEW_SHARED_HPP
#define RANGES_V3_EXPERIMENTAL_VIEW_SHARED_HPP
#include <memory>
#include <type_traits>
#include <meta/meta.hpp>
#include <range/v3/range/access.hpp>
#include <range/v3/range/concepts.hpp>
#include <range/v3/range/primitives.hpp>
#include <range/v3/view/all.hpp>
namespace ranges
{
namespace experimental
{
template<typename Rng>
struct shared_view
: view_interface<shared_view<Rng>, range_cardinality<Rng>::value>
{
private:
// shared storage
std::shared_ptr<Rng> rng_ptr_;
public:
shared_view() = default;
// construct from a range rvalue
explicit shared_view(Rng && t)
: rng_ptr_{std::make_shared<Rng>(std::move(t))}
{}
// use the stored range's begin and end
iterator_t<Rng> begin() const
{
return ranges::begin(*rng_ptr_);
}
sentinel_t<Rng> end() const
{
return ranges::end(*rng_ptr_);
}
CPP_member
auto CPP_fun(size)()(const requires sized_range<Rng>)
{
return ranges::size(*rng_ptr_);
}
};
/// \relates all
/// \addtogroup group-views
/// @{
namespace views
{
struct shared_fn : pipeable_base
{
public:
template<typename Rng>
auto operator()(Rng && t) const -> CPP_ret(shared_view<Rng>)( //
requires range<Rng> &&
(!view_<Rng>)&&(!std::is_reference<Rng>::value))
{
return shared_view<Rng>{std::move(t)};
}
};
/// \relates all_fn
/// \ingroup group-views
RANGES_INLINE_VARIABLE(shared_fn, shared)
template<typename Rng>
using shared_t = detail::decay_t<decltype(shared(std::declval<Rng>()))>;
} // namespace views
/// @}
} // namespace experimental
} // namespace ranges
#endif // include guard
| 27 | 84 | 0.545998 | berolinux |
d0fe834270a0752580cd614340dd2d036fcc225c | 60,900 | cc | C++ | grpc/clients/cpp/generated/wallet/v1/wallet.pb.cc | legg/api | a818834f8a935b802af3b01b4237e64ed41ab3f2 | [
"MIT"
] | 6 | 2021-05-20T15:30:46.000Z | 2022-02-22T12:06:39.000Z | grpc/clients/cpp/generated/wallet/v1/wallet.pb.cc | legg/api | a818834f8a935b802af3b01b4237e64ed41ab3f2 | [
"MIT"
] | 29 | 2021-03-16T11:58:05.000Z | 2021-10-05T14:04:45.000Z | grpc/clients/cpp/generated/wallet/v1/wallet.pb.cc | legg/api | a818834f8a935b802af3b01b4237e64ed41ab3f2 | [
"MIT"
] | 6 | 2021-05-07T06:43:02.000Z | 2022-03-29T07:18:01.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: wallet/v1/wallet.proto
#include "wallet/v1/wallet.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fvalidator_5fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_ChainEvent_commands_2fv1_2fvalidator_5fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DelegateSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_LiquidityProvisionSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fvalidator_5fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_NodeRegistration_commands_2fv1_2fvalidator_5fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fvalidator_5fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_NodeSignature_commands_2fv1_2fvalidator_5fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fvalidator_5fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_NodeVote_commands_2fv1_2fvalidator_5fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2foracles_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_OracleDataSubmission_commands_2fv1_2foracles_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_OrderAmendment_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_OrderCancellation_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_OrderSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ProposalSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UndelegateSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_VoteSubmission_commands_2fv1_2fcommands_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_commands_2fv1_2fcommands_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_WithdrawSubmission_commands_2fv1_2fcommands_2eproto;
namespace vega {
namespace wallet {
namespace v1 {
class SubmitTransactionRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SubmitTransactionRequest> _instance;
} _SubmitTransactionRequest_default_instance_;
} // namespace v1
} // namespace wallet
} // namespace vega
static void InitDefaultsscc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::vega::wallet::v1::_SubmitTransactionRequest_default_instance_;
new (ptr) ::vega::wallet::v1::SubmitTransactionRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<14> scc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 14, 0, InitDefaultsscc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto}, {
&scc_info_OrderSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_OrderCancellation_commands_2fv1_2fcommands_2eproto.base,
&scc_info_OrderAmendment_commands_2fv1_2fcommands_2eproto.base,
&scc_info_WithdrawSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_ProposalSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_VoteSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_LiquidityProvisionSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_DelegateSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_UndelegateSubmission_commands_2fv1_2fcommands_2eproto.base,
&scc_info_NodeRegistration_commands_2fv1_2fvalidator_5fcommands_2eproto.base,
&scc_info_NodeVote_commands_2fv1_2fvalidator_5fcommands_2eproto.base,
&scc_info_NodeSignature_commands_2fv1_2fvalidator_5fcommands_2eproto.base,
&scc_info_ChainEvent_commands_2fv1_2fvalidator_5fcommands_2eproto.base,
&scc_info_OracleDataSubmission_commands_2fv1_2foracles_2eproto.base,}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_wallet_2fv1_2fwallet_2eproto[1];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_wallet_2fv1_2fwallet_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_wallet_2fv1_2fwallet_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_wallet_2fv1_2fwallet_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::vega::wallet::v1::SubmitTransactionRequest, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::vega::wallet::v1::SubmitTransactionRequest, _oneof_case_[0]),
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::vega::wallet::v1::SubmitTransactionRequest, pub_key_),
PROTOBUF_FIELD_OFFSET(::vega::wallet::v1::SubmitTransactionRequest, propagate_),
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
::PROTOBUF_NAMESPACE_ID::internal::kInvalidFieldOffsetTag,
PROTOBUF_FIELD_OFFSET(::vega::wallet::v1::SubmitTransactionRequest, command_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::vega::wallet::v1::SubmitTransactionRequest)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::vega::wallet::v1::_SubmitTransactionRequest_default_instance_),
};
const char descriptor_table_protodef_wallet_2fv1_2fwallet_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n\026wallet/v1/wallet.proto\022\016vega.wallet.v1"
"\032\032commands/v1/commands.proto\032$commands/v"
"1/validator_commands.proto\032\031commands/v1/"
"oracles.proto\"\205\n\n\030SubmitTransactionReque"
"st\022\027\n\007pub_key\030\001 \001(\tR\006pubKey\022\034\n\tpropagate"
"\030\002 \001(\010R\tpropagate\022O\n\020order_submission\030\351\007"
" \001(\0132!.vega.commands.v1.OrderSubmissionH"
"\000R\017orderSubmission\022U\n\022order_cancellation"
"\030\352\007 \001(\0132#.vega.commands.v1.OrderCancella"
"tionH\000R\021orderCancellation\022L\n\017order_amend"
"ment\030\353\007 \001(\0132 .vega.commands.v1.OrderAmen"
"dmentH\000R\016orderAmendment\022X\n\023withdraw_subm"
"ission\030\354\007 \001(\0132$.vega.commands.v1.Withdra"
"wSubmissionH\000R\022withdrawSubmission\022X\n\023pro"
"posal_submission\030\355\007 \001(\0132$.vega.commands."
"v1.ProposalSubmissionH\000R\022proposalSubmiss"
"ion\022L\n\017vote_submission\030\356\007 \001(\0132 .vega.com"
"mands.v1.VoteSubmissionH\000R\016voteSubmissio"
"n\022w\n\036liquidity_provision_submission\030\357\007 \001"
"(\0132..vega.commands.v1.LiquidityProvision"
"SubmissionH\000R\034liquidityProvisionSubmissi"
"on\022X\n\023delegate_submission\030\360\007 \001(\0132$.vega."
"commands.v1.DelegateSubmissionH\000R\022delega"
"teSubmission\022^\n\025undelegate_submission\030\361\007"
" \001(\0132&.vega.commands.v1.UndelegateSubmis"
"sionH\000R\024undelegateSubmission\022R\n\021node_reg"
"istration\030\321\017 \001(\0132\".vega.commands.v1.Node"
"RegistrationH\000R\020nodeRegistration\022:\n\tnode"
"_vote\030\322\017 \001(\0132\032.vega.commands.v1.NodeVote"
"H\000R\010nodeVote\022I\n\016node_signature\030\323\017 \001(\0132\037."
"vega.commands.v1.NodeSignatureH\000R\rnodeSi"
"gnature\022@\n\013chain_event\030\324\017 \001(\0132\034.vega.com"
"mands.v1.ChainEventH\000R\nchainEvent\022_\n\026ora"
"cle_data_submission\030\271\027 \001(\0132&.vega.comman"
"ds.v1.OracleDataSubmissionH\000R\024oracleData"
"SubmissionB\t\n\007commandBK\n\036io.vegaprotocol"
".vega.wallet.v1Z)code.vegaprotocol.io/ve"
"ga/proto/wallet/v1b\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_wallet_2fv1_2fwallet_2eproto_deps[3] = {
&::descriptor_table_commands_2fv1_2fcommands_2eproto,
&::descriptor_table_commands_2fv1_2foracles_2eproto,
&::descriptor_table_commands_2fv1_2fvalidator_5fcommands_2eproto,
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_wallet_2fv1_2fwallet_2eproto_sccs[1] = {
&scc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_wallet_2fv1_2fwallet_2eproto_once;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_wallet_2fv1_2fwallet_2eproto = {
false, false, descriptor_table_protodef_wallet_2fv1_2fwallet_2eproto, "wallet/v1/wallet.proto", 1506,
&descriptor_table_wallet_2fv1_2fwallet_2eproto_once, descriptor_table_wallet_2fv1_2fwallet_2eproto_sccs, descriptor_table_wallet_2fv1_2fwallet_2eproto_deps, 1, 3,
schemas, file_default_instances, TableStruct_wallet_2fv1_2fwallet_2eproto::offsets,
file_level_metadata_wallet_2fv1_2fwallet_2eproto, 1, file_level_enum_descriptors_wallet_2fv1_2fwallet_2eproto, file_level_service_descriptors_wallet_2fv1_2fwallet_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_wallet_2fv1_2fwallet_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_wallet_2fv1_2fwallet_2eproto)), true);
namespace vega {
namespace wallet {
namespace v1 {
// ===================================================================
class SubmitTransactionRequest::_Internal {
public:
static const ::vega::commands::v1::OrderSubmission& order_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::OrderCancellation& order_cancellation(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::OrderAmendment& order_amendment(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::WithdrawSubmission& withdraw_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::ProposalSubmission& proposal_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::VoteSubmission& vote_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::LiquidityProvisionSubmission& liquidity_provision_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::DelegateSubmission& delegate_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::UndelegateSubmission& undelegate_submission(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::NodeRegistration& node_registration(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::NodeVote& node_vote(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::NodeSignature& node_signature(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::ChainEvent& chain_event(const SubmitTransactionRequest* msg);
static const ::vega::commands::v1::OracleDataSubmission& oracle_data_submission(const SubmitTransactionRequest* msg);
};
const ::vega::commands::v1::OrderSubmission&
SubmitTransactionRequest::_Internal::order_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.order_submission_;
}
const ::vega::commands::v1::OrderCancellation&
SubmitTransactionRequest::_Internal::order_cancellation(const SubmitTransactionRequest* msg) {
return *msg->command_.order_cancellation_;
}
const ::vega::commands::v1::OrderAmendment&
SubmitTransactionRequest::_Internal::order_amendment(const SubmitTransactionRequest* msg) {
return *msg->command_.order_amendment_;
}
const ::vega::commands::v1::WithdrawSubmission&
SubmitTransactionRequest::_Internal::withdraw_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.withdraw_submission_;
}
const ::vega::commands::v1::ProposalSubmission&
SubmitTransactionRequest::_Internal::proposal_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.proposal_submission_;
}
const ::vega::commands::v1::VoteSubmission&
SubmitTransactionRequest::_Internal::vote_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.vote_submission_;
}
const ::vega::commands::v1::LiquidityProvisionSubmission&
SubmitTransactionRequest::_Internal::liquidity_provision_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.liquidity_provision_submission_;
}
const ::vega::commands::v1::DelegateSubmission&
SubmitTransactionRequest::_Internal::delegate_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.delegate_submission_;
}
const ::vega::commands::v1::UndelegateSubmission&
SubmitTransactionRequest::_Internal::undelegate_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.undelegate_submission_;
}
const ::vega::commands::v1::NodeRegistration&
SubmitTransactionRequest::_Internal::node_registration(const SubmitTransactionRequest* msg) {
return *msg->command_.node_registration_;
}
const ::vega::commands::v1::NodeVote&
SubmitTransactionRequest::_Internal::node_vote(const SubmitTransactionRequest* msg) {
return *msg->command_.node_vote_;
}
const ::vega::commands::v1::NodeSignature&
SubmitTransactionRequest::_Internal::node_signature(const SubmitTransactionRequest* msg) {
return *msg->command_.node_signature_;
}
const ::vega::commands::v1::ChainEvent&
SubmitTransactionRequest::_Internal::chain_event(const SubmitTransactionRequest* msg) {
return *msg->command_.chain_event_;
}
const ::vega::commands::v1::OracleDataSubmission&
SubmitTransactionRequest::_Internal::oracle_data_submission(const SubmitTransactionRequest* msg) {
return *msg->command_.oracle_data_submission_;
}
void SubmitTransactionRequest::set_allocated_order_submission(::vega::commands::v1::OrderSubmission* order_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (order_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(order_submission)->GetArena();
if (message_arena != submessage_arena) {
order_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, order_submission, submessage_arena);
}
set_has_order_submission();
command_.order_submission_ = order_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.order_submission)
}
void SubmitTransactionRequest::clear_order_submission() {
if (_internal_has_order_submission()) {
if (GetArena() == nullptr) {
delete command_.order_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_order_cancellation(::vega::commands::v1::OrderCancellation* order_cancellation) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (order_cancellation) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(order_cancellation)->GetArena();
if (message_arena != submessage_arena) {
order_cancellation = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, order_cancellation, submessage_arena);
}
set_has_order_cancellation();
command_.order_cancellation_ = order_cancellation;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.order_cancellation)
}
void SubmitTransactionRequest::clear_order_cancellation() {
if (_internal_has_order_cancellation()) {
if (GetArena() == nullptr) {
delete command_.order_cancellation_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_order_amendment(::vega::commands::v1::OrderAmendment* order_amendment) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (order_amendment) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(order_amendment)->GetArena();
if (message_arena != submessage_arena) {
order_amendment = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, order_amendment, submessage_arena);
}
set_has_order_amendment();
command_.order_amendment_ = order_amendment;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.order_amendment)
}
void SubmitTransactionRequest::clear_order_amendment() {
if (_internal_has_order_amendment()) {
if (GetArena() == nullptr) {
delete command_.order_amendment_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_withdraw_submission(::vega::commands::v1::WithdrawSubmission* withdraw_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (withdraw_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(withdraw_submission)->GetArena();
if (message_arena != submessage_arena) {
withdraw_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, withdraw_submission, submessage_arena);
}
set_has_withdraw_submission();
command_.withdraw_submission_ = withdraw_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.withdraw_submission)
}
void SubmitTransactionRequest::clear_withdraw_submission() {
if (_internal_has_withdraw_submission()) {
if (GetArena() == nullptr) {
delete command_.withdraw_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_proposal_submission(::vega::commands::v1::ProposalSubmission* proposal_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (proposal_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(proposal_submission)->GetArena();
if (message_arena != submessage_arena) {
proposal_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, proposal_submission, submessage_arena);
}
set_has_proposal_submission();
command_.proposal_submission_ = proposal_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.proposal_submission)
}
void SubmitTransactionRequest::clear_proposal_submission() {
if (_internal_has_proposal_submission()) {
if (GetArena() == nullptr) {
delete command_.proposal_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_vote_submission(::vega::commands::v1::VoteSubmission* vote_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (vote_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(vote_submission)->GetArena();
if (message_arena != submessage_arena) {
vote_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, vote_submission, submessage_arena);
}
set_has_vote_submission();
command_.vote_submission_ = vote_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.vote_submission)
}
void SubmitTransactionRequest::clear_vote_submission() {
if (_internal_has_vote_submission()) {
if (GetArena() == nullptr) {
delete command_.vote_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_liquidity_provision_submission(::vega::commands::v1::LiquidityProvisionSubmission* liquidity_provision_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (liquidity_provision_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(liquidity_provision_submission)->GetArena();
if (message_arena != submessage_arena) {
liquidity_provision_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, liquidity_provision_submission, submessage_arena);
}
set_has_liquidity_provision_submission();
command_.liquidity_provision_submission_ = liquidity_provision_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.liquidity_provision_submission)
}
void SubmitTransactionRequest::clear_liquidity_provision_submission() {
if (_internal_has_liquidity_provision_submission()) {
if (GetArena() == nullptr) {
delete command_.liquidity_provision_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_delegate_submission(::vega::commands::v1::DelegateSubmission* delegate_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (delegate_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(delegate_submission)->GetArena();
if (message_arena != submessage_arena) {
delegate_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, delegate_submission, submessage_arena);
}
set_has_delegate_submission();
command_.delegate_submission_ = delegate_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.delegate_submission)
}
void SubmitTransactionRequest::clear_delegate_submission() {
if (_internal_has_delegate_submission()) {
if (GetArena() == nullptr) {
delete command_.delegate_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_undelegate_submission(::vega::commands::v1::UndelegateSubmission* undelegate_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (undelegate_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(undelegate_submission)->GetArena();
if (message_arena != submessage_arena) {
undelegate_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, undelegate_submission, submessage_arena);
}
set_has_undelegate_submission();
command_.undelegate_submission_ = undelegate_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.undelegate_submission)
}
void SubmitTransactionRequest::clear_undelegate_submission() {
if (_internal_has_undelegate_submission()) {
if (GetArena() == nullptr) {
delete command_.undelegate_submission_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_node_registration(::vega::commands::v1::NodeRegistration* node_registration) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (node_registration) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(node_registration)->GetArena();
if (message_arena != submessage_arena) {
node_registration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, node_registration, submessage_arena);
}
set_has_node_registration();
command_.node_registration_ = node_registration;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.node_registration)
}
void SubmitTransactionRequest::clear_node_registration() {
if (_internal_has_node_registration()) {
if (GetArena() == nullptr) {
delete command_.node_registration_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_node_vote(::vega::commands::v1::NodeVote* node_vote) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (node_vote) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(node_vote)->GetArena();
if (message_arena != submessage_arena) {
node_vote = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, node_vote, submessage_arena);
}
set_has_node_vote();
command_.node_vote_ = node_vote;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.node_vote)
}
void SubmitTransactionRequest::clear_node_vote() {
if (_internal_has_node_vote()) {
if (GetArena() == nullptr) {
delete command_.node_vote_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_node_signature(::vega::commands::v1::NodeSignature* node_signature) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (node_signature) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(node_signature)->GetArena();
if (message_arena != submessage_arena) {
node_signature = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, node_signature, submessage_arena);
}
set_has_node_signature();
command_.node_signature_ = node_signature;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.node_signature)
}
void SubmitTransactionRequest::clear_node_signature() {
if (_internal_has_node_signature()) {
if (GetArena() == nullptr) {
delete command_.node_signature_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_chain_event(::vega::commands::v1::ChainEvent* chain_event) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (chain_event) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(chain_event)->GetArena();
if (message_arena != submessage_arena) {
chain_event = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, chain_event, submessage_arena);
}
set_has_chain_event();
command_.chain_event_ = chain_event;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.chain_event)
}
void SubmitTransactionRequest::clear_chain_event() {
if (_internal_has_chain_event()) {
if (GetArena() == nullptr) {
delete command_.chain_event_;
}
clear_has_command();
}
}
void SubmitTransactionRequest::set_allocated_oracle_data_submission(::vega::commands::v1::OracleDataSubmission* oracle_data_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_command();
if (oracle_data_submission) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(oracle_data_submission)->GetArena();
if (message_arena != submessage_arena) {
oracle_data_submission = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, oracle_data_submission, submessage_arena);
}
set_has_oracle_data_submission();
command_.oracle_data_submission_ = oracle_data_submission;
}
// @@protoc_insertion_point(field_set_allocated:vega.wallet.v1.SubmitTransactionRequest.oracle_data_submission)
}
void SubmitTransactionRequest::clear_oracle_data_submission() {
if (_internal_has_oracle_data_submission()) {
if (GetArena() == nullptr) {
delete command_.oracle_data_submission_;
}
clear_has_command();
}
}
SubmitTransactionRequest::SubmitTransactionRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:vega.wallet.v1.SubmitTransactionRequest)
}
SubmitTransactionRequest::SubmitTransactionRequest(const SubmitTransactionRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message() {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
pub_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_pub_key().empty()) {
pub_key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_pub_key(),
GetArena());
}
propagate_ = from.propagate_;
clear_has_command();
switch (from.command_case()) {
case kOrderSubmission: {
_internal_mutable_order_submission()->::vega::commands::v1::OrderSubmission::MergeFrom(from._internal_order_submission());
break;
}
case kOrderCancellation: {
_internal_mutable_order_cancellation()->::vega::commands::v1::OrderCancellation::MergeFrom(from._internal_order_cancellation());
break;
}
case kOrderAmendment: {
_internal_mutable_order_amendment()->::vega::commands::v1::OrderAmendment::MergeFrom(from._internal_order_amendment());
break;
}
case kWithdrawSubmission: {
_internal_mutable_withdraw_submission()->::vega::commands::v1::WithdrawSubmission::MergeFrom(from._internal_withdraw_submission());
break;
}
case kProposalSubmission: {
_internal_mutable_proposal_submission()->::vega::commands::v1::ProposalSubmission::MergeFrom(from._internal_proposal_submission());
break;
}
case kVoteSubmission: {
_internal_mutable_vote_submission()->::vega::commands::v1::VoteSubmission::MergeFrom(from._internal_vote_submission());
break;
}
case kLiquidityProvisionSubmission: {
_internal_mutable_liquidity_provision_submission()->::vega::commands::v1::LiquidityProvisionSubmission::MergeFrom(from._internal_liquidity_provision_submission());
break;
}
case kDelegateSubmission: {
_internal_mutable_delegate_submission()->::vega::commands::v1::DelegateSubmission::MergeFrom(from._internal_delegate_submission());
break;
}
case kUndelegateSubmission: {
_internal_mutable_undelegate_submission()->::vega::commands::v1::UndelegateSubmission::MergeFrom(from._internal_undelegate_submission());
break;
}
case kNodeRegistration: {
_internal_mutable_node_registration()->::vega::commands::v1::NodeRegistration::MergeFrom(from._internal_node_registration());
break;
}
case kNodeVote: {
_internal_mutable_node_vote()->::vega::commands::v1::NodeVote::MergeFrom(from._internal_node_vote());
break;
}
case kNodeSignature: {
_internal_mutable_node_signature()->::vega::commands::v1::NodeSignature::MergeFrom(from._internal_node_signature());
break;
}
case kChainEvent: {
_internal_mutable_chain_event()->::vega::commands::v1::ChainEvent::MergeFrom(from._internal_chain_event());
break;
}
case kOracleDataSubmission: {
_internal_mutable_oracle_data_submission()->::vega::commands::v1::OracleDataSubmission::MergeFrom(from._internal_oracle_data_submission());
break;
}
case COMMAND_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:vega.wallet.v1.SubmitTransactionRequest)
}
void SubmitTransactionRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto.base);
pub_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
propagate_ = false;
clear_has_command();
}
SubmitTransactionRequest::~SubmitTransactionRequest() {
// @@protoc_insertion_point(destructor:vega.wallet.v1.SubmitTransactionRequest)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void SubmitTransactionRequest::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
pub_key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (has_command()) {
clear_command();
}
}
void SubmitTransactionRequest::ArenaDtor(void* object) {
SubmitTransactionRequest* _this = reinterpret_cast< SubmitTransactionRequest* >(object);
(void)_this;
}
void SubmitTransactionRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void SubmitTransactionRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const SubmitTransactionRequest& SubmitTransactionRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SubmitTransactionRequest_wallet_2fv1_2fwallet_2eproto.base);
return *internal_default_instance();
}
void SubmitTransactionRequest::clear_command() {
// @@protoc_insertion_point(one_of_clear_start:vega.wallet.v1.SubmitTransactionRequest)
switch (command_case()) {
case kOrderSubmission: {
if (GetArena() == nullptr) {
delete command_.order_submission_;
}
break;
}
case kOrderCancellation: {
if (GetArena() == nullptr) {
delete command_.order_cancellation_;
}
break;
}
case kOrderAmendment: {
if (GetArena() == nullptr) {
delete command_.order_amendment_;
}
break;
}
case kWithdrawSubmission: {
if (GetArena() == nullptr) {
delete command_.withdraw_submission_;
}
break;
}
case kProposalSubmission: {
if (GetArena() == nullptr) {
delete command_.proposal_submission_;
}
break;
}
case kVoteSubmission: {
if (GetArena() == nullptr) {
delete command_.vote_submission_;
}
break;
}
case kLiquidityProvisionSubmission: {
if (GetArena() == nullptr) {
delete command_.liquidity_provision_submission_;
}
break;
}
case kDelegateSubmission: {
if (GetArena() == nullptr) {
delete command_.delegate_submission_;
}
break;
}
case kUndelegateSubmission: {
if (GetArena() == nullptr) {
delete command_.undelegate_submission_;
}
break;
}
case kNodeRegistration: {
if (GetArena() == nullptr) {
delete command_.node_registration_;
}
break;
}
case kNodeVote: {
if (GetArena() == nullptr) {
delete command_.node_vote_;
}
break;
}
case kNodeSignature: {
if (GetArena() == nullptr) {
delete command_.node_signature_;
}
break;
}
case kChainEvent: {
if (GetArena() == nullptr) {
delete command_.chain_event_;
}
break;
}
case kOracleDataSubmission: {
if (GetArena() == nullptr) {
delete command_.oracle_data_submission_;
}
break;
}
case COMMAND_NOT_SET: {
break;
}
}
_oneof_case_[0] = COMMAND_NOT_SET;
}
void SubmitTransactionRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:vega.wallet.v1.SubmitTransactionRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
pub_key_.ClearToEmpty();
propagate_ = false;
clear_command();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SubmitTransactionRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// string pub_key = 1 [json_name = "pubKey"];
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
auto str = _internal_mutable_pub_key();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "vega.wallet.v1.SubmitTransactionRequest.pub_key"));
CHK_(ptr);
} else goto handle_unusual;
continue;
// bool propagate = 2 [json_name = "propagate"];
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
propagate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.OrderSubmission order_submission = 1001 [json_name = "orderSubmission"];
case 1001:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) {
ptr = ctx->ParseMessage(_internal_mutable_order_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.OrderCancellation order_cancellation = 1002 [json_name = "orderCancellation"];
case 1002:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) {
ptr = ctx->ParseMessage(_internal_mutable_order_cancellation(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.OrderAmendment order_amendment = 1003 [json_name = "orderAmendment"];
case 1003:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) {
ptr = ctx->ParseMessage(_internal_mutable_order_amendment(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.WithdrawSubmission withdraw_submission = 1004 [json_name = "withdrawSubmission"];
case 1004:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) {
ptr = ctx->ParseMessage(_internal_mutable_withdraw_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.ProposalSubmission proposal_submission = 1005 [json_name = "proposalSubmission"];
case 1005:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) {
ptr = ctx->ParseMessage(_internal_mutable_proposal_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.VoteSubmission vote_submission = 1006 [json_name = "voteSubmission"];
case 1006:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 114)) {
ptr = ctx->ParseMessage(_internal_mutable_vote_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.LiquidityProvisionSubmission liquidity_provision_submission = 1007 [json_name = "liquidityProvisionSubmission"];
case 1007:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) {
ptr = ctx->ParseMessage(_internal_mutable_liquidity_provision_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.DelegateSubmission delegate_submission = 1008 [json_name = "delegateSubmission"];
case 1008:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) {
ptr = ctx->ParseMessage(_internal_mutable_delegate_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.UndelegateSubmission undelegate_submission = 1009 [json_name = "undelegateSubmission"];
case 1009:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 138)) {
ptr = ctx->ParseMessage(_internal_mutable_undelegate_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.NodeRegistration node_registration = 2001 [json_name = "nodeRegistration"];
case 2001:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 138)) {
ptr = ctx->ParseMessage(_internal_mutable_node_registration(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.NodeVote node_vote = 2002 [json_name = "nodeVote"];
case 2002:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 146)) {
ptr = ctx->ParseMessage(_internal_mutable_node_vote(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.NodeSignature node_signature = 2003 [json_name = "nodeSignature"];
case 2003:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 154)) {
ptr = ctx->ParseMessage(_internal_mutable_node_signature(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.ChainEvent chain_event = 2004 [json_name = "chainEvent"];
case 2004:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 162)) {
ptr = ctx->ParseMessage(_internal_mutable_chain_event(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .vega.commands.v1.OracleDataSubmission oracle_data_submission = 3001 [json_name = "oracleDataSubmission"];
case 3001:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 202)) {
ptr = ctx->ParseMessage(_internal_mutable_oracle_data_submission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* SubmitTransactionRequest::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:vega.wallet.v1.SubmitTransactionRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string pub_key = 1 [json_name = "pubKey"];
if (this->pub_key().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_pub_key().data(), static_cast<int>(this->_internal_pub_key().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"vega.wallet.v1.SubmitTransactionRequest.pub_key");
target = stream->WriteStringMaybeAliased(
1, this->_internal_pub_key(), target);
}
// bool propagate = 2 [json_name = "propagate"];
if (this->propagate() != 0) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->_internal_propagate(), target);
}
// .vega.commands.v1.OrderSubmission order_submission = 1001 [json_name = "orderSubmission"];
if (_internal_has_order_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1001, _Internal::order_submission(this), target, stream);
}
// .vega.commands.v1.OrderCancellation order_cancellation = 1002 [json_name = "orderCancellation"];
if (_internal_has_order_cancellation()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1002, _Internal::order_cancellation(this), target, stream);
}
// .vega.commands.v1.OrderAmendment order_amendment = 1003 [json_name = "orderAmendment"];
if (_internal_has_order_amendment()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1003, _Internal::order_amendment(this), target, stream);
}
// .vega.commands.v1.WithdrawSubmission withdraw_submission = 1004 [json_name = "withdrawSubmission"];
if (_internal_has_withdraw_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1004, _Internal::withdraw_submission(this), target, stream);
}
// .vega.commands.v1.ProposalSubmission proposal_submission = 1005 [json_name = "proposalSubmission"];
if (_internal_has_proposal_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1005, _Internal::proposal_submission(this), target, stream);
}
// .vega.commands.v1.VoteSubmission vote_submission = 1006 [json_name = "voteSubmission"];
if (_internal_has_vote_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1006, _Internal::vote_submission(this), target, stream);
}
// .vega.commands.v1.LiquidityProvisionSubmission liquidity_provision_submission = 1007 [json_name = "liquidityProvisionSubmission"];
if (_internal_has_liquidity_provision_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1007, _Internal::liquidity_provision_submission(this), target, stream);
}
// .vega.commands.v1.DelegateSubmission delegate_submission = 1008 [json_name = "delegateSubmission"];
if (_internal_has_delegate_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1008, _Internal::delegate_submission(this), target, stream);
}
// .vega.commands.v1.UndelegateSubmission undelegate_submission = 1009 [json_name = "undelegateSubmission"];
if (_internal_has_undelegate_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1009, _Internal::undelegate_submission(this), target, stream);
}
// .vega.commands.v1.NodeRegistration node_registration = 2001 [json_name = "nodeRegistration"];
if (_internal_has_node_registration()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
2001, _Internal::node_registration(this), target, stream);
}
// .vega.commands.v1.NodeVote node_vote = 2002 [json_name = "nodeVote"];
if (_internal_has_node_vote()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
2002, _Internal::node_vote(this), target, stream);
}
// .vega.commands.v1.NodeSignature node_signature = 2003 [json_name = "nodeSignature"];
if (_internal_has_node_signature()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
2003, _Internal::node_signature(this), target, stream);
}
// .vega.commands.v1.ChainEvent chain_event = 2004 [json_name = "chainEvent"];
if (_internal_has_chain_event()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
2004, _Internal::chain_event(this), target, stream);
}
// .vega.commands.v1.OracleDataSubmission oracle_data_submission = 3001 [json_name = "oracleDataSubmission"];
if (_internal_has_oracle_data_submission()) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
3001, _Internal::oracle_data_submission(this), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:vega.wallet.v1.SubmitTransactionRequest)
return target;
}
size_t SubmitTransactionRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:vega.wallet.v1.SubmitTransactionRequest)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string pub_key = 1 [json_name = "pubKey"];
if (this->pub_key().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_pub_key());
}
// bool propagate = 2 [json_name = "propagate"];
if (this->propagate() != 0) {
total_size += 1 + 1;
}
switch (command_case()) {
// .vega.commands.v1.OrderSubmission order_submission = 1001 [json_name = "orderSubmission"];
case kOrderSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.order_submission_);
break;
}
// .vega.commands.v1.OrderCancellation order_cancellation = 1002 [json_name = "orderCancellation"];
case kOrderCancellation: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.order_cancellation_);
break;
}
// .vega.commands.v1.OrderAmendment order_amendment = 1003 [json_name = "orderAmendment"];
case kOrderAmendment: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.order_amendment_);
break;
}
// .vega.commands.v1.WithdrawSubmission withdraw_submission = 1004 [json_name = "withdrawSubmission"];
case kWithdrawSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.withdraw_submission_);
break;
}
// .vega.commands.v1.ProposalSubmission proposal_submission = 1005 [json_name = "proposalSubmission"];
case kProposalSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.proposal_submission_);
break;
}
// .vega.commands.v1.VoteSubmission vote_submission = 1006 [json_name = "voteSubmission"];
case kVoteSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.vote_submission_);
break;
}
// .vega.commands.v1.LiquidityProvisionSubmission liquidity_provision_submission = 1007 [json_name = "liquidityProvisionSubmission"];
case kLiquidityProvisionSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.liquidity_provision_submission_);
break;
}
// .vega.commands.v1.DelegateSubmission delegate_submission = 1008 [json_name = "delegateSubmission"];
case kDelegateSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.delegate_submission_);
break;
}
// .vega.commands.v1.UndelegateSubmission undelegate_submission = 1009 [json_name = "undelegateSubmission"];
case kUndelegateSubmission: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.undelegate_submission_);
break;
}
// .vega.commands.v1.NodeRegistration node_registration = 2001 [json_name = "nodeRegistration"];
case kNodeRegistration: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.node_registration_);
break;
}
// .vega.commands.v1.NodeVote node_vote = 2002 [json_name = "nodeVote"];
case kNodeVote: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.node_vote_);
break;
}
// .vega.commands.v1.NodeSignature node_signature = 2003 [json_name = "nodeSignature"];
case kNodeSignature: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.node_signature_);
break;
}
// .vega.commands.v1.ChainEvent chain_event = 2004 [json_name = "chainEvent"];
case kChainEvent: {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.chain_event_);
break;
}
// .vega.commands.v1.OracleDataSubmission oracle_data_submission = 3001 [json_name = "oracleDataSubmission"];
case kOracleDataSubmission: {
total_size += 3 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*command_.oracle_data_submission_);
break;
}
case COMMAND_NOT_SET: {
break;
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void SubmitTransactionRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:vega.wallet.v1.SubmitTransactionRequest)
GOOGLE_DCHECK_NE(&from, this);
const SubmitTransactionRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SubmitTransactionRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:vega.wallet.v1.SubmitTransactionRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:vega.wallet.v1.SubmitTransactionRequest)
MergeFrom(*source);
}
}
void SubmitTransactionRequest::MergeFrom(const SubmitTransactionRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:vega.wallet.v1.SubmitTransactionRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.pub_key().size() > 0) {
_internal_set_pub_key(from._internal_pub_key());
}
if (from.propagate() != 0) {
_internal_set_propagate(from._internal_propagate());
}
switch (from.command_case()) {
case kOrderSubmission: {
_internal_mutable_order_submission()->::vega::commands::v1::OrderSubmission::MergeFrom(from._internal_order_submission());
break;
}
case kOrderCancellation: {
_internal_mutable_order_cancellation()->::vega::commands::v1::OrderCancellation::MergeFrom(from._internal_order_cancellation());
break;
}
case kOrderAmendment: {
_internal_mutable_order_amendment()->::vega::commands::v1::OrderAmendment::MergeFrom(from._internal_order_amendment());
break;
}
case kWithdrawSubmission: {
_internal_mutable_withdraw_submission()->::vega::commands::v1::WithdrawSubmission::MergeFrom(from._internal_withdraw_submission());
break;
}
case kProposalSubmission: {
_internal_mutable_proposal_submission()->::vega::commands::v1::ProposalSubmission::MergeFrom(from._internal_proposal_submission());
break;
}
case kVoteSubmission: {
_internal_mutable_vote_submission()->::vega::commands::v1::VoteSubmission::MergeFrom(from._internal_vote_submission());
break;
}
case kLiquidityProvisionSubmission: {
_internal_mutable_liquidity_provision_submission()->::vega::commands::v1::LiquidityProvisionSubmission::MergeFrom(from._internal_liquidity_provision_submission());
break;
}
case kDelegateSubmission: {
_internal_mutable_delegate_submission()->::vega::commands::v1::DelegateSubmission::MergeFrom(from._internal_delegate_submission());
break;
}
case kUndelegateSubmission: {
_internal_mutable_undelegate_submission()->::vega::commands::v1::UndelegateSubmission::MergeFrom(from._internal_undelegate_submission());
break;
}
case kNodeRegistration: {
_internal_mutable_node_registration()->::vega::commands::v1::NodeRegistration::MergeFrom(from._internal_node_registration());
break;
}
case kNodeVote: {
_internal_mutable_node_vote()->::vega::commands::v1::NodeVote::MergeFrom(from._internal_node_vote());
break;
}
case kNodeSignature: {
_internal_mutable_node_signature()->::vega::commands::v1::NodeSignature::MergeFrom(from._internal_node_signature());
break;
}
case kChainEvent: {
_internal_mutable_chain_event()->::vega::commands::v1::ChainEvent::MergeFrom(from._internal_chain_event());
break;
}
case kOracleDataSubmission: {
_internal_mutable_oracle_data_submission()->::vega::commands::v1::OracleDataSubmission::MergeFrom(from._internal_oracle_data_submission());
break;
}
case COMMAND_NOT_SET: {
break;
}
}
}
void SubmitTransactionRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:vega.wallet.v1.SubmitTransactionRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SubmitTransactionRequest::CopyFrom(const SubmitTransactionRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:vega.wallet.v1.SubmitTransactionRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SubmitTransactionRequest::IsInitialized() const {
return true;
}
void SubmitTransactionRequest::InternalSwap(SubmitTransactionRequest* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
pub_key_.Swap(&other->pub_key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(propagate_, other->propagate_);
swap(command_, other->command_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::PROTOBUF_NAMESPACE_ID::Metadata SubmitTransactionRequest::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace v1
} // namespace wallet
} // namespace vega
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::vega::wallet::v1::SubmitTransactionRequest* Arena::CreateMaybeMessage< ::vega::wallet::v1::SubmitTransactionRequest >(Arena* arena) {
return Arena::CreateMessageInternal< ::vega::wallet::v1::SubmitTransactionRequest >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 45.481703 | 194 | 0.750115 | legg |
cb9b706d6bd2c1b1d7243b87017c5e7361fd173c | 443 | cpp | C++ | test/general/headers.cpp | komiga/Beard | 059c7aed8c9d9818bcda2284c1e004309d70d2e1 | [
"MIT"
] | 3 | 2015-06-19T20:06:19.000Z | 2019-04-11T20:04:00.000Z | test/general/headers.cpp | komiga/Beard | 059c7aed8c9d9818bcda2284c1e004309d70d2e1 | [
"MIT"
] | null | null | null | test/general/headers.cpp | komiga/Beard | 059c7aed8c9d9818bcda2284c1e004309d70d2e1 | [
"MIT"
] | null | null | null |
#include <Beard/config.hpp>
#include <Beard/utility.hpp>
#include <Beard/ErrorCode.hpp>
#include <Beard/aux.hpp>
#include <Beard/String.hpp>
#include <Beard/Error.hpp>
#include <Beard/detail/gr_core.hpp>
#include <Beard/detail/gr_ceformat.hpp>
#include <Beard/detail/debug.hpp>
#include <Beard/tty/Defs.hpp>
#include <Beard/tty/Caps.hpp>
#include <Beard/tty/TerminalInfo.hpp>
#include <Beard/tty/Terminal.hpp>
signed
main() {
return 0;
}
| 20.136364 | 39 | 0.742664 | komiga |
cba1c45e531565fdd03678a71570e27ccb506fa4 | 5,693 | cpp | C++ | Simple++/Network/Server.cpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/Network/Server.cpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/Network/Server.cpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | #include "Server.h"
namespace Network {
Server::Server() :
mIsBinded( false ) {
}
Server::~Server() {
close();
}
bool Server::listen( unsigned short port, SockType sockType, IpFamily ipFamily, int maxClients ) {
return _listen( NULL, StringASCII( port ).getData(), sockType, ipFamily, maxClients );
}
bool Server::listen( const StringASCII & address, const StringASCII & service, SockType sockType, IpFamily ipFamily, int maxClients ) {
return _listen( address.getData(), service.getData(), sockType, ipFamily, maxClients );
}
bool Server::listen( const StringASCII & address, unsigned int port, SockType sockType, IpFamily ipFamily, int maxClients ) {
return _listen( address.getData(), StringASCII( port ).getData(), sockType, ipFamily, maxClients );
}
bool Server::listen( const Address & address, int maxClients /*= 100*/ ) {
if ( !Network::init() ) return false;
AddrInfo thisAddrInfo( *( ( AddrInfo * ) &address ) );
if ( ( ( int ) _tryListen( &thisAddrInfo, maxClients ) ) == SOCKET_ERROR ) {
error( StringASCII( "Unable to bind ip " ) << thisAddrInfo.getIpFamilyS() << " : " << thisAddrInfo.getNameInfo() << " on port " << thisAddrInfo.getPort() << " with protocol " << thisAddrInfo.getSockTypeS() );
return false;
}
updateFdSet();
this -> mIsBinded = true;
return true;
}
bool Server::_listen( const char * ip, const char * service, SockType sockType, IpFamily ipFamily, int maxClients /*= 100*/ ) {
if ( !Network::init() ) return false;
AddrInfo hints( sockType, ipFamily );
hints.addFlag( Flags::Passive );
hints.addFlag( Flags::NumericHost );
struct addrinfo * addrResults;
if ( ::getaddrinfo( ip, service, hints.getAddrInfoStruct(), &addrResults ) ) {
error( StringASCII( "Unable to retreive address info on address " ) << ip << "@" << service );
return false;
}
if ( _tryListen( addrResults, maxClients ) == false ) {
error( StringASCII( "Unable to bind on " ) << ( ( AddrInfo ) ( *addrResults ) ).getIpFamilyS() << " : " << ip << " on port " << service << " with Protocol " << ( ( AddrInfo ) ( *addrResults ) ).getSockTypeS() );
freeaddrinfo( addrResults );
return false;
}
freeaddrinfo( addrResults );
updateFdSet();
this -> mIsBinded = true;
return true;
}
bool Server::_tryListen( const struct addrinfo * addrResults, int maxClients ) {
Vector<const AddrInfo *> addrInfoVector;
bool result = false;
for ( const struct addrinfo * AI = addrResults; AI != NULL; AI = AI -> ai_next ) {
AddrInfo * addrInfo = ( AddrInfo* ) AI;
addrInfoVector.push( addrInfo );
if ( this -> mSocketVector.getSize() >= FD_SETSIZE ) {
warn( "getaddrinfo returned more addresses than we could use.\n" );
break;
}
result = _tryListen( addrInfo, maxClients ) || result;
}
return result;
}
bool Server::_tryListen( AddrInfo * addrInfo, int maxClients ) {
if ( addrInfo -> getIpFamily() == IpFamily::Undefined ) {
addrInfo -> setIpFamily( IpFamily::IPv6 );
bool result2 = _tryListen( new Connection( *addrInfo ), maxClients );
addrInfo -> setIpFamily( IpFamily::IPv4 );
bool result1 = _tryListen( new Connection( *addrInfo ), maxClients );
return result2 || result1;
} else {
return _tryListen( new Connection( *addrInfo ), maxClients );
}
return false;
}
bool Server::_tryListen( Connection * socket, int maxClients ) {
if ( this -> mSocketVector.getSize() >= FD_SETSIZE ) {
warn( "getaddrinfo returned more addresses than we could use.\n" );
return false;
}
if ( socket -> listen( maxClients ) ) {
this -> mSocketVector.push( socket );
return true;
}
delete socket;
return false;
}
bool Server::close() {
if ( !this -> mIsBinded ) return false;
for ( unsigned int i = 0; i < this -> mSocketVector.getSize(); i++ ) {
this -> mSocketVector[i] -> close();
delete this -> mSocketVector[i];
}
this -> mSocketVector.clear();
this -> mIsBinded = false;
return true;
}
bool Server::accept( Connection * clientSocket ) {
if ( getNumConnections() == 1 )
return this -> mSocketVector[0] -> accept( clientSocket );
Connection * selectedSocket = _select();
if ( selectedSocket )
return selectedSocket -> accept( clientSocket );
else
return false;
}
void Server::updateFdSet() {
this -> mFdSet.fd_count = ( u_int ) Math::min<Vector<Connection * >::Size>( this -> mSocketVector.getSize(), FD_SETSIZE );
for ( unsigned int i = 0; i < this -> mFdSet.fd_count; i++ ) {
this -> mFdSet.fd_array[i] = this -> mSocketVector[i] -> getSocket();
}
}
typename Vector<Connection * >::Size Server::getNumConnections() const {
return this -> mSocketVector.getSize();
}
size_t Server::getMaximumNbConnections() {
return FD_SETSIZE;
}
Connection * Server::_select() {
if ( this -> mFdSet.fd_count > 0 ) {
memcpy( &this -> mFdSetTmp, &this -> mFdSet, sizeof( fd_set ) );
if ( ::select( ( int ) getNumConnections(), &this -> mFdSetTmp, 0, 0, 0 ) == SOCKET_ERROR ) {
error( "Select failed !" );
return NULL;
}
while ( this -> mFdSetTmp.fd_count > 0 ) {
this -> mFdSetTmp.fd_count--;
SOCKET activeSocket = this -> mFdSetTmp.fd_array[this -> mFdSetTmp.fd_count];
for ( auto i = this -> mSocketVector.begin(); i != this -> mSocketVector.end(); i++ ) {
if ( ( *i ) -> getSocket() == activeSocket ) {
return ( *i );
}
}
}
}
return NULL;
}
int Server::receive( char * buffer, int maxSize, Address * addressFrom ) {
Connection * selectedSocket = _select();
if ( selectedSocket )
return selectedSocket -> receive( buffer, maxSize, addressFrom );
else
return 0;
}
}
| 26.47907 | 214 | 0.645003 | Oriode |
cba2f72867e76b7d13524f329bd0189683090056 | 7,325 | cpp | C++ | src/lib/analysis/advisor/Inspection.cpp | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | null | null | null | src/lib/analysis/advisor/Inspection.cpp | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | null | null | null | src/lib/analysis/advisor/Inspection.cpp | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | 2 | 2021-11-30T18:24:10.000Z | 2022-02-13T18:13:17.000Z |
//************************* System Include Files ****************************
#include <fstream>
#include <iostream>
#include <iomanip>
#include <climits>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <typeinfo>
#include <unordered_map>
#include <sys/stat.h>
//*************************** User Include Files ****************************
#include <include/gcc-attr.h>
#include <include/gpu-metric-names.h>
#include <include/uint.h>
#include "GPUOptimizer.hpp"
#include "Inspection.hpp"
using std::string;
#include <lib/prof/CCT-Tree.hpp>
#include <lib/prof/Metric-ADesc.hpp>
#include <lib/prof/Metric-Mgr.hpp>
#include <lib/prof/Struct-Tree.hpp>
#include <lib/profxml/PGMReader.hpp>
#include <lib/profxml/XercesUtil.hpp>
#include <lib/prof-lean/hpcrun-metric.h>
#include <lib/binutils/LM.hpp>
#include <lib/binutils/VMAInterval.hpp>
#include <lib/xml/xml.hpp>
#include <lib/support/IOUtil.hpp>
#include <lib/support/Logic.hpp>
#include <lib/support/StrUtil.hpp>
#include <lib/support/diagnostics.h>
#include <iostream>
#include <vector>
namespace Analysis {
std::stack<Prof::Struct::Alien *>
InspectionFormatter::getInlineStack(Prof::Struct::ACodeNode *stmt) {
std::stack<Prof::Struct::Alien *> st;
Prof::Struct::Alien *alien = stmt->ancestorAlien();
while (alien) {
st.push(alien);
auto *stmt = alien->parent();
if (stmt) {
alien = stmt->ancestorAlien();
} else {
break;
}
};
return st;
}
std::string SimpleInspectionFormatter::formatInlineStack(
std::stack<Prof::Struct::Alien *> &inline_stack) {
std::stringstream ss;
ss << "Inline stack: " << std::endl;
while (inline_stack.empty() == false) {
auto *inline_struct = inline_stack.top();
inline_stack.pop();
// Current inline stack line mapping information is not accurate
//ss << "Line " << inline_struct->begLine() <<
ss << " " << inline_struct->fileName() << std::endl;
}
return ss.str();
}
std::string SimpleInspectionFormatter::format(const Inspection &inspection) {
std::stringstream ss;
std::string sep = "------------------------------------------"
"--------------------------------------------------";
std::string indent = " ";
// Debug
//std::cout << "Apply " << inspection.optimization << " optimization," << std::endl;
// Overview
ss << indent << "Apply " << inspection.optimization << " optimization,";
ss << std::fixed << std::setprecision(3);
ss << " ratio " << inspection.ratios.back() * 100 << "%,";
ss << " estimate speedup " << inspection.speedups.back() << "x" << std::endl;
indent += " ";
ss << indent << inspection.hint << std::endl;
// Specific suggestion
if (inspection.active_warp_count.first != -1) {
ss << indent << "Adjust #active_warps: " << inspection.active_warp_count.first;
if (inspection.active_warp_count.second != -1) {
ss << " to " << inspection.active_warp_count.second;
}
ss << std::endl;
}
if (inspection.thread_count.first != -1) {
ss << indent << "Adjust #threads: " << inspection.thread_count.first;
if (inspection.thread_count.second != -1) {
ss << " to " << inspection.thread_count.second;
}
ss << std::endl;
}
if (inspection.block_count.first != -1) {
ss << indent << "Adjust #blocks: " << inspection.block_count.first;
if (inspection.block_count.second != -1) {
ss << " to " << inspection.block_count.second;
}
ss << std::endl;
}
if (inspection.reg_count.first != -1) {
ss << indent << "Adjust #regs: " << inspection.reg_count.first;
if (inspection.reg_count.second != -1) {
ss << " to " << inspection.reg_count.second;
}
ss << std::endl;
}
// Hot regions
for (size_t index = 0; index < inspection.regions.size(); ++index) {
auto ®ion_blame = inspection.regions[index];
auto ratio = 0.0;
auto speedup = 0.0;
if (inspection.loop) {
ratio = inspection.ratios[index];
speedup = inspection.speedups[index];
} else {
auto metric = inspection.stall ? region_blame.stall_blame : region_blame.lat_blame;
ratio = metric / inspection.total;
}
ss << indent << index + 1 << ". Hot " << region_blame.blame_name << " code, ratio " <<
ratio * 100 << "%, ";
if (speedup != 0.0) {
ss << "speedup " << speedup << "x";
}
if (inspection.density.size() != 0.0) {
ss << ", density " << inspection.density[index] * 100 << "%";
}
ss << std::endl;
std::vector<InstructionBlame> inst_blames;
if (inspection.hotspots.size() != 0) {
inst_blames = inspection.hotspots[index];
} else {
inst_blames.push_back(region_blame);
}
std::string prefix = " ";
for (auto &inst_blame : inst_blames) {
auto inst_blame_ratio = 0.0;
auto inst_blame_metric = inspection.stall ? inst_blame.stall_blame : inst_blame.lat_blame;
inst_blame_ratio = inst_blame_metric / inspection.total;
ss << indent + prefix << "Hot " << inst_blame.blame_name << " code, ratio " <<
inst_blame_ratio * 100 << "%, distance " << inst_blame.distance << std::endl;
auto *src_struct = inst_blame.src_struct;
auto *dst_struct = inst_blame.dst_struct;
auto *src_func = src_struct->ancestorProc();
auto *dst_func = dst_struct->ancestorProc();
auto src_vma = inst_blame.src_inst == NULL ? src_struct->vmaSet().begin()->beg() :
(inst_blame.src_inst)->pc - src_func->vmaSet().begin()->beg();
auto dst_vma = inst_blame.dst_inst == NULL ? dst_struct->vmaSet().begin()->beg() :
(inst_blame.dst_inst)->pc - dst_func->vmaSet().begin()->beg();
// Print inline call stack
std::stack<Prof::Struct::Alien *> src_inline_stack =
getInlineStack(src_struct);
std::stack<Prof::Struct::Alien *> dst_inline_stack =
getInlineStack(dst_struct);
auto *src_file = src_struct->ancestorFile();
ss << indent + prefix + prefix << "From " << src_func->name() << " at " << src_file->name() << ":" <<
src_file->begLine() << std::endl;
if (src_inline_stack.empty() == false) {
ss << indent + prefix + prefix + prefix << formatInlineStack(src_inline_stack);
}
ss << indent + prefix + prefix + prefix << std::hex << "0x" << src_vma << std::dec << " at " <<
"Line " << src_struct->begLine();
if (inspection.loop) {
auto *loop = src_struct->ancestorLoop();
if (loop) {
ss << " in Loop at Line " << loop->begLine();
}
}
ss << std::endl;
auto *dst_file = dst_struct->ancestorFile();
ss << indent + prefix + prefix << "To " << dst_func->name() << " at " << dst_file->name() << ":" <<
dst_file->begLine() << std::endl;
if (dst_inline_stack.empty() == false) {
ss << indent + prefix + prefix + prefix << formatInlineStack(dst_inline_stack);
}
ss << indent + prefix + prefix + prefix << std::hex << "0x" << dst_vma << std::dec << " at " <<
"Line " << dst_struct->begLine() << std::endl;
}
if (inspection.callback != NULL) {
ss << inspection.callback(region_blame) << std::endl;
}
ss << std::endl;
}
ss << sep << std::endl;
return ss.str();
};
} // namespace Analysis
| 29.53629 | 107 | 0.593857 | GVProf |
cba8b71b091fd3417882130d65401db0d0994a62 | 7,784 | cpp | C++ | DisPG/DisPG/util.cpp | hackflame/PgResarch | 5a2bb5433aae617cf9737bd1efc1643886f6bcf5 | [
"MIT"
] | 228 | 2015-01-04T01:28:05.000Z | 2022-03-28T01:37:46.000Z | DisPG/DisPG/util.cpp | zgz715/PgResarch | 5a2bb5433aae617cf9737bd1efc1643886f6bcf5 | [
"MIT"
] | 3 | 2015-07-24T04:34:05.000Z | 2018-10-07T06:08:57.000Z | DisPG/DisPG/util.cpp | zgz715/PgResarch | 5a2bb5433aae617cf9737bd1efc1643886f6bcf5 | [
"MIT"
] | 111 | 2015-01-05T19:32:10.000Z | 2021-11-24T03:07:26.000Z | //
// This module implements auxiliary functions. These functions do not have
// prefixes on their names.
//
#include "stdafx.h"
#include "util.h"
////////////////////////////////////////////////////////////////////////////////
//
// macro utilities
//
////////////////////////////////////////////////////////////////////////////////
//
// constants and macros
//
// Tag used for memory allocation APIs
static const LONG UTIL_TAG = 'util';
// Change it to 0xCC when you want to install break points for patched code
static const UCHAR UTIL_HOOK_ENTRY_CODE = 0x90;
// Page table related
#ifndef PXE_BASE
#define PXE_BASE 0xFFFFF6FB7DBED000UI64
#define PPE_BASE 0xFFFFF6FB7DA00000UI64
#define PDE_BASE 0xFFFFF6FB40000000UI64
#define PTE_BASE 0xFFFFF68000000000UI64
#define PTI_SHIFT 12
#define PDI_SHIFT 21
#define PPI_SHIFT 30
#define PXI_SHIFT 39
#define PXE_PER_PAGE 512
#define PXI_MASK (PXE_PER_PAGE - 1)
#endif
////////////////////////////////////////////////////////////////////////////////
//
// types
//
////////////////////////////////////////////////////////////////////////////////
//
// prototypes
//
////////////////////////////////////////////////////////////////////////////////
//
// variables
//
////////////////////////////////////////////////////////////////////////////////
//
// implementations
//
// Disable the write protection
EXTERN_C
void Ia32DisableWriteProtect()
{
CR0_REG Cr0 = {};
Cr0.All = __readcr0();
Cr0.Field.WP = FALSE;
__writecr0(Cr0.All);
}
// Enable the write protection
EXTERN_C
void Ia32EnableWriteProtect()
{
CR0_REG Cr0 = {};
Cr0.All = __readcr0();
Cr0.Field.WP = TRUE;
__writecr0(Cr0.All);
}
// Return an address of PXE
EXTERN_C
PHARDWARE_PTE MiAddressToPxe(
__in void* Address)
{
ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PXI_SHIFT - 3);
Offset &= (PXI_MASK << 3);
return reinterpret_cast<PHARDWARE_PTE>(PXE_BASE + Offset);
}
// Return an address of PPE
EXTERN_C
PHARDWARE_PTE MiAddressToPpe(
__in void* Address)
{
ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PPI_SHIFT - 3);
Offset &= (0x3FFFF << 3);
return reinterpret_cast<PHARDWARE_PTE>(PPE_BASE + Offset);
}
// Return an address of PDE
EXTERN_C
PHARDWARE_PTE MiAddressToPde(
__in void* Address)
{
ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PDI_SHIFT - 3);
Offset &= (0x7FFFFFF << 3);
return reinterpret_cast<PHARDWARE_PTE>(PDE_BASE + Offset);
}
// Return an address of PTE
EXTERN_C
PHARDWARE_PTE MiAddressToPte(
__in void* Address)
{
ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PTI_SHIFT - 3);
Offset &= (0xFFFFFFFFFULL << 3);
return reinterpret_cast<PHARDWARE_PTE>(PTE_BASE + Offset);
}
// Return a number of processors
EXTERN_C
ULONG KeQueryActiveProcessorCountCompatible(
__out_opt PKAFFINITY ActiveProcessors)
{
#if (NTDDI_VERSION >= NTDDI_VISTA)
return KeQueryActiveProcessorCount(ActiveProcessors);
#else
ULONG numberOfProcessors = 0;
KAFFINITY affinity = KeQueryActiveProcessors();
if (ActiveProcessors)
{
*ActiveProcessors = affinity;
}
for (; affinity; affinity >>= 1)
{
if (affinity & 1)
{
numberOfProcessors++;
}
}
return numberOfProcessors;
#endif
}
// Execute a given callback routine on all processors in DPC_LEVEL. Returns
// STATUS_SUCCESS when all callback returned STATUS_SUCCESS as well. When
// one of callbacks returns anything but STATUS_SUCCESS, this function stops
// to call remaining callbacks and returns the value.
EXTERN_C
NTSTATUS ForEachProcessors(
__in NTSTATUS(*CallbackRoutine)(void*),
__in_opt void* Context)
{
const auto numberOfProcessors =
KeQueryActiveProcessorCountCompatible(nullptr);
for (ULONG processorNumber = 0; processorNumber < numberOfProcessors;
processorNumber++)
{
// Switch the current processor
KeSetSystemAffinityThread(static_cast<KAFFINITY>(1ull << processorNumber));
const auto oldIrql = KeRaiseIrqlToDpcLevel();
// Execute callback
const auto status = CallbackRoutine(Context);
KeLowerIrql(oldIrql);
KeRevertToUserAffinityThread();
if (!NT_SUCCESS(status))
{
return status;
}
}
return STATUS_SUCCESS;
}
// Random memory version strstr()
EXTERN_C
void* MemMem(
__in const void* SearchBase,
__in SIZE_T SearchSize,
__in const void* Pattern,
__in SIZE_T PatternSize)
{
ASSERT(SearchBase);
ASSERT(SearchSize);
ASSERT(Pattern);
ASSERT(PatternSize);
if (PatternSize > SearchSize)
{
return nullptr;
}
auto searchBase = static_cast<const char*>(SearchBase);
for (size_t i = 0; i <= SearchSize - PatternSize; i++)
{
if (!memcmp(Pattern, &searchBase[i], PatternSize))
{
return const_cast<char*>(&searchBase[i]);
}
}
return nullptr;
}
// Replaces placeholder (0xffffffffffffffff) in AsmHandler with a given
// ReturnAddress. AsmHandler does not has to be writable. Race condition between
// multiple processors should be taken care of by a programmer it exists; this
// function does not care about it.
EXTERN_C
void FixupAsmCode(
__in ULONG_PTR ReturnAddress,
__in ULONG_PTR AsmHandler,
__in ULONG_PTR AsmHandlerEnd)
{
ASSERT(AsmHandlerEnd > AsmHandler);
SIZE_T asmHandlerSize = AsmHandlerEnd - AsmHandler;
ULONG_PTR pattern = 0xffffffffffffffff;
auto returnAddr = MemMem(reinterpret_cast<void*>(AsmHandler),
asmHandlerSize, &pattern, sizeof(pattern));
ASSERT(returnAddr);
PatchReal(returnAddr, &ReturnAddress, sizeof(ReturnAddress));
}
// Install a hook on PatchAddress by overwriting original code with JMP code
// that transfer execution to JumpDestination without modifying any registers.
// PatchAddress does not has to be writable. Race condition between multiple
// processors should be taken care of by a programmer it exists; this function
// does not care about it.
EXTERN_C
void InstallJump(
__in ULONG_PTR PatchAddress,
__in ULONG_PTR JumpDestination)
{
// Code used to overwrite PatchAddress
UCHAR patchCode[] =
{
UTIL_HOOK_ENTRY_CODE, // nop or int 3
0x50, // push rax
0x48, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // mov rax, 0ffffffffffffffffh
0x48, 0x87, 0x04, 0x24, // xchg rax, [rsp]
0xC3, // ret
};
C_ASSERT(sizeof(patchCode) == 17);
// Replace placeholder (0xffffffffffffffff) located at offset 4 of patchCode
// with JumpDestination
*reinterpret_cast<ULONG_PTR*>(patchCode + 4) = JumpDestination;
// And install patch
PatchReal(reinterpret_cast<void*>(PatchAddress), patchCode,
sizeof(patchCode));
}
// Overwrites PatchAddr with PatchCode with disabling write protection and
// raising IRQL in order to avoid race condition on this processor.
EXTERN_C
void PatchReal(
__in void* PatchAddr,
__in const void* PatchCode,
__in SIZE_T PatchBytes)
{
const auto oldIrql = KeRaiseIrqlToDpcLevel();
Ia32DisableWriteProtect();
memcpy(PatchAddr, PatchCode, PatchBytes);
__writecr3(__readcr3());
KeLowerIrql(oldIrql);
Ia32EnableWriteProtect();
}
// Returns true if the address is canonical address
EXTERN_C
bool IsCanonicalAddress(
__in ULONG_PTR Address)
{
return (
(Address & 0xFFFF000000000000) == 0xFFFF000000000000 ||
(Address & 0xFFFF000000000000) == 0);
}
| 26.297297 | 98 | 0.635149 | hackflame |
cba99ee10cd3b28bf2f9e3779c82bcf228c13d5e | 13,472 | cpp | C++ | src/vidhrdw/lwings.cpp | pierrelouys/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | 1 | 2021-01-25T20:16:33.000Z | 2021-01-25T20:16:33.000Z | src/vidhrdw/lwings.cpp | pierrelouys/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | 1 | 2021-05-24T20:28:35.000Z | 2021-05-25T14:44:54.000Z | src/vidhrdw/lwings.cpp | PSP-Archive/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | null | null | null | /***************************************************************************
vidhrdw.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "osdepend.h"
unsigned char *lwings_backgroundram;
unsigned char *lwings_backgroundattribram;
int lwings_backgroundram_size;
unsigned char *lwings_scrolly;
unsigned char *lwings_scrollx;
unsigned char *trojan_scrolly;
unsigned char *trojan_scrollx;
unsigned char *trojan_bk_scrolly;
unsigned char *trojan_bk_scrollx;
static unsigned char *dirtybuffer2;
static unsigned char *dirtybuffer4;
static struct osd_bitmap *tmpbitmap2;
static struct osd_bitmap *tmpbitmap3;
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
int lwings_vh_start(void)
{
int i;
if (generic_vh_start() != 0)
return 1;
if ((dirtybuffer2 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0)
{
generic_vh_stop();
return 1;
}
fast_memset(dirtybuffer2,1,lwings_backgroundram_size);
if ((dirtybuffer4 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0)
{
generic_vh_stop();
return 1;
}
fast_memset(dirtybuffer4,1,lwings_backgroundram_size);
/* the background area is twice as tall as the screen */
if ((tmpbitmap2 = osd_new_bitmap(2*Machine->drv->screen_width,
2*Machine->drv->screen_height,Machine->scrbitmap->depth)) == 0)
{
gp2x_free(dirtybuffer2);
generic_vh_stop();
return 1;
}
#define COLORTABLE_START(gfxn,color_code) Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + \
color_code * Machine->gfx[gfxn]->color_granularity
#define GFX_COLOR_CODES(gfxn) Machine->gfx[gfxn]->total_colors
#define GFX_ELEM_COLORS(gfxn) Machine->gfx[gfxn]->color_granularity
fast_memset(palette_used_colors,PALETTE_COLOR_UNUSED,Machine->drv->total_colors * sizeof(unsigned char));
/* chars */
for (i = 0;i < GFX_COLOR_CODES(0);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(0,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(0));
palette_used_colors[COLORTABLE_START(0,i) + GFX_ELEM_COLORS(0)-1] = PALETTE_COLOR_TRANSPARENT;
}
/* bg tiles */
for (i = 0;i < GFX_COLOR_CODES(1);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(1,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(1));
}
/* sprites */
for (i = 0;i < GFX_COLOR_CODES(2);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(2,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(2));
}
return 0;
}
/***************************************************************************
Stop the video hardware emulation.
***************************************************************************/
void lwings_vh_stop(void)
{
osd_free_bitmap(tmpbitmap2);
gp2x_free(dirtybuffer2);
gp2x_free(dirtybuffer4);
generic_vh_stop();
}
void lwings_background_w(int offset,int data)
{
if (lwings_backgroundram[offset] != data)
{
lwings_backgroundram[offset] = data;
dirtybuffer2[offset] = 1;
}
}
void lwings_backgroundattrib_w(int offset,int data)
{
if (lwings_backgroundattribram[offset] != data)
{
lwings_backgroundattribram[offset] = data;
dirtybuffer4[offset] = 1;
}
}
/***************************************************************************
Draw the game screen in the given osd_bitmap.
Do NOT call osd_update_display() from this function, it will be called by
the main emulation engine.
***************************************************************************/
void lwings_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh)
{
int offs;
if (palette_recalc())
{
fast_memset(dirtybuffer2,1,lwings_backgroundram_size);
fast_memset(dirtybuffer4,1,lwings_backgroundram_size);
}
for (offs = lwings_backgroundram_size - 1;offs >= 0;offs--)
{
int sx,sy, colour;
/*
Tiles
=====
0x80 Tile code MSB
0x40 Tile code MSB
0x20 Tile code MSB
0x10 X flip
0x08 Y flip
0x04 Colour
0x02 Colour
0x01 Colour
*/
colour=(lwings_backgroundattribram[offs] & 0x07);
if (dirtybuffer2[offs] != 0 || dirtybuffer4[offs] != 0)
{
int code;
dirtybuffer2[offs] = dirtybuffer4[offs] = 0;
sx = offs / 32;
sy = offs % 32;
code=lwings_backgroundram[offs];
code+=((((int)lwings_backgroundattribram[offs]) &0xe0) <<3);
drawgfx(tmpbitmap2,Machine->gfx[1],
code,
colour,
(lwings_backgroundattribram[offs] & 0x08),
(lwings_backgroundattribram[offs] & 0x10),
16 * sx,16 * sy,
0,TRANSPARENCY_NONE,0);
}
}
/* copy the background graphics */
{
int scrollx,scrolly;
scrolly = -(lwings_scrollx[0] + 256 * lwings_scrollx[1]);
scrollx = -(lwings_scrolly[0] + 256 * lwings_scrolly[1]);
copyscrollbitmap(bitmap,tmpbitmap2,1,&scrollx,1,&scrolly,&Machine->drv->visible_area,TRANSPARENCY_NONE,0);
}
/* Draw the sprites. */
for (offs = spriteram_size - 4;offs >= 0;offs -= 4)
{
int code,sx,sy;
/*
Sprites
=======
0x80 Sprite code MSB
0x40 Sprite code MSB
0x20 Colour
0x10 Colour
0x08 Colour
0x04 Y flip
0x02 X flip
0x01 X MSB
*/
sx = spriteram[offs + 3] - 0x100 * (spriteram[offs + 1] & 0x01);
sy = spriteram[offs + 2];
if (sx && sy)
{
code = spriteram[offs];
code += (spriteram[offs + 1] & 0xc0) << 2;
drawgfx(bitmap,Machine->gfx[2],
code,
(spriteram[offs + 1] & 0x38) >> 3,
spriteram[offs + 1] & 0x02,spriteram[offs + 1] & 0x04,
sx,sy,
&Machine->drv->visible_area,TRANSPARENCY_PEN,15);
}
}
/* draw the frontmost playfield. They are characters, but draw them as sprites */
for (offs = videoram_size - 1;offs >= 0;offs--)
{
int sx,sy;
sx = offs % 32;
sy = offs / 32;
drawgfx(bitmap,Machine->gfx[0],
videoram[offs] + 4 * (colorram[offs] & 0xc0),
colorram[offs] & 0x0f,
colorram[offs] & 0x10,colorram[offs] & 0x20,
8*sx,8*sy,
&Machine->drv->visible_area,TRANSPARENCY_PEN,3);
}
}
/*
TROJAN
======
Differences:
Tile attribute (no y flip, possible priority)
Sprite attribute (more sprites)
Extra scroll layer
*/
int trojan_vh_start(void)
{
int i;
if (generic_vh_start() != 0)
return 1;
if ((dirtybuffer2 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0)
{
generic_vh_stop();
return 1;
}
fast_memset(dirtybuffer2,1,lwings_backgroundram_size);
if ((dirtybuffer4 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0)
{
generic_vh_stop();
return 1;
}
fast_memset(dirtybuffer4,1,lwings_backgroundram_size);
if ((tmpbitmap3 = osd_new_bitmap(16*0x12,
16*0x12,Machine->scrbitmap->depth)) == 0)
{
gp2x_free(dirtybuffer4);
gp2x_free(dirtybuffer2);
generic_vh_stop();
return 1;
}
#define COLORTABLE_START(gfxn,color_code) Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + \
color_code * Machine->gfx[gfxn]->color_granularity
#define GFX_COLOR_CODES(gfxn) Machine->gfx[gfxn]->total_colors
#define GFX_ELEM_COLORS(gfxn) Machine->gfx[gfxn]->color_granularity
fast_memset(palette_used_colors,PALETTE_COLOR_UNUSED,Machine->drv->total_colors * sizeof(unsigned char));
/* chars */
for (i = 0;i < GFX_COLOR_CODES(0);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(0,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(0));
palette_used_colors[COLORTABLE_START(0,i) + GFX_ELEM_COLORS(0)-1] = PALETTE_COLOR_TRANSPARENT;
}
/* fg tiles */
for (i = 0;i < GFX_COLOR_CODES(1);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(1,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(1));
}
/* sprites */
for (i = 0;i < GFX_COLOR_CODES(2);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(2,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(2));
}
/* bg tiles */
for (i = 0;i < GFX_COLOR_CODES(3);i++)
{
fast_memset(&palette_used_colors[COLORTABLE_START(3,i)],
PALETTE_COLOR_USED,
GFX_ELEM_COLORS(3));
}
return 0;
}
void trojan_vh_stop(void)
{
osd_free_bitmap(tmpbitmap3);
gp2x_free(dirtybuffer4);
gp2x_free(dirtybuffer2);
generic_vh_stop();
}
void trojan_render_foreground( struct osd_bitmap *bitmap, int scrollx, int scrolly, int priority )
{
int scrlx = -(scrollx&0x0f);
int scrly = -(scrolly&0x0f);
int sx, sy;
int offsy = (scrolly >> 4)-1;
int offsx = (scrollx >> 4)*32-32;
int transp0,transp1;
if( priority ){
transp0 = 0xFFFF; /* draw nothing (all pens transparent) */
transp1 = 0xF00F; /* high priority half of tile */
}
else {
transp0 = 1; /* TRANSPARENCY_PEN, color 0 */
transp1 = 0x0FF0; /* low priority half of tile */
}
for (sx=0; sx<0x12; sx++)
{
offsx&=0x03ff;
for (sy=0; sy<0x12; sy++)
{
/*
Tiles
0x80 Tile code MSB
0x40 Tile code MSB
0x20 Tile code MSB
0x10 X flip
0x08 Priority ????
0x04 Colour
0x02 Colour
0x01 Colour
*/
int offset = offsx+( (sy+offsy)&0x1f );
int attribute = lwings_backgroundattribram[offset];
drawgfx(bitmap,Machine->gfx[1],
lwings_backgroundram[offset] + ((attribute &0xe0) <<3),
attribute & 0x07,
attribute & 0x10,
0,
16 * sx+scrlx-16,16 * sy+scrly-16, &Machine->drv->visible_area, TRANSPARENCY_PENS,(attribute & 0x08)?transp1:transp0 );
}
offsx+=0x20;
}
}
void trojan_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh)
{
int offs, sx, sy, scrollx, scrolly;
int offsy, offsx;
if (palette_recalc())
{
fast_memset(dirtybuffer2,1,lwings_backgroundram_size);
fast_memset(dirtybuffer4,1,lwings_backgroundram_size);
}
{
static int oldoffsy=0xffff;
static int oldoffsx=0xffff;
scrollx = (trojan_bk_scrollx[0]);
scrolly = (trojan_bk_scrolly[0]);
offsy = 0x20 * scrolly;
offsx = (scrollx >> 4);
scrollx = -(scrollx & 0x0f);
scrolly = 0; /* Y doesn't scroll ??? */
if (oldoffsy != offsy || oldoffsx != offsx)
{
unsigned char *p=Machine->memory_region[4];
oldoffsx=offsx;
oldoffsy=offsy;
for (sy=0; sy < 0x11; sy++)
{
offsy &= 0x7fff;
for (sx=0; sx<0x11; sx++)
{
int code, colour;
int offset=offsy + ((2*(offsx+sx)) & 0x3f);
code = *(p+offset);
colour = *(p+offset+1);
drawgfx(tmpbitmap3, Machine->gfx[3],
code+((colour&0x80)<<1),
colour & 0x07,
colour&0x10,
colour&0x20,
16 * sx,16 * sy,
0,TRANSPARENCY_NONE,0);
}
offsy += 0x800;
}
}
copyscrollbitmap(bitmap,tmpbitmap3,1,&scrollx,1,&scrolly,&Machine->drv->visible_area,TRANSPARENCY_NONE,0);
}
scrollx = (trojan_scrollx[0] + 256 * trojan_scrollx[1]);
scrolly = (trojan_scrolly[0] + 256 * trojan_scrolly[1]);
trojan_render_foreground( bitmap, scrollx, scrolly, 0 );
/* Draw the sprites. */
for (offs = spriteram_size - 4;offs >= 0;offs -= 4)
{
int code,attrib;
/*
Sprites
=======
0x80 Sprite code MSB
0x40 Sprite code MSB
0x20 Sprite code MSB
0x10 X flip
0x08 Colour
0x04 colour
0x02 colour
0x01 X MSB
*/
attrib = spriteram[offs + 1];
sx = spriteram[offs + 3] - 0x100 * (attrib & 0x01);
sy = spriteram[offs + 2];
if (sx && sy)
{
code = spriteram[offs];
if( attrib&0x40 ) code += 256;
if( attrib&0x80 ) code += 256*4;
if( attrib&0x20 ) code += 256*2;
drawgfx(bitmap,Machine->gfx[2],
code,
(attrib & 0x0e) >> 1,
attrib & 0x10,1,
sx,sy,
&Machine->drv->visible_area,TRANSPARENCY_PEN,15);
}
}
trojan_render_foreground( bitmap, scrollx, scrolly, 1 );
/* draw the frontmost playfield. They are characters, but draw them as sprites */
for (offs = videoram_size - 1;offs >= 0;offs--)
{
sx = offs % 32;
sy = offs / 32;
drawgfx(bitmap,Machine->gfx[0],
videoram[offs] + 4 * (colorram[offs] & 0xc0),
colorram[offs] & 0x0f,
colorram[offs] & 0x10,colorram[offs] & 0x20,
8*sx,8*sy,
&Machine->drv->visible_area,TRANSPARENCY_PEN,3);
}
}
| 26.261209 | 151 | 0.565395 | pierrelouys |
cbabf1d4201f5f4cf4de68d0c2674cd26e9bab64 | 1,051 | hpp | C++ | coding/csv_reader.hpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | 13 | 2019-09-16T17:45:31.000Z | 2022-01-29T15:51:52.000Z | coding/csv_reader.hpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | 37 | 2019-10-04T00:55:46.000Z | 2019-12-27T15:13:19.000Z | coding/csv_reader.hpp | maksimandrianov/omim | cbc5a80d09d585afbda01e471887f63b9d3ab0c2 | [
"Apache-2.0"
] | 13 | 2019-10-02T15:03:58.000Z | 2020-12-28T13:06:22.000Z | #pragma once
#include "coding/reader.hpp"
#include <functional>
#include <sstream>
#include <string>
#include <vector>
namespace coding
{
class CSVReader
{
public:
struct Params
{
Params() {}
bool m_readHeader = false;
char m_delimiter = ',';
};
CSVReader() = default;
using Row = std::vector<std::string>;
using File = std::vector<Row>;
using RowByRowCallback = std::function<void(Row && row)>;
using FullFileCallback = std::function<void(File && file)>;
void Read(std::istringstream & stream, RowByRowCallback const & fn,
Params const & params = {}) const;
void Read(std::istringstream & stream, FullFileCallback const & fn,
Params const & params = {}) const;
template <typename Callback>
void Read(Reader const & reader, Callback const & fn, Params const & params = {}) const
{
std::string str(static_cast<size_t>(reader.Size()), '\0');
reader.Read(0, &str[0], str.size());
std::istringstream stream(str);
Read(stream, fn, params);
}
};
} // namespace coding
| 23.355556 | 89 | 0.649857 | Barysman |
cbb10b61d84d535032a741a75db84a9e87bee635 | 437 | cpp | C++ | tests/operation/out.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | 17 | 2018-08-22T06:48:20.000Z | 2022-02-22T21:20:09.000Z | tests/operation/out.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | tests/operation/out.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | // Copyright 2020 Oleksandr Bacherikov.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <actl/operation/scalar/all.hpp>
#include "test.hpp"
TEST_CASE("output parameter")
{
int res{};
CHECK(6 == (ac::out{res} = ac::add(2, 4)).x);
CHECK(6 == res);
ac::out{res} = ac::add(2, res);
CHECK(8 == res);
}
| 24.277778 | 60 | 0.638444 | AlCash07 |
cbb29f4bd651a9f40f5f1ea413809f830d86f536 | 1,354 | hpp | C++ | include/Color.hpp | Crazy-Piri/Img2CPC | af748085b3e1d1d63697aedb12d7021236b1e8ff | [
"MIT"
] | 6 | 2015-08-10T13:10:19.000Z | 2020-06-06T08:15:34.000Z | include/Color.hpp | Crazy-Piri/Img2CPC | af748085b3e1d1d63697aedb12d7021236b1e8ff | [
"MIT"
] | 5 | 2016-04-10T13:20:01.000Z | 2021-06-23T06:36:32.000Z | include/Color.hpp | Crazy-Piri/Img2CPC | af748085b3e1d1d63697aedb12d7021236b1e8ff | [
"MIT"
] | 4 | 2015-08-15T16:45:32.000Z | 2020-08-15T19:57:54.000Z | #ifndef _COLOR_H_
#define _COLOR_H_
#include <cmath>
#include <iostream>
using namespace std;
class Color {
public:
unsigned char A;
unsigned char R;
unsigned char G;
unsigned char B;
Color(): Color(0, 0,0,0) {};
Color(const unsigned char r,
const unsigned char g,
const unsigned b): A(255), R(r),G(g),B(b) { };
Color(const unsigned char a,
const unsigned char r,
const unsigned char g,
const unsigned b): A(a), R(r),G(g),B(b) { };
unsigned int toInt() { return (this->A << 24) | (this->R << 16) | (this->G << 8) | (this->B); };
double Distance(const Color &other) { return Color::Distance(*this, other); };
void Dump() {
cout << "{ a: " << (unsigned int) this->A ;
cout << ", r: " << (unsigned int) this->R ;
cout << ", g: " << (unsigned int) this->G ;
cout << ", b: " << (unsigned int) this->B ;
cout << " }";
};
static double Distance (const Color &col1, const Color &col2) {
if(col1.A == 0 && col2.A == 0) {
return 0.0;
}
else {
int deltaA = col1.A - col2.A;
int deltaR = col1.R - col2.R;
int deltaG = col1.G - col2.G;
int deltaB = col1.B - col2.B;
return sqrt(
(double)(
(deltaA * deltaA) +
(deltaR * deltaR) +
(deltaG * deltaG) +
(deltaB * deltaB)
));
}
};
};
#endif | 22.949153 | 97 | 0.532496 | Crazy-Piri |
cbbb8834b87999c28a2ba680766a7a7a6f1e3e9b | 98 | hpp | C++ | include/test_data.hpp | andrewkatson/json | c11ca0a075f2d4bb5b5b613b5319597cf15db11e | [
"MIT"
] | null | null | null | include/test_data.hpp | andrewkatson/json | c11ca0a075f2d4bb5b5b613b5319597cf15db11e | [
"MIT"
] | null | null | null | include/test_data.hpp | andrewkatson/json | c11ca0a075f2d4bb5b5b613b5319597cf15db11e | [
"MIT"
] | null | null | null | #define TEST_DATA_DIRECTORY "/home/andrew/DenariiServices/Core/external/json/json/json_test_data"
| 49 | 97 | 0.857143 | andrewkatson |
cbbd73f6660cba7352885432152cbafb50c0ad6d | 7,593 | cpp | C++ | src/qt/qtwebkit/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011 Apple Inc. All Rights Reserved.
* Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(INSPECTOR_SERVER)
#include "WebInspectorServer.h"
#include "HTTPRequest.h"
#include "WebInspectorProxy.h"
#include "WebSocketServerConnection.h"
using namespace WebCore;
namespace WebKit {
static unsigned pageIdFromRequestPath(const String& path)
{
size_t start = path.reverseFind('/');
String numberString = path.substring(start + 1, path.length() - start - 1);
bool ok = false;
unsigned number = numberString.toUIntStrict(&ok);
if (!ok)
return 0;
return number;
}
WebInspectorServer& WebInspectorServer::shared()
{
static WebInspectorServer& server = *new WebInspectorServer;
return server;
}
WebInspectorServer::WebInspectorServer()
: WebSocketServer(this)
, m_nextAvailablePageId(1)
{
}
WebInspectorServer::~WebInspectorServer()
{
// Close any remaining open connections.
HashMap<unsigned, WebSocketServerConnection*>::iterator end = m_connectionMap.end();
for (HashMap<unsigned, WebSocketServerConnection*>::iterator it = m_connectionMap.begin(); it != end; ++it) {
WebSocketServerConnection* connection = it->value;
WebInspectorProxy* client = m_clientMap.get(connection->identifier());
closeConnection(client, connection);
}
}
int WebInspectorServer::registerPage(WebInspectorProxy* client)
{
#ifndef ASSERT_DISABLED
ClientMap::iterator end = m_clientMap.end();
for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it)
ASSERT(it->value != client);
#endif
int pageId = m_nextAvailablePageId++;
m_clientMap.set(pageId, client);
return pageId;
}
void WebInspectorServer::unregisterPage(int pageId)
{
m_clientMap.remove(pageId);
WebSocketServerConnection* connection = m_connectionMap.get(pageId);
if (connection)
closeConnection(0, connection);
}
#if !PLATFORM(QT)
String WebInspectorServer::inspectorUrlForPageID(int)
{
return String();
}
#endif
void WebInspectorServer::sendMessageOverConnection(unsigned pageIdForConnection, const String& message)
{
WebSocketServerConnection* connection = m_connectionMap.get(pageIdForConnection);
if (connection)
connection->sendWebSocketMessage(message);
}
void WebInspectorServer::didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection* connection, PassRefPtr<HTTPRequest> request)
{
// request->url() contains only the path extracted from the HTTP request line
// and KURL is poor at parsing incomplete URLs, so extract the interesting parts manually.
String path = request->url();
size_t pathEnd = path.find('?');
if (pathEnd == notFound)
pathEnd = path.find('#');
if (pathEnd != notFound)
path.truncate(pathEnd);
// Ask for the complete payload in memory for the sake of simplicity. A more efficient way would be
// to ask for header data and then let the platform abstraction write the payload straight on the connection.
Vector<char> body;
String contentType;
bool found = platformResourceForPath(path, body, contentType);
HTTPHeaderMap headerFields;
headerFields.set("Connection", "close");
headerFields.set("Content-Length", String::number(body.size()));
if (found)
headerFields.set("Content-Type", contentType);
// Send when ready and close immediately afterwards.
connection->sendHTTPResponseHeader(found ? 200 : 404, found ? "OK" : "Not Found", headerFields);
connection->sendRawData(body.data(), body.size());
connection->shutdownAfterSendOrNow();
}
bool WebInspectorServer::didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerConnection*, PassRefPtr<HTTPRequest> request)
{
String path = request->url();
// NOTE: Keep this in sync with WebCore/inspector/front-end/inspector.js.
DEFINE_STATIC_LOCAL(const String, inspectorWebSocketConnectionPathPrefix, (ASCIILiteral("/devtools/page/")));
// Unknown path requested.
if (!path.startsWith(inspectorWebSocketConnectionPathPrefix))
return false;
int pageId = pageIdFromRequestPath(path);
// Invalid page id.
if (!pageId)
return false;
// There is no client for that page id.
WebInspectorProxy* client = m_clientMap.get(pageId);
if (!client)
return false;
return true;
}
void WebInspectorServer::didEstablishWebSocketConnection(WebSocketServerConnection* connection, PassRefPtr<HTTPRequest> request)
{
String path = request->url();
unsigned pageId = pageIdFromRequestPath(path);
ASSERT(pageId);
// Ignore connections to a page that already have a remote inspector connected.
if (m_connectionMap.contains(pageId)) {
LOG_ERROR("A remote inspector connection already exist for page ID %d. Ignoring.", pageId);
connection->shutdownNow();
return;
}
// Map the pageId to the connection in case we need to close the connection locally.
connection->setIdentifier(pageId);
m_connectionMap.set(pageId, connection);
WebInspectorProxy* client = m_clientMap.get(pageId);
client->remoteFrontendConnected();
}
void WebInspectorServer::didReceiveWebSocketMessage(WebSocketServerConnection* connection, const String& message)
{
// Dispatch incoming remote message locally.
unsigned pageId = connection->identifier();
ASSERT(pageId);
WebInspectorProxy* client = m_clientMap.get(pageId);
client->dispatchMessageFromRemoteFrontend(message);
}
void WebInspectorServer::didCloseWebSocketConnection(WebSocketServerConnection* connection)
{
// Connection has already shut down.
unsigned pageId = connection->identifier();
if (!pageId)
return;
// The socket closing means the remote side has caused the close.
WebInspectorProxy* client = m_clientMap.get(pageId);
closeConnection(client, connection);
}
void WebInspectorServer::closeConnection(WebInspectorProxy* client, WebSocketServerConnection* connection)
{
// Local side cleanup.
if (client)
client->remoteFrontendDisconnected();
// Remote side cleanup.
m_connectionMap.remove(connection->identifier());
connection->setIdentifier(0);
connection->shutdownNow();
}
}
#endif // ENABLE(INSPECTOR_SERVER)
| 34.357466 | 130 | 0.73278 | viewdy |
cbbdd34d39b29ff1d27cddb7447d9b48f7f2bc57 | 2,514 | cpp | C++ | src/common/file_watcher.cpp | eBay/block-aggregator | d16d10718f42da42ef8df8048eecb25df0d55f4a | [
"Apache-2.0"
] | 18 | 2021-12-16T11:31:07.000Z | 2022-03-29T06:44:02.000Z | src/common/file_watcher.cpp | eBay/block-aggregator | d16d10718f42da42ef8df8048eecb25df0d55f4a | [
"Apache-2.0"
] | 1 | 2022-02-03T19:42:35.000Z | 2022-02-03T19:42:35.000Z | src/common/file_watcher.cpp | eBay/block-aggregator | d16d10718f42da42ef8df8048eecb25df0d55f4a | [
"Apache-2.0"
] | 3 | 2021-12-18T13:54:13.000Z | 2022-02-15T17:03:42.000Z | /************************************************************************
Copyright 2021, eBay, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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 "file_watcher.hpp"
#include "common/logging.hpp"
#include <boost/algorithm/string.hpp>
FileWatcher::FileWatcher(const std::vector<std::string>& paths, FileWatcher::listener_t&& updater) :
paths{paths},
listener{std::move(updater)},
monitor{fsw::monitor_factory::create_monitor(fsw_monitor_type::system_default_monitor_type, paths,
process_events, this)} {
if (listener == nullptr) {
LOG(FATAL) << "FileWatcher listener should not be null";
}
}
FileWatcher::~FileWatcher() {
if (is_running()) {
stop();
}
}
void FileWatcher::start() {
LOG(INFO) << "File watcher start on [" << boost::algorithm::join(paths, ", ") << "]";
if (daemon != nullptr) {
stop();
}
daemon = std::make_unique<boost::thread>([this]() {
#ifdef __APPLE__
pthread_setname_np("FileWatcher");
#else
pthread_setname_np(pthread_self(), "FileWatcher");
#endif /* __APPLE__ */
LOG(INFO) << "File watcher thread started";
monitor->start();
LOG(INFO) << "File watcher thread exited";
});
}
void FileWatcher::stop() {
try {
LOG(INFO) << "File watcher stopping";
monitor->stop();
if (daemon != nullptr && daemon->joinable()) {
daemon->join();
}
LOG(INFO) << "File watcher stopped";
} catch (...) {
LOG(FATAL) << "Failed to stop file watcher due to: " << boost::current_exception_diagnostic_information();
}
}
bool FileWatcher::is_running() { return monitor->is_running(); }
void FileWatcher::process_events(const std::vector<fsw::event>& events, void* context) {
auto* self = reinterpret_cast<FileWatcher*>(context);
if (self->listener) {
self->listener(events);
}
}
| 33.078947 | 114 | 0.604614 | eBay |
cbc32c5849ee5e01e91f5fa2d22eb64b8e2928e8 | 698 | hpp | C++ | src/arithmetic/bucket.hpp | r3c/tesca | e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8 | [
"MIT"
] | 2 | 2016-06-01T14:44:21.000Z | 2018-05-04T11:55:02.000Z | src/arithmetic/bucket.hpp | r3c/tesca | e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8 | [
"MIT"
] | 1 | 2021-03-21T11:36:18.000Z | 2021-03-21T14:49:17.000Z | src/arithmetic/bucket.hpp | r3c/tesca | e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8 | [
"MIT"
] | null | null | null |
#ifndef __TESCA_ARITHMETIC_BUCKET_HPP
#define __TESCA_ARITHMETIC_BUCKET_HPP
#include "../../lib/glay/src/glay.hpp"
#include "../storage/variant.hpp"
namespace Tesca
{
namespace Arithmetic
{
class Bucket
{
public:
Bucket (Bucket const&);
Bucket (Glay::Int32u);
~Bucket ();
Bucket& operator = (Bucket const&);
Storage::Variant const& operator [] (Glay::Int32u) const;
Glay::Int32u getLength () const;
Glay::Int16s compare (Bucket const&) const;
Bucket& keep ();
void set (Glay::Int32u, Storage::Variant const&);
private:
Storage::Variant* buffer;
Glay::Int32u length;
};
bool operator < (Bucket const&, Bucket const&);
}
}
#endif
| 18.368421 | 61 | 0.657593 | r3c |
cbc4f3e3c8059ad79718c963c6790252082636c6 | 3,602 | cc | C++ | tensorflow/core/transforms/utils/eval_utils_test.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 3 | 2022-03-09T01:39:56.000Z | 2022-03-30T23:17:58.000Z | tensorflow/core/transforms/utils/eval_utils_test.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | null | null | null | tensorflow/core/transforms/utils/eval_utils_test.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 1 | 2022-03-22T00:45:15.000Z | 2022-03-22T00:45:15.000Z | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/transforms/utils/eval_utils.h"
#include <memory>
#include "llvm/ADT/SmallVector.h"
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/Parser/Parser.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/ir/dialect.h"
#include "tensorflow/core/ir/ops.h"
#include "tensorflow/core/platform/test.h"
namespace mlir {
namespace tfg {
TEST(EvalUtilsTest, EvaluateOperation) {
const char *const code = R"mlir(
tfg.func @test() -> (tensor<2x2xi32>) {
%Const_0, %ctl_0 = Const name("c0") {dtype = i32, value = dense<1> : tensor<2x2xi32>} : () -> (tensor<2x2xi32>)
%Const_1, %ctl_2 = Const name("c1") {dtype = i32, value = dense<2> : tensor<2x2xi32>} : () -> (tensor<2x2xi32>)
%Add, %ctl_7 = Add(%Const_0, %Const_1) name("add") {T = i32} : (tensor<2x2xi32>, tensor<2x2xi32>) -> (tensor<2x2xi32>)
return (%Const_1) : tensor<2x2xi32>
}
)mlir";
MLIRContext context;
context.getOrLoadDialect<tfg::TFGraphDialect>();
OwningOpRef<ModuleOp> module =
mlir::parseSourceString<mlir::ModuleOp>(code, &context);
ASSERT_TRUE(module);
GraphFuncOp func = module->lookupSymbol<GraphFuncOp>("test");
ASSERT_TRUE(func);
auto iter = func.body().begin()->begin();
Operation *const_0 = &*iter++;
Operation *const_1 = &*iter++;
Operation *add = &*iter++;
auto cpu_device = std::make_unique<util::SimpleDevice>();
auto resource_mgr = std::make_unique<tensorflow::ResourceMgr>();
llvm::SmallVector<Attribute> result;
EXPECT_TRUE(succeeded(util::EvaluateOperation(
cpu_device.get(), resource_mgr.get(), const_0,
{const_0->getAttrOfType<ElementsAttr>("value")}, result)));
ASSERT_EQ(result.size(), 1);
ASSERT_TRUE(result[0].isa<ElementsAttr>());
EXPECT_EQ(result[0].cast<ElementsAttr>().getValues<int>()[0], 1);
result.clear();
EXPECT_TRUE(succeeded(util::EvaluateOperation(
cpu_device.get(), resource_mgr.get(), const_1,
{const_1->getAttrOfType<ElementsAttr>("value")}, result)));
ASSERT_EQ(result.size(), 1);
ASSERT_TRUE(result[0].isa<ElementsAttr>());
EXPECT_EQ(result[0].cast<ElementsAttr>().getValues<int>()[0], 2);
result.clear();
EXPECT_TRUE(succeeded(
util::EvaluateOperation(cpu_device.get(), resource_mgr.get(), add,
{const_0->getAttrOfType<ElementsAttr>("value"),
const_1->getAttrOfType<ElementsAttr>("value")},
result)));
ASSERT_EQ(result.size(), 1);
ASSERT_TRUE(result[0].isa<ElementsAttr>());
EXPECT_EQ(result[0].cast<ElementsAttr>().getValues<int>()[0], 3);
}
} // namespace tfg
} // namespace mlir
| 37.520833 | 124 | 0.673792 | TheRakeshPurohit |
cbc55c23aabd6be2d881a9136e18c06b287f1909 | 2,484 | cpp | C++ | win8.1/test/readme.cpp | panopticoncentral/jsrt-wrappers | 9e6352240a00ff622bbf0726f1fba363977313b9 | [
"Apache-2.0"
] | 12 | 2015-08-17T12:59:12.000Z | 2021-10-10T02:54:40.000Z | win8.1/test/readme.cpp | panopticoncentral/jsrt-wrappers | 9e6352240a00ff622bbf0726f1fba363977313b9 | [
"Apache-2.0"
] | null | null | null | win8.1/test/readme.cpp | panopticoncentral/jsrt-wrappers | 9e6352240a00ff622bbf0726f1fba363977313b9 | [
"Apache-2.0"
] | 5 | 2019-03-08T04:13:44.000Z | 2019-12-17T09:51:09.000Z | // Copyright 2013 Paul Vick
//
// 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 "stdafx.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace jsrtwrapperstest
{
TEST_CLASS(readme)
{
public:
static double add(const jsrt::call_info &info, double a, double b)
{
return a + b;
}
MY_TEST_METHOD(samples, "Test readme samples.")
{
jsrt::runtime runtime = jsrt::runtime::create();
jsrt::context context = runtime.create_context();
{
jsrt::context::scope scope(context);
jsrt::pinned<jsrt::object> pinned_obj = jsrt::object::create();
jsrt::object obj = jsrt::object::create();
obj.set_property(jsrt::property_id::create(L"boolProperty"), true);
bool bool_value = obj.get_property<bool>(jsrt::property_id::create(L"boolProperty"));
obj.set_property(jsrt::property_id::create(L"stringProperty"), L"foo");
jsrt::array<double> darray = jsrt::array<double>::create(1);
darray[0] = 10;
darray[1] = 20;
auto f = (jsrt::function<double, double, double>)jsrt::context::evaluate(L"function f(a, b) { return a + b; }; f;");
double a = f(jsrt::context::undefined(), 1, 2);
auto nf = jsrt::function<double, double, double>::create(add);
jsrt::context::global().set_property(jsrt::property_id::create(L"add"), nf);
jsrt::context::run(L"add(1, 2)");
auto bf = jsrt::bound_function<jsrt::value, double, double, double>(
jsrt::context::undefined(),
(jsrt::function<double, double, double>)jsrt::context::evaluate(L"function f(a, b) { return a + b; }; f;"));
double ba = bf(1, 2);
}
runtime.dispose();
}
};
} | 40.064516 | 132 | 0.5938 | panopticoncentral |
cbc5aad420f0548a1937734403c34d8bf29369ce | 4,555 | cpp | C++ | console/src/boost_1_78_0/libs/filesystem/test/issues/reparse_tag_file_placeholder.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | console/src/boost_1_78_0/libs/filesystem/test/issues/reparse_tag_file_placeholder.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | console/src/boost_1_78_0/libs/filesystem/test/issues/reparse_tag_file_placeholder.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 41 | 2015-07-08T19:18:35.000Z | 2021-01-14T16:39:56.000Z | // Boost reparse_tag_file_placeholder.cpp ---------------------------------------------------------//
// Copyright Roman Savchenko 2020
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// Library home page: http://www.boost.org/libs/filesystem
#include <iostream>
#if defined(BOOST_FILESYSTEM_HAS_MKLINK)
#include <boost/filesystem.hpp>
#include <boost/core/lightweight_test.hpp>
#include <cstddef>
#include <windows.h>
#include <winnt.h>
#ifdef _MSC_VER
#pragma comment(lib, "Advapi32.lib")
#endif
// Test correct boost::filesystem::status when reparse point ReparseTag set to IO_REPARSE_TAG_FILE_PLACEHOLDER
// https://docs.microsoft.com/en-us/windows/compatibility/placeholder-files?redirectedfrom=MSDN
#if !defined(__MINGW32__) || defined(__MINGW64__)
typedef struct _REPARSE_DATA_BUFFER
{
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union
{
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct
{
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
#endif
#ifndef IO_REPARSE_TAG_FILE_PLACEHOLDER
#define IO_REPARSE_TAG_FILE_PLACEHOLDER (0x80000015L)
#endif
#ifndef FSCTL_SET_REPARSE_POINT
#define FSCTL_SET_REPARSE_POINT (0x000900a4)
#endif
#ifndef REPARSE_DATA_BUFFER_HEADER_SIZE
#define REPARSE_DATA_BUFFER_HEADER_SIZE FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer)
#endif
bool obtain_restore_privilege()
{
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
std::cout << "OpenProcessToken() failed with: " << GetLastError() << std::endl;
return false;
}
TOKEN_PRIVILEGES tp;
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
{
CloseHandle(hToken);
std::cout << "LookupPrivilegeValue() failed with: " << GetLastError() << std::endl;
return false;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
{
CloseHandle(hToken);
std::cout << "AdjustTokenPrivileges() failed with: " << GetLastError() << std::endl;
return false;
}
CloseHandle(hToken);
return true;
}
bool create_io_reparse_file_placeholder(const wchar_t* name)
{
if (!obtain_restore_privilege())
{
return false;
}
HANDLE hHandle = CreateFileW(name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_FLAG_OPEN_REPARSE_POINT, 0);
if (hHandle == INVALID_HANDLE_VALUE)
{
std::cout << "CreateFile() failed with: " << GetLastError() << std::endl;
return false;
}
PREPARSE_DATA_BUFFER pReparse = reinterpret_cast< PREPARSE_DATA_BUFFER >(GlobalAlloc(GPTR, MAXIMUM_REPARSE_DATA_BUFFER_SIZE));
//note: IO_REPARSE_TAG_FILE_PLACEHOLDER - just to show that reparse point could be not only symlink or junction
pReparse->ReparseTag = IO_REPARSE_TAG_FILE_PLACEHOLDER;
DWORD dwLen;
bool ret = DeviceIoControl(hHandle, FSCTL_SET_REPARSE_POINT, pReparse, pReparse->ReparseDataLength + REPARSE_DATA_BUFFER_HEADER_SIZE, NULL, 0, &dwLen, NULL) != 0;
if (!ret)
{
std::cout << "DeviceIoControl() failed with: " << GetLastError() << std::endl;
}
CloseHandle(hHandle);
GlobalFree(pReparse);
return ret;
}
int main()
{
boost::filesystem::path rpt = boost::filesystem::temp_directory_path() / "reparse_point_test.txt";
BOOST_TEST(create_io_reparse_file_placeholder(rpt.native().c_str()));
BOOST_TEST(boost::filesystem::status(rpt).type() == boost::filesystem::reparse_file);
BOOST_TEST(boost::filesystem::remove(rpt));
return boost::report_errors();
}
#else // defined(BOOST_FILESYSTEM_HAS_MKLINK)
int main()
{
std::cout << "Skipping test as the target system does not support mklink." << std::endl;
return 0;
}
#endif // defined(BOOST_FILESYSTEM_HAS_MKLINK)
| 29.012739 | 166 | 0.686718 | vany152 |
cbca8f819c06a57e7b04f6b80df354673bf4ef76 | 4,051 | cpp | C++ | modules/attention_segmentation/src/LocationMap.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 17 | 2015-11-16T14:21:10.000Z | 2020-11-09T02:57:33.000Z | modules/attention_segmentation/src/LocationMap.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 35 | 2015-07-27T15:04:43.000Z | 2019-08-22T10:52:35.000Z | modules/attention_segmentation/src/LocationMap.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 18 | 2015-08-06T09:26:27.000Z | 2020-09-03T01:31:00.000Z | /**
* Copyright (C) 2012
* Ekaterina Potapova
* Automation and Control Institute
* Vienna University of Technology
* Gusshausstraße 25-29
* 1040 Vienna, Austria
* potapova(at)acin.tuwien.ac.at
*
* 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 "v4r/attention_segmentation/LocationMap.h"
namespace v4r
{
LocationSaliencyMap::LocationSaliencyMap():
BaseMap()
{
reset();
}
LocationSaliencyMap::~LocationSaliencyMap()
{
}
void LocationSaliencyMap::reset()
{
BaseMap::reset();
location = AM_CENTER;
center_point = cv::Point(0,0);
mapName = "LocationSaliencyMap";
}
void LocationSaliencyMap::print()
{
BaseMap::print();
printf("[%s]: location = %d\n",mapName.c_str(),location);
printf("[%s]: center_point = (%d,%d)\n",mapName.c_str(),center_point.x,center_point.y);
}
void LocationSaliencyMap::setLocation(int location_)
{
location = location_;
calculated = false;
printf("[INFO]: %s: location is set to: %d\n",mapName.c_str(),location);
}
void LocationSaliencyMap::setCenter(cv::Point _center_point)
{
center_point = _center_point;
calculated = false;
printf("[INFO]: %s: center_point is set to: (%d,%d)\n",mapName.c_str(),center_point.x,center_point.y);
}
int LocationSaliencyMap::checkParameters()
{
if( (width == 0) || (height == 0) )
{
printf("[ERROR]: %s: Seems like image is empty.\n",mapName.c_str());
return(AM_IMAGE);
}
if(!haveMask)
mask = cv::Mat_<uchar>::ones(height,width);
if((mask.cols != width) || (mask.rows != height))
{
mask = cv::Mat_<uchar>::ones(height,width);
}
return(AM_OK);
}
int LocationSaliencyMap::calculate()
{
calculated = false;
int rt_code = checkParameters();
if(rt_code != AM_OK)
return(rt_code);
printf("[INFO]: %s: Computation started.\n",mapName.c_str());
cv::Point center;
float a = 1;
float b = 1;
switch(location)
{
case AM_CENTER:
center = cv::Point(width/2,height/2);
break;
case AM_LEFT_CENTER:
center = cv::Point(width/4,height/2);
break;
case AM_LEFT:
center = cv::Point(width/4,height/4);
b = 0;
break;
case AM_RIGHT_CENTER:
center = cv::Point(4*width/4,height/2);
break;
case AM_RIGHT:
center = cv::Point(3*width/4,3*height/2);
b = 0;
break;
case AM_TOP_CENTER:
center = cv::Point(width/2,height/4);
break;
case AM_TOP:
center = cv::Point(width/2,height/4);
a = 0;
break;
case AM_BOTTOM_CENTER:
center = cv::Point(width/2,3*height/4);
break;
case AM_BOTTOM:
center = cv::Point(width/2,3*height/4);
a = 0;
break;
case AM_LOCATION_CUSTOM:
center = center_point;
break;
default:
center = cv::Point(width/2,height/2);
break;
}
map = cv::Mat_<float>::zeros(height,width);
for(int r = 0; r < height; ++r)
{
for(int c = 0; c < width; ++c)
{
if(mask.at<uchar>(r,c))
{
float dx = c-center.x;
dx = a*(dx/width);
float dy = r-center.y;
dy = b*(dy/height);
float value = dx*dx + dy*dy;
map.at<float>(r,c) = exp(-11*value);
}
}
}
cv::blur(map,map,cv::Size(filter_size,filter_size));
v4r::normalize(map,normalization_type);
calculated = true;
printf("[INFO]: %s: Computation succeed.\n",mapName.c_str());
return(AM_OK);
}
} //namespace v4r | 23.690058 | 104 | 0.626265 | ToMadoRe |
cbcc52e70beef2eee742e1c514a298755efe0a30 | 4,447 | cpp | C++ | final-project/repositories/High_level_synthesis_for_Image_Deblurring_Processor/2020MSOC_Final-main/deblur.cpp | bol-edu/2020-fall-ntu | 5e009875dec5a3bbcebd1b3fae327990371d1b6a | [
"MIT"
] | 7 | 2021-02-10T17:59:48.000Z | 2021-09-27T15:02:56.000Z | final-project/repositories/High_level_synthesis_for_Image_Deblurring_Processor/2020MSOC_Final-main/deblur.cpp | mediaic/MSoC-HLS | d876b6bdfe45caba63811b16b273a9723e9baf65 | [
"MIT"
] | null | null | null | final-project/repositories/High_level_synthesis_for_Image_Deblurring_Processor/2020MSOC_Final-main/deblur.cpp | mediaic/MSoC-HLS | d876b6bdfe45caba63811b16b273a9723e9baf65 | [
"MIT"
] | 1 | 2021-09-27T15:14:50.000Z | 2021-09-27T15:14:50.000Z | #include "deblur.h"
void gather_result(eita_t data_out[HEIGHT][WIDTH])
{ //data_in copy to data_out
for_y : for (int y = 0; y < HEIGHT; y++)
{
for_x : for (int x = 0; x < WIDTH; x++)
{
if(data_out[y][x]<0.0) data_out[y][x]=0.0;
}
}
}
void array_display(int k,cmpxDataIn data_out[HEIGHT][WIDTH])
{ //data_in copy to data_out
for_y : for (int y = 0; y < HEIGHT; y++)
{
for_x : for (int x = 0; x < WIDTH; x++)
{
//printf("(x,y)=(%d,%d)\n",x,y);
printf("%d th array_dispaly %f \n",k,float(data_out[y][x].real()));
printf("%d th array_dispaly %f \n",k,float(data_out[y][x].imag()));
}
}
}
void array_display_int(eita_t data_out[HEIGHT][WIDTH])
{ //data_in copy to data_out
for_y : for (int y = 0; y < HEIGHT; y++)
{
for_x : for (int x = 0; x < WIDTH; x++)
{
//printf("(x,y)=(%d,%d)\n",x,y);
//printf("%d th array_dispaly %f \n",x,float(data_out[x][y]));
}
}
}
void array_copy(eita_t data_in[HEIGHT][WIDTH],
eita_t data_out[HEIGHT][WIDTH])
{ //data_in copy to data_out
for_y : for (int y = 0; y < HEIGHT; y++)
{
for_x : for (int x = 0; x < WIDTH; x++)
{
#pragma HLS PIPELINE
data_out[y][x] = data_in[y][x] ;
//printf("(x,y)=(%d,%d)\n",x,y);
//printf("array_copy %d for reading\n",int(data_out[y][x]));
}
}
}
void array_initialize(eita_t y_1[HEIGHT][WIDTH],
eita_t y_2[HEIGHT][WIDTH],
eita_t y_3[HEIGHT][WIDTH],
eita_t y_4[HEIGHT][WIDTH],
eita_t y_5[HEIGHT][WIDTH],
eita_t y_6[HEIGHT][WIDTH],
eita_t y_7[HEIGHT][WIDTH],
eita_t img[HEIGHT][WIDTH])
//eita_t y_8[HEIGHT][WIDTH],
//eita_t y_9[HEIGHT][WIDTH])
{
for_y : for (int y = 0; y < HEIGHT; y++)
{
for_x : for (int x = 0; x < WIDTH; x++)
{
#pragma HLS PIPELINE
y_1[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_2[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_3[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_4[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_5[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_6[y][x] = img[y][x] ;
#pragma HLS PIPELINE
y_7[y][x] = img[y][x] ;
/*
#pragma HLS PIPELINE
y_8[y][x] = 0 ;
#pragma HLS PIPELINE
y_9[y][x] = 0 ;
*/
}
}
}
void cross_channel_deblur(eita_t x[HEIGHT][WIDTH],
eita_t adjChImg[HEIGHT][WIDTH],
proxGSDataIn coe_a[HEIGHT][WIDTH], //For ProxGS(FFT result)
fft_operation coe_b[HEIGHT][WIDTH]) //For ProxGS(FFT result)
{ //printf("[DEBUG] cross channel prior\n");
eita_t x_bar[HEIGHT][WIDTH],x_old[HEIGHT][WIDTH];//,x[HEIGHT][WIDTH];
eita_t y_1[HEIGHT][WIDTH],y_2[HEIGHT][WIDTH],y_3[HEIGHT][WIDTH],y_4[HEIGHT][WIDTH],y_5[HEIGHT][WIDTH],y_6[HEIGHT][WIDTH],y_7[HEIGHT][WIDTH],y_8[HEIGHT][WIDTH],y_9[HEIGHT][WIDTH];
array_copy(x,x_bar);// x_bar = img
//array_copy(Img,x); // x = img
array_initialize(y_1,y_2,y_3,y_4,y_5,y_6,y_7,adjChImg);//,y_8,y_9);// y_0 =Kx(ProxFs),initialize y_0(set flag=1 )
for_iteration: for(int k=0;k<ITERATION;k++) {
array_copy(x,x_old);//x_old=x;
my_filter_v1(x,x_bar,adjChImg,y_1,y_2,y_3,y_4,y_5,y_6,y_7);//,y_8,y_9); // ProxFS &&
ProxGS(x,coe_a,coe_b);
Relax(x,x_old,x_bar);
}
gather_result(x);
//array_copy(x,Img);
//array_display_int(x);
}
void DEBLUR(eita_t refImg_R[HEIGHT][WIDTH],
eita_t adjChImg_G[HEIGHT][WIDTH],
eita_t adjChImg_B[HEIGHT][WIDTH],
proxGSDataIn nominator_G[HEIGHT][WIDTH], //For ProxGS(FFT result)
fft_operation denominator_G[HEIGHT][WIDTH], //For ProxGS(FFT result)
proxGSDataIn nominator_B[HEIGHT][WIDTH], //For ProxGS(FFT result)
fft_operation denominator_B[HEIGHT][WIDTH]) //For ProxGS(FFT result)
{ //cross_channel_deblur( refImg_R,refImg_R,nominator_G,denominator_G);
cross_channel_deblur(adjChImg_G,refImg_R,nominator_G,denominator_G);
cross_channel_deblur(adjChImg_B,refImg_R,nominator_B,denominator_B);
}
| 33.186567 | 182 | 0.540589 | bol-edu |
cbcd0ef8bc515c65044757062273b32f0068437d | 3,018 | hpp | C++ | include/blacknot/assert.hpp | yzt/blacknot | 58f2bc4264aae8c4300159c33ac0929edf07d36c | [
"MIT"
] | 16 | 2015-03-17T11:38:58.000Z | 2019-06-07T16:59:17.000Z | include/blacknot/assert.hpp | yzt/blacknot | 58f2bc4264aae8c4300159c33ac0929edf07d36c | [
"MIT"
] | 1 | 2020-04-03T07:14:19.000Z | 2020-04-03T07:14:19.000Z | include/blacknot/assert.hpp | yzt/blacknot | 58f2bc4264aae8c4300159c33ac0929edf07d36c | [
"MIT"
] | null | null | null | //======================================================================
// This is part of Project Blacknot:
// https://github.com/yzt/blacknot
//======================================================================
#pragma once
//======================================================================
#include <blacknot/config.hpp>
#include <blacknot/macros.hpp>
//======================================================================
#define BKNT_STATIC_ASSERT(cond, msg) static_assert ((cond), msg)
#define BKNT_STATIC_ASSERT_SIZE(t, sz) static_assert (sizeof(t) == (sz), "Type " BKNT_STRINGIZE(t) " must be " BKNT_STRINGIZE(sz) " bytes.")
//----------------------------------------------------------------------
#if defined(BKNT_ENABLE_FULL_ASSERTS)
#if defined(BKNT_COMPILER_IS_VC)
#define BKNT_ASSERT(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__);}while(false)
#define BKNT_ASSERT_REPAIR(cond, ...) (::Blacknot::Assert(cond,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__))
#define BKNT_ASSERT_PTR_VALID(ptr, ...) BKNT_ASSERT(BKNT_PTR_VALID(ptr),__VA_ARGS__)
#else
#define BKNT_ASSERT(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__);}while(false)
#define BKNT_ASSERT_REPAIR(cond, ...) (::Blacknot::Assert(cond,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__))
#define BKNT_ASSERT_PTR_VALID(ptr, ...) BKNT_ASSERT(BKNT_PTR_VALID(ptr),##__VA_ARGS__)
#endif
#else
#define BKNT_ASSERT(cond, ...) /**/
#define BKNT_ASSERT_REPAIR(cond, ...) (cond)
#define BKNT_ASSERT_PTR_VALID(ptr, ...) /**/
#endif
#if defined(BKNT_COMPILER_IS_VC)
#define BKNT_ASSERT_STRONG(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__);}while(false)
#define BKNT_ASSERT_PTR_VALID_STRONG(ptr, ...) BKNT_ASSERT_STRONG(BKNT_PTR_VALID(ptr),__VA_ARGS__)
#else
#define BKNT_ASSERT_STRONG(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__);}while(false)
#define BKNT_ASSERT_PTR_VALID_STRONG(ptr, ...) BKNT_ASSERT_STRONG(BKNT_PTR_VALID(ptr),##__VA_ARGS__)
#endif
//----------------------------------------------------------------------
//======================================================================
namespace Blacknot {
//======================================================================
void DebugBreak ();
//----------------------------------------------------------------------
bool Assert (
bool cond, char const * cond_str,
char const * file, int line, char const * func,
char const * fmt = nullptr, ...
);
//----------------------------------------------------------------------
//======================================================================
} // namespace Blacknot
//======================================================================
| 46.430769 | 161 | 0.523194 | yzt |
cbd103eb5bd48dc7858554b641a4486e3b9e8e3a | 812 | cpp | C++ | 1st/unique_binary_search_trees.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/unique_binary_search_trees.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/unique_binary_search_trees.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
using std::cout;
using std::endl;
class Solution {
public:
int numTrees(int n) {
if (n <= 0)
return 0;
int *res = new int[n+1]();
res[0] = 1;
res[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
res[i] += res[j]*res[i-j-1];
}
}
int ret = res[n];
delete [] res;
return ret;
//return numTrees(1, n);
}
int numTrees(int start, int end) {
if (start >= end)
return 1;
int ret = 0;
for (int i = start; i <= end; ++i) {
ret += numTrees(start, i-1)*numTrees(i+1, end);
}
return ret;
}
};
int main(void)
{
cout << Solution().numTrees(3) << endl;
return 0;
}
| 20.3 | 59 | 0.415025 | buptlxb |
cbdafb03ab1b587da77687fd19d36207438a8f18 | 11,043 | cpp | C++ | Source/Constraint/constraint_angle.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Constraint/constraint_angle.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Constraint/constraint_angle.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2007, 2008, CerroKai Development
* 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 CerroKai Development 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 CerroKai Development ``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 CerroKai Development 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.
********************************************************************************/
/*** Included Header Files ***/
#include <Constraint/constraint_angle.h>
#include <Sketcher/sketch.h>
#include <Sketcher/sketch_line.h>
#include <Kernel/document.h>
#include <Kernel/unit_types.h>
#include <PartDesign/part_plane.h>
/***********************************************~***************************************************/
void WCConstraintAngle::GenerateMeasure(const bool &genOffsets) {
//Determine point of intersection (center) between lines
WCVector4 center;
WPFloat dummyA, dummyB;
WPUInt retVal = RayRayIntersection(this->_lineA->Begin(), this->_lineA->End() - this->_lineA->Begin(),
this->_lineB->Begin(), this->_lineB->End() - this->_lineB->Begin(),
dummyA, dummyB, center);
//Make sure the lines intersect
if (retVal != INTERSECTION_INTERSECTION) {
CLOGGER_WARN(WCLogManager::RootLogger(), "WCConstraintAngle::GenerateMeasure - Non-itersecting lines selected");
return;
}
center = this->_sketch->ReferencePlane()->TransformMatrix() * center;
//Determine first and second point
WCVector4 firstPt = this->_lineA->Base()->Evaluate(0.5);
WCVector4 secondPt = this->_lineB->Base()->Evaluate(0.5);
WPFloat offset, labelOffset;
//Don't generate the offsets
if (!genOffsets) {
offset = this->_measure->Offset();
labelOffset = this->_measure->LabelOffset();
}
//Generate offsets
else {
//Get distance from middle of lineA to center as offset
offset = center.Distance(this->_lineA->Base()->Evaluate(0.5));
labelOffset = 0.5;
}
//Determine angle between lines
WCVector4 p2p1 = firstPt - center;
WCVector4 p0p1 = secondPt - center;
p2p1.L(0.0);
p0p1.L(0.0);
WPFloat num = p2p1.DotProduct(p0p1);
WPFloat den = p2p1.Magnitude() * p0p1.Magnitude();
this->_angle = acos( num / den );
//Check to see if old measure needs to be deleted
if (this->_measure != NULL) delete this->_measure;
//Set the measure label
std::string label = this->_lineA->Document()->AngleUnit()->DisplayString(this->_angle, 4);
this->_measure = new WCConstraintMeasureAngle(this, label, center, firstPt, secondPt, true,
this->_sketch->ReferencePlane()->InverseTransformMatrix(),
this->_sketch->ReferencePlane()->TransformMatrix(),
offset, labelOffset);
}
void WCConstraintAngle::Initialize(void) {
//Generate the measure
this->GenerateMeasure(true);
//Create the angle controller
this->_controller = new WCConstraintAngleController(this);
//Make sure base is not null
if ((this->_lineA == NULL) || (this->_lineB == NULL) || (this->_controller == NULL)) {
CLOGGER_ERROR(WCLogManager::RootLogger(), "WCConstraintAngle::Initialize - NULL arc or controller.");
//throw error
return;
}
//Check feature name
if (this->_name == "") this->_name = this->_sketch->GenerateFeatureName(this);
this->_color = WCSketchFeature::ConstraintColor;
//Retain the lines
this->_lineA->Retain(*this);
this->_lineB->Retain(*this);
//Add into sketch
if (!this->_sketch->AddConstraint(this)) {
CLOGGER_ERROR(WCLogManager::RootLogger(), "WCConstraintAngle::WCConstraintAngle - Problem adding constraint to sketch.");
//Should delete base
//throw error
return;
}
//Create tree element and add into the tree (beneath the sketch features element)
WSTexture* constraintIcon = this->_document->Scene()->TextureManager()->TextureFromName("constraint32");
this->_treeElement = new WCTreeElement( this->_sketch->Document()->TreeView(), this->_name, this->_controller, constraintIcon);
this->_sketch->ConstraintsTreeElement()->AddLastChild(this->_treeElement);
//Inject constraints into sketch planner
this->InjectConstraints(this->_sketch->ConstraintPlanner());
}
/***********************************************~***************************************************/
WCConstraintAngle::WCConstraintAngle(WCSketch *sketch, const std::string &name, WCSketchLine *lineA, WCSketchLine *lineB) :
::WCSketchConstraint(sketch, name), _lineA(lineA), _lineB(lineB), _angle(0.0), _measure(NULL) {
//Initialize the measure
this->Initialize();
}
WCConstraintAngle::WCConstraintAngle(xercesc::DOMElement *element, WCSerialDictionary *dictionary) :
::WCSketchConstraint( WCSerializeableObject::ElementFromName(element,"SketchConstraint"), dictionary ),
_lineA(NULL), _lineB(NULL), _angle(0.0), _measure(NULL) {
//Make sure element if not null
if (element == NULL) return;
//Get GUID and register it
WCGUID guid = WCSerializeableObject::GetStringAttrib(element, "guid");
dictionary->InsertGUID(guid, this);
//Setup lineA
this->_lineA = (WCSketchLine*)WCSerializeableObject::GetGUIDAttrib(element, "lineA", dictionary);
//Setup lineB
this->_lineB = (WCSketchLine*)WCSerializeableObject::GetGUIDAttrib(element, "lineB", dictionary);
//Setup angle
this->_angle = WCSerializeableObject::GetFloatAttrib(element, "angle");
//Initialize the measure
this->Initialize();
}
WCConstraintAngle::~WCConstraintAngle() {
//Release the features
this->_lineA->Release(*this);
this->_lineB->Release(*this);
//Remove from the sketch
if (!this->_sketch->RemoveConstraint(this)) {
CLOGGER_ERROR(WCLogManager::RootLogger(), "WCConstraintAngle::~WCConstraintAngle - Problem removing constraint from sketch.");
}
//Check to see if old measure needs to be deleted
if (this->_measure != NULL) delete this->_measure;
}
void WCConstraintAngle::InjectConstraints(WCConstraintPlanner *planner) {
//Not yet implemented
}
bool WCConstraintAngle::DependencyCheck(WCSketchFeature *feature) {
//If feature matches either lineA or lineB return true, false otherwise
return (feature == this->_lineA) || (feature == this->_lineB);
}
void WCConstraintAngle::ReceiveNotice(WCObjectMsg msg, WCObject *sender) {
//Update measure
this->GenerateMeasure(false);
}
bool WCConstraintAngle::Regenerate(void) {
//Not yet implemented
CLOGGER_ERROR(WCLogManager::RootLogger(), "WCConstraintAngle::Regenerate - Not yet implemented.");
return false;
}
std::list<WCObject*> WCConstraintAngle::DeletionDependencies(void) {
//No deletion dependencies
return std::list<WCObject*>();
}
void WCConstraintAngle::OnSelection(const bool fromManager, std::list<WCVisualObject*> objects) {
//Set the color
this->_color.Set(WCSketchFeature::SelectedColor);
this->_measure->Text()->Color(WCSketchFeature::SelectedColor);
//Mark this as selected
this->_isSelected = true;
}
void WCConstraintAngle::OnDeselection(const bool fromManager) {
//Set the color
this->_color.Set(WCSketchFeature::ConstraintColor);
this->_measure->Text()->Color(WCSketchFeature::DefaultTextColor);
//Mark this as not selected
this->_isSelected = false;
}
void WCConstraintAngle::Render(const GLuint &defaultProg, const WCColor &color, const WPFloat &zoom) {
//Make sure is visible
if (!this->_isVisible) return;
//Check the color (see if in selection mode)
if (color == WCColor::Default()) {
//Just call measure to render
this->_measure->Render(this->_color);
}
//Not in selection mode
else {
//Call measure to render for selection
this->_measure->Render(color, true);
}
}
xercesc::DOMElement* WCConstraintAngle::Serialize(xercesc::DOMDocument *document, WCSerialDictionary *dictionary) {
//Insert self into dictionary
WCGUID guid = dictionary->InsertAddress(this);
//Create primary element for this object
XMLCh* xmlString = xercesc::XMLString::transcode("ConstraintAngle");
xercesc::DOMElement* element = document->createElement(xmlString);
xercesc::XMLString::release(&xmlString);
//Include the parent element
xercesc::DOMElement* featureElement = this->WCSketchConstraint::Serialize(document, dictionary);
element->appendChild(featureElement);
//Add GUID attribute
WCSerializeableObject::AddStringAttrib(element, "guid", guid);
//Add line A attribute
WCSerializeableObject::AddGUIDAttrib(element, "lineA", this->_lineA, dictionary);
//Add line B attribute
WCSerializeableObject::AddGUIDAttrib(element, "lineB", this->_lineB, dictionary);
//Add angle attribute
WCSerializeableObject::AddFloatAttrib(element, "angle", this->_angle);
//Return the new element
return element;
}
/***********************************************~***************************************************/
WCDrawingMode* WCConstraintAngle::ModeEdit(WCConstraintAngle *constraint) {
//Create a new editing mode
return new WCModeConstraintAngleEdit(constraint);
}
WCActionConstraintAngleCreate* WCConstraintAngle::ActionCreate(WCSketch *sketch, const std::string &constraintName,
WCSketchLine *lineA, WCSketchLine *lineB) {
//Create new action to create constraint
return new WCActionConstraintAngleCreate(sketch, constraintName, lineA, lineB);
}
WCActionConstraintAngleMove* WCConstraintAngle::ActionMove(WCConstraintAngle *constraint, const WPFloat &offset, const WPFloat &labelOffset) {
//Create new action to move the constraint
return new WCActionConstraintAngleMove(constraint, offset, labelOffset);
}
/***********************************************~***************************************************/
std::ostream& __WILDCAT_NAMESPACE__::operator<<(std::ostream& out, const WCConstraintAngle &constraint) {
std::cout << "Constraint Angle(" << &constraint << "): " << constraint._angle << std::endl;
return out;
}
/***********************************************~***************************************************/
| 37.68942 | 142 | 0.701983 | neonkingfr |
cbdb015e5e4ec0d145e6756c4930c1ecfb0a3957 | 1,931 | cpp | C++ | Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp | hakansanli/VectorWarUE4 | 042c4321f0cab9f6ea2344e98d1db38a4b1ade06 | [
"MIT"
] | null | null | null | Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp | hakansanli/VectorWarUE4 | 042c4321f0cab9f6ea2344e98d1db38a4b1ade06 | [
"MIT"
] | null | null | null | Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp | hakansanli/VectorWarUE4 | 042c4321f0cab9f6ea2344e98d1db38a4b1ade06 | [
"MIT"
] | null | null | null | #include "MovementComponent.h"
#include "ECS/Entity.h"
#include "InputReceiverComponent.h"
#include "ComponentFactory.h"
#include <math.h>
#include "BodyComponent.h"
#include "VectorWar/vectorwar.h"
void MovementComponent::Update(Entity* entity) {
auto inputReceiver=(InputReceiverComponent*)entity->GetComponent(ComponentTypes::InputReceiverComponentType);
if(inputReceiver!=nullptr){
if (inputReceiver->GetData()->input & INPUT_ROTATE_RIGHT) {
GetData()->heading = (GetData()->heading + ROTATE_INCREMENT) % 360;
} else if (inputReceiver->GetData()->input & INPUT_ROTATE_LEFT) {
GetData()->heading = (GetData()->heading - ROTATE_INCREMENT + 360) % 360;
}
if (inputReceiver->GetData()->input & INPUT_THRUST) {
GetData()->thrust = SHIP_THRUST;
} else if (inputReceiver->GetData()->input & INPUT_BREAK) {
GetData()->thrust = -SHIP_THRUST;
} else {
GetData()->thrust = 0;
}
if (GetData()->thrust) {
double dx = GetData()->thrust * ::cos(degtorad(GetData()->heading));
double dy = GetData()->thrust * ::sin(degtorad(GetData()->heading));
auto body=(BodyComponent*)entity->GetComponent(ComponentTypes::BodyComponentType);
UE_LOG(LogTemp,Warning,TEXT("dx:%f - dy:%f"));
body->GetData()->velocity.dx += dx;
body->GetData()->velocity.dy += dy;
double mag = sqrt(body->GetData()->velocity.dx * body->GetData()->velocity.dx +
body->GetData()->velocity.dy * body->GetData()->velocity.dy);
if (mag > SHIP_MAX_THRUST) {
body->GetData()->velocity.dx = (body->GetData()->velocity.dx * SHIP_MAX_THRUST) / mag;
body->GetData()->velocity.dy = (body->GetData()->velocity.dy * SHIP_MAX_THRUST) / mag;
}
}
}
}
| 37.862745 | 113 | 0.590368 | hakansanli |
cbe5463e3a4b4df6971d54efaad81d97df641544 | 499 | cpp | C++ | examples/imgui_demo/imgui_demo.cpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | 52 | 2021-11-19T09:08:30.000Z | 2022-03-28T00:53:43.000Z | examples/imgui_demo/imgui_demo.cpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | 1 | 2021-10-30T06:55:35.000Z | 2021-10-30T06:55:35.000Z | examples/imgui_demo/imgui_demo.cpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | 2 | 2021-12-15T02:10:42.000Z | 2022-01-08T17:50:25.000Z | #include "imgui_demo.hpp"
#include <hitagi/gui/gui_manager.hpp>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
using namespace hitagi;
int ImGuiDemo::Initialize() {
m_Logger = spdlog::stdout_color_mt("ImGuiDemo");
return 0;
}
void ImGuiDemo::Finalize() {
m_Logger->info("ImGuiDemo Finalize");
m_Logger = nullptr;
}
void ImGuiDemo::Tick() {
bool open = true;
g_GuiManager->DrawGui([&]() -> void {
ImGui::ShowDemoWindow(&open);
});
}
| 19.192308 | 52 | 0.669339 | L-Sun |
cbe5566c3e0bc7613787e8eceba489f88000b3dc | 8,179 | cpp | C++ | MagicianApprentice/MagicianApprentice/Player.cpp | vandalo/MagicianApprentice | d8f0419399fd6579960ad1b85028ecfc88a83e25 | [
"MIT"
] | null | null | null | MagicianApprentice/MagicianApprentice/Player.cpp | vandalo/MagicianApprentice | d8f0419399fd6579960ad1b85028ecfc88a83e25 | [
"MIT"
] | null | null | null | MagicianApprentice/MagicianApprentice/Player.cpp | vandalo/MagicianApprentice | d8f0419399fd6579960ad1b85028ecfc88a83e25 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Utils.h"
#include "Player.h"
#include "Exit.h"
#include "Room.h"
#include "Item.h"
#include "Spell.h"
#include "Monster.h"
#include <string>
#include "World.h"
Player::Player(const char* name, const char* description, Entity* parent, World* myWorld) :
Creature(name, description, parent), myWorld(myWorld)
{
type = PLAYER;
hp = 50;
maxHp = 50;
mana = 100;
lvl = 1;
shield = 0;
}
Player::~Player()
{}
bool Player::Update() {
if (shield > 0)
{
shield--;
}
return false;
}
unsigned int Player::ReciveAtack(unsigned int damage)
{
if (shield > 0)
{
if (shield > damage)
{
shield -= damage;
cout << "\nYou lose " + to_string(damage) + " shield points.";
damage = 0;
}
else
{
cout << "\nYou lose " + to_string(shield) + " shield points.";
damage -= shield;
shield = 0;
}
}
if (hp > damage)
{
hp -= damage;
}
else
{
hp = 0;
}
return damage;
}
void Player::UseSpell(const vector<string>& args)
{
Spell* spell = HaveSpellAndMana(args);
if (spell != nullptr)
{
spell->effect(this);
}
}
void Player::UpdateMana(int manaMod)
{
mana += manaMod;
}
void Player::UpdateHp(int hpMod)
{
int hpStart = hp;
hp += hpMod;
if(hp > maxHp)
{
hp = maxHp;
cout << "You healed " << hp - hpStart <<" hp.\n";
}
}
void Player::UpdateShield(int shieldPoints)
{
shield += shieldPoints;
}
void Player::Use(const vector<string>& args)
{
list<Entity*> items;
FindByTypeAndPropietary(ITEM, items, (Entity*)this);
bool find = false;
for (list<Entity*>::const_iterator it = items.begin(); it != items.cend() && find == false; ++it)
{
if (Same((*it)->name, args[1]))
{
Item* item = (Item*)(*it);
item->Use(this, args);
find = true;
}
}
if (find == false)
{
list<Entity*> itemsInRoom;
FindByTypeAndPropietary(ITEM, itemsInRoom, GetRoom());
for (list<Entity*>::const_iterator it = itemsInRoom.begin(); it != itemsInRoom.cend() && find == false; ++it)
{
if (Same((*it)->name, args[1]))
{
Item* item = (Item*)(*it);
if (item->fixed == true)
{
item->Use(this, args);
find = true;
}
}
}
}
if (find == false)
{
cout << "You don\'t have this item!\n";
}
}
void Player::UseOn(const vector<string>& args)
{
list<Entity*> items;
FindByTypeAndPropietary(ITEM, items, GetRoom());
bool find = false;
for (list<Entity*>::const_iterator it = items.begin(); it != items.cend() && find == false; ++it)
{
if (Same((*it)->name, args[3]))
{
Item* item = (Item*)(*it);
item->Use(this, args);
find = true;
}
}
if (find == false)
{
cout << "There aren't any " << args[3] << ".\n";
}
}
Spell * Player::HaveSpellAndMana(const vector<string>& args) const
{
bool haveSpell = false;
Spell* ret = nullptr;
list<Entity*> spells;
FindByTypeAndPropietary(ITEM, spells, (Entity*)this);
for (list<Entity*>::const_iterator it = spells.begin(); it != spells.cend(); ++it)
{
Item* item = (Item*)(*it);
if (item->container.size() > 0)
{
for (list<Entity*>::const_iterator it = item->container.begin(); it != item->container.cend(); ++it)
{
if ((*it)->type == SPELL)
{
Spell* spell = (Spell*)(*it);
if (Same(spell->nameSpell, args[0]))
{
haveSpell = true;
if (mana > spell->mana)
{
if (spell->cdTime <= 0)
{
ret = spell;
}
else
{
cout << "This spell is in cooldown!\nYou have to wait " << spell->cdTime << " seconds to use it again.\n";
}
}
else
{
cout << "You have not enought mana!\n";
}
}
}
}
}
}
if (haveSpell == false)
{
cout << "You don\'t know this spell yet!\n";
}
return ret;
}
void Player::Look(const vector<string>& args) const
{
if (args.size() > 1)
{
for (list<Entity*>::const_iterator it = parent->container.begin(); it != parent->container.cend(); ++it)
{
if (Same((*it)->name, args[1]))
{
if ((*it)->type == MONSTER)
{
Monster* monster = (Monster*)(*it);
monster->Look();
}
else
{
(*it)->Look();
}
return;
}
}
for (list<Entity*>::const_iterator it = container.begin(); it != container.cend(); ++it)
{
if (Same((*it)->name, args[1]))
{
(*it)->Look();
return;
}
}
if (Same(args[1], "me"))
{
cout << name << "\n";
cout << description << "\n";
Stats();
}
}
else
{
parent->Look();
}
}
void Player::Stats() const
{
int lifePercent = hp * 100 / maxHp;
//cout << "You are level " << lvl << endl;
if (lifePercent > 75)
{
cout << "You are healthy, ";
}
else if (lifePercent > 25)
{
cout << "You are hurt, ";
}
else
{
cout << "You are almost death, ";
}
cout << "you have " << hp << "/" << maxHp << " hit points" << endl;
cout << "You have " << mana << " mana points" << endl;
if (shield > 0)
{
cout << "You have a shield of " << shield << " seconds.\n";
}
}
void Player::Inventory(const vector<string>& args) const
{
list<Entity*> items;
FindByTypeAndPropietary(ITEM, items, (Entity*)this);
for (list<Entity*>::const_iterator it = items.begin(); it != items.cend(); ++it)
{
(*it)->Look();
}
}
void Player::Open(const vector<string>& args)
{
list<Entity*> exits;
FindByTypeAndPropietary(EXIT, exits, GetRoom());
for (list<Entity*>::const_iterator it = exits.begin(); it != exits.cend(); ++it)
{
Exit* exit = (Exit*)(*it);
if (exit->name == args[1] || exit->GetDestination() == args[1])
{
exit->Open(this);
}
}
}
void Player::Go(const vector<string>& args)
{
Exit* exit = GetRoom()->GetExitByName(args[1]);
if (exit == nullptr)
{
cout << "There aren't anything on " + (args[1]) + ".\n";
}
else
{
if (exit->closed == true)
{
cout << "You can't pass " + (args[1]) + " it's locked.\n";
}
else if(exit->condition != nullptr && exit->condition->type == MONSTER)
{
Monster* monster = (Monster*)exit->condition;
if (monster->IsAlive())
{
cout << "You can not go " << exit->name << ", " << monster->name << " is blocking the acces.\n";
}
else
{
ChangeParentTo(exit->GetDestinationByRoom(GetRoom()));
parent->Look();
}
}
else
{
ChangeParentTo(exit->GetDestinationByRoom(GetRoom()));
parent->Look();
}
}
}
void Player::Take(const vector<string>& args)
{
Item* item = (Item*)GetRoom()->GetItemByName(args[1]);
if (item == nullptr)
{
item = (Item*)GetItemByName(args[1]);
if (item != nullptr)
{
cout << "You already have " + item->name + ".\n";
}
else
{
cout << "There aren't any item called " + (args[1]) + ".\n";
}
}
else
{
item = (Item*)GetRoom()->GetItemByName(args[1]);
if (item == nullptr)
{
cout << "There aren't any item called " + (args[1]) + ".\n";
}
else if (item->fixed)
{
cout << "You can't take " + (args[1]) + ".\n";
}
else
{
if (item->must == nullptr)
{
item->ChangeParentTo(this);
cout << "You added the " + item->name + " to your inventory.\n";
}
else
{
if (item->must->type == ITEM)
{
list<Entity*> items;
FindByTypeAndPropietary(ITEM, items, (Entity*)this);
FindByTypeAndPropietary(SPELL, items, (Entity*)this);
bool find = false;
for (list<Entity*>::const_iterator it = items.begin(); it != items.cend(); ++it)
{
if ((*it)->name == item->must->name)
{
item->ChangeParentTo(*it);
cout << "You added " + item->name + " to your " + (*it)->name + ".\n";
find = true;
}
}
if (find != true)
{
cout << "You can't take " + (args[1]) + ".\n";
}
}
else if (item->must->type == MONSTER)
{
Monster* monster = (Monster*)item->must;
if (monster->IsAlive())
{
cout << "You can't take " + (args[1]) + ", " << monster->name <<" is protecting it.\n";
}
else
{
item->ChangeParentTo(this);
cout << "You added " + item->name + " to your inventory.\n";
}
}
}
}
}
}
void Player::CreateBookpage3() const
{
myWorld->CreateBookpage3();
}
void Player::CreateKey1() const
{
myWorld->CreateKey1();
}
void Player::CreateSecretExit() const
{
myWorld->CreateSecretExit();
}
| 19.427553 | 114 | 0.55618 | vandalo |
cbe73101f952e4043fe767d8c61dc32c7d116e4b | 6,368 | cc | C++ | ecs/src/model/DescribeSecurityGroupAttributeResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ecs/src/model/DescribeSecurityGroupAttributeResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ecs/src/model/DescribeSecurityGroupAttributeResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ecs/model/DescribeSecurityGroupAttributeResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ecs;
using namespace AlibabaCloud::Ecs::Model;
DescribeSecurityGroupAttributeResult::DescribeSecurityGroupAttributeResult() :
ServiceResult()
{}
DescribeSecurityGroupAttributeResult::DescribeSecurityGroupAttributeResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeSecurityGroupAttributeResult::~DescribeSecurityGroupAttributeResult()
{}
void DescribeSecurityGroupAttributeResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allPermissionsNode = value["Permissions"]["Permission"];
for (auto valuePermissionsPermission : allPermissionsNode)
{
Permission permissionsObject;
if(!valuePermissionsPermission["Direction"].isNull())
permissionsObject.direction = valuePermissionsPermission["Direction"].asString();
if(!valuePermissionsPermission["SourceGroupId"].isNull())
permissionsObject.sourceGroupId = valuePermissionsPermission["SourceGroupId"].asString();
if(!valuePermissionsPermission["DestGroupOwnerAccount"].isNull())
permissionsObject.destGroupOwnerAccount = valuePermissionsPermission["DestGroupOwnerAccount"].asString();
if(!valuePermissionsPermission["DestPrefixListId"].isNull())
permissionsObject.destPrefixListId = valuePermissionsPermission["DestPrefixListId"].asString();
if(!valuePermissionsPermission["DestPrefixListName"].isNull())
permissionsObject.destPrefixListName = valuePermissionsPermission["DestPrefixListName"].asString();
if(!valuePermissionsPermission["SourceCidrIp"].isNull())
permissionsObject.sourceCidrIp = valuePermissionsPermission["SourceCidrIp"].asString();
if(!valuePermissionsPermission["Ipv6DestCidrIp"].isNull())
permissionsObject.ipv6DestCidrIp = valuePermissionsPermission["Ipv6DestCidrIp"].asString();
if(!valuePermissionsPermission["CreateTime"].isNull())
permissionsObject.createTime = valuePermissionsPermission["CreateTime"].asString();
if(!valuePermissionsPermission["Ipv6SourceCidrIp"].isNull())
permissionsObject.ipv6SourceCidrIp = valuePermissionsPermission["Ipv6SourceCidrIp"].asString();
if(!valuePermissionsPermission["DestGroupId"].isNull())
permissionsObject.destGroupId = valuePermissionsPermission["DestGroupId"].asString();
if(!valuePermissionsPermission["DestCidrIp"].isNull())
permissionsObject.destCidrIp = valuePermissionsPermission["DestCidrIp"].asString();
if(!valuePermissionsPermission["IpProtocol"].isNull())
permissionsObject.ipProtocol = valuePermissionsPermission["IpProtocol"].asString();
if(!valuePermissionsPermission["Priority"].isNull())
permissionsObject.priority = valuePermissionsPermission["Priority"].asString();
if(!valuePermissionsPermission["DestGroupName"].isNull())
permissionsObject.destGroupName = valuePermissionsPermission["DestGroupName"].asString();
if(!valuePermissionsPermission["NicType"].isNull())
permissionsObject.nicType = valuePermissionsPermission["NicType"].asString();
if(!valuePermissionsPermission["Policy"].isNull())
permissionsObject.policy = valuePermissionsPermission["Policy"].asString();
if(!valuePermissionsPermission["Description"].isNull())
permissionsObject.description = valuePermissionsPermission["Description"].asString();
if(!valuePermissionsPermission["PortRange"].isNull())
permissionsObject.portRange = valuePermissionsPermission["PortRange"].asString();
if(!valuePermissionsPermission["SourcePrefixListName"].isNull())
permissionsObject.sourcePrefixListName = valuePermissionsPermission["SourcePrefixListName"].asString();
if(!valuePermissionsPermission["SourcePrefixListId"].isNull())
permissionsObject.sourcePrefixListId = valuePermissionsPermission["SourcePrefixListId"].asString();
if(!valuePermissionsPermission["SourceGroupOwnerAccount"].isNull())
permissionsObject.sourceGroupOwnerAccount = valuePermissionsPermission["SourceGroupOwnerAccount"].asString();
if(!valuePermissionsPermission["SourceGroupName"].isNull())
permissionsObject.sourceGroupName = valuePermissionsPermission["SourceGroupName"].asString();
if(!valuePermissionsPermission["SourcePortRange"].isNull())
permissionsObject.sourcePortRange = valuePermissionsPermission["SourcePortRange"].asString();
permissions_.push_back(permissionsObject);
}
if(!value["VpcId"].isNull())
vpcId_ = value["VpcId"].asString();
if(!value["InnerAccessPolicy"].isNull())
innerAccessPolicy_ = value["InnerAccessPolicy"].asString();
if(!value["Description"].isNull())
description_ = value["Description"].asString();
if(!value["SecurityGroupId"].isNull())
securityGroupId_ = value["SecurityGroupId"].asString();
if(!value["SecurityGroupName"].isNull())
securityGroupName_ = value["SecurityGroupName"].asString();
if(!value["RegionId"].isNull())
regionId_ = value["RegionId"].asString();
}
std::string DescribeSecurityGroupAttributeResult::getDescription()const
{
return description_;
}
std::string DescribeSecurityGroupAttributeResult::getVpcId()const
{
return vpcId_;
}
std::string DescribeSecurityGroupAttributeResult::getSecurityGroupName()const
{
return securityGroupName_;
}
std::string DescribeSecurityGroupAttributeResult::getSecurityGroupId()const
{
return securityGroupId_;
}
std::vector<DescribeSecurityGroupAttributeResult::Permission> DescribeSecurityGroupAttributeResult::getPermissions()const
{
return permissions_;
}
std::string DescribeSecurityGroupAttributeResult::getInnerAccessPolicy()const
{
return innerAccessPolicy_;
}
std::string DescribeSecurityGroupAttributeResult::getRegionId()const
{
return regionId_;
}
| 44.222222 | 121 | 0.798053 | aliyun |
cbe7e405bbd78e85e4a9e32be91309c95ebfe609 | 965 | cpp | C++ | HackerRank/University-Codesprint-5/Cube-loving-Numbers.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | HackerRank/University-Codesprint-5/Cube-loving-Numbers.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | HackerRank/University-Codesprint-5/Cube-loving-Numbers.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | /**
* > Author : TISparta
* > Date : 09-09-18
* > Tags : Inclusion-Exclusion Principle
* > Difficulty : 4 / 10
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int SZ = 1e6;
int t;
ll n, ans;
bool isPrime[SZ + 1];
vector <int> prime;
void sieve () {
memset(isPrime, true, sizeof isPrime);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < SZ; i++)
if (isPrime[i]) {
for (ll j = 1LL * i * i; j < SZ; j += i) isPrime[j] = false;
prime.push_back(i);
}
}
void backtrack (int id, ll a, int sign) {
int newSign = -1 * sign;
for (int i = id; i < prime.size(); i++) {
__int128_t aaa = __int128_t(a) * prime[i] * prime[i] * prime[i];
if (aaa > n) break;
ans += newSign * (n / aaa);
backtrack(i + 1, aaa, newSign);
}
}
void solve () {
cin >> n;
ans = 0;
backtrack(0, 1, -1);
cout << ans << endl;
}
int main () {
sieve();
cin >> t;
while (t--) solve();
return (0);
}
| 17.87037 | 68 | 0.53886 | TISparta |
cbebc3d40bb7e6b9c9568b642a68e529abf28cc1 | 2,765 | cpp | C++ | ehunter/genotyping/AlleleChecker.cpp | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 122 | 2017-01-06T16:19:31.000Z | 2022-03-08T00:05:50.000Z | ehunter/genotyping/AlleleChecker.cpp | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 90 | 2017-01-04T00:23:34.000Z | 2022-02-27T12:55:52.000Z | ehunter/genotyping/AlleleChecker.cpp | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 35 | 2017-03-02T13:39:58.000Z | 2022-03-30T17:34:11.000Z | //
// Expansion Hunter
// Copyright 2016-2019 Illumina, Inc.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "genotyping/AlleleChecker.hh"
#include <boost/math/special_functions/binomial.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <numeric>
namespace ehunter
{
namespace
{
double poissonLogPmf(double lambda, double count)
{
return count * log(lambda) - lambda - boost::math::lgamma(count + 1);
}
double logBeta(int a, int b) { return boost::math::lgamma(a) + boost::math::lgamma(b) - boost::math::lgamma(a + b); }
double logBinomCoef(int n, int k) { return -boost::math::log1p(n) - logBeta(n - k + 1, k + 1); }
double binomLogPmf(int n, double p, int count)
{
return logBinomCoef(n, count) + count * log(p) + (n - count) * boost::math::log1p(-p);
}
}
AlleleCheckSummary AlleleChecker::check(double haplotypeDepth, int targetAlleleCount, int otherAlleleCount) const
{
if (haplotypeDepth <= 0)
{
throw std::runtime_error("Haplotype depth must be positive");
}
if (targetAlleleCount < 0 || otherAlleleCount < 0)
{
throw std::runtime_error("Negative read counts are not allowed");
}
const int totalReadCount = targetAlleleCount + otherAlleleCount;
const double ll0 = (totalReadCount > 0) ? binomLogPmf(totalReadCount, errorRate_, targetAlleleCount) : 0;
const double ll1 = poissonLogPmf(haplotypeDepth, targetAlleleCount);
AlleleStatus status = AlleleStatus::kUncertain;
double logLikelihoodRatio = (ll1 - ll0) / log(10);
if (logLikelihoodRatio < -log10(likelihoodRatioThreshold_))
{
status = AlleleStatus::kAbsent;
}
else if (logLikelihoodRatio > log10(likelihoodRatioThreshold_))
{
status = AlleleStatus::kPresent;
}
return AlleleCheckSummary(status, logLikelihoodRatio);
}
std::ostream& operator<<(std::ostream& out, AlleleStatus status)
{
switch (status)
{
case AlleleStatus::kAbsent:
out << "Absent";
break;
case AlleleStatus::kPresent:
out << "Present";
break;
case AlleleStatus::kUncertain:
out << "Uncertain";
break;
}
return out;
}
}
| 28.214286 | 117 | 0.688608 | bw2 |
cbebd7bce4351504b038d57b0d9e7e92cb57a291 | 2,242 | hpp | C++ | src/deps/include/boost/url/rfc/query_bnf.hpp | sandmanhome/liuguang | 73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3 | [
"Apache-2.0"
] | null | null | null | src/deps/include/boost/url/rfc/query_bnf.hpp | sandmanhome/liuguang | 73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3 | [
"Apache-2.0"
] | null | null | null | src/deps/include/boost/url/rfc/query_bnf.hpp | sandmanhome/liuguang | 73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3 | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/url
//
#ifndef BOOST_URL_RFC_QUERY_BNF_HPP
#define BOOST_URL_RFC_QUERY_BNF_HPP
#include <boost/url/detail/config.hpp>
#include <boost/url/error.hpp>
#include <boost/url/pct_encoding_types.hpp>
#include <boost/url/string.hpp>
#include <boost/url/bnf/range.hpp>
#include <cstddef>
namespace boost {
namespace urls {
struct query_param
{
pct_encoded_str key;
pct_encoded_str value;
bool has_value = false;
};
/** BNF for query
@par BNF
@code
query = *( pchar / "/" / "?" )
query-params = query-param *( "&" query-param )
query-param = key [ "=" value ]
key = *qpchar
value = *( qpchar / "=" )
qpchar = unreserved
/ pct-encoded
/ "!" / "$" / "'" / "(" / ")"
/ "*" / "+" / "," / ";"
/ ":" / "@" / "/" / "?"
@endcode
@see
https://datatracker.ietf.org/doc/html/rfc3986#section-3.4
*/
struct query_bnf : bnf::range
{
using value_type =
query_param;
query_bnf()
: bnf::range(this)
{
}
BOOST_URL_DECL
static
bool
begin(
char const*& it,
char const* const end,
error_code& ec,
query_param& t) noexcept;
BOOST_URL_DECL
static
bool
increment(
char const*& it,
char const* const end,
error_code& ec,
query_param& t) noexcept;
};
/** BNF for query-part
@par BNF
@code
query-part = [ "?" query ]
query = *( pchar / "/" / "?" )
@endcode
@see
https://datatracker.ietf.org/doc/html/rfc3986#section-3.4
*/
struct query_part_bnf
{
bool has_query;
query_bnf query;
string_view query_part;
BOOST_URL_DECL
friend
bool
parse(
char const*& it,
char const* const end,
error_code& ec,
query_part_bnf& t);
};
} // urls
} // boost
#endif
| 20.198198 | 79 | 0.554862 | sandmanhome |
cbec9a7211d61a68f33d3c8e2c7cb935427d8dec | 5,014 | cpp | C++ | src/add-ons/print/drivers/pdf/source/DrawShape.cpp | deep-1/haiku | b273e9733d25babe5e6702dc1e24f3dff1ffd6dc | [
"MIT"
] | 4 | 2017-06-17T22:03:56.000Z | 2019-01-25T10:51:55.000Z | src/add-ons/print/drivers/pdf/source/DrawShape.cpp | jessicah/haiku | c337460525c39e870d31221d205a299d9cd79c6a | [
"MIT"
] | null | null | null | src/add-ons/print/drivers/pdf/source/DrawShape.cpp | jessicah/haiku | c337460525c39e870d31221d205a299d9cd79c6a | [
"MIT"
] | 1 | 2020-05-08T04:02:02.000Z | 2020-05-08T04:02:02.000Z | /*
DrawShape
Copyright (c) 2002 OpenBeOS.
Author:
Michael Pfeiffer
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 "DrawShape.h"
#include "Bezier.h"
#include "PDFLinePathBuilder.h"
#include "Log.h"
#include "Report.h"
#include "PDFWriter.h"
#ifdef CODEWARRIOR
#pragma mark [BShape drawing support routines]
#endif
// --------------------------------------------------
DrawShape::DrawShape(PDFWriter *writer, bool stroke)
: fWriter(writer)
, fStroke(stroke)
, fDrawn(false)
, fCurrentPoint(0, 0)
{
}
// --------------------------------------------------
DrawShape::~DrawShape()
{
Draw();
}
// --------------------------------------------------
// approximate length of bezier curve
float
DrawShape::BezierLength(BPoint *curve, int n) {
float len = 0.0;
if (n <= 0) return len;
BPoint start = curve[0];
for (int i = 1; i < n; i++) {
BPoint end = curve[i];
BPoint diff = start - end;
len += sqrt(diff.x * diff.x + diff.y * diff.y);
start = end;
}
return scale(len);
}
// --------------------------------------------------
int
DrawShape::BezierPoints(BPoint *curve, int n) {
float len = BezierLength(curve, n);
if (len <= kMinBezierPoints) return kMinBezierPoints;
if (len > kMaxBezierPoints) return kMaxBezierPoints;
return (int)len;
}
// --------------------------------------------------
void
DrawShape::CreateBezierPath(BPoint *curve) {
Bezier bezier(curve, 4);
const int n = BezierPoints(curve, 4)-1;
REPORT(kDebug, 0, "BezierPoints %d", n);
for (int i = 0; i <= n; i ++) {
fSubPath.AddPoint(bezier.PointAt(i / (float) n));
}
}
// --------------------------------------------------
void
DrawShape::EndSubPath()
{
PDFLinePathBuilder builder(&fSubPath, fWriter);
builder.CreateLinePath();
}
// --------------------------------------------------
status_t
DrawShape::IterateBezierTo(int32 bezierCount, BPoint *control)
{
REPORT(kDebug, 0, "BezierTo");
for (int32 i = 0; i < bezierCount; i++, control += 3) {
REPORT(kDebug, 0," (%f %f) (%f %f) (%f %f)", tx(control[0].x), ty(control[0].y), tx(control[1].x), ty(control[1].y), tx(control[2].x), ty(control[2].y));
if (TransformPath()) {
BPoint p[4] = { fCurrentPoint, control[0], control[1], control[2] };
CreateBezierPath(p);
} else {
PDF_curveto(Pdf(),
tx(control[0].x), ty(control[0].y),
tx(control[1].x), ty(control[1].y),
tx(control[2].x), ty(control[2].y));
}
fCurrentPoint = control[2];
}
return B_OK;
}
// --------------------------------------------------
status_t
DrawShape::IterateClose(void)
{
REPORT(kDebug, 0, "IterateClose %s", IsDrawing() ? (fStroke ? "stroke" : "fill") : "clip");
if (fDrawn) REPORT(kDebug, 0, ">>> IterateClose called multiple times!");
if (TransformPath())
fSubPath.Close();
else
PDF_closepath(Pdf());
Draw();
return B_OK;
}
// --------------------------------------------------
void
DrawShape::Draw()
{
if (!fDrawn) {
fDrawn = true;
if (IsDrawing()) {
if (fStroke)
fWriter->StrokeOrClip(); // strokes always
else {
fWriter->FillOrClip(); // fills always
}
} else if (TransformPath()) {
EndSubPath();
} else {
PDF_closepath(Pdf());
}
}
}
// --------------------------------------------------
status_t
DrawShape::IterateLineTo(int32 lineCount, BPoint *linePoints)
{
REPORT(kDebug, 0, "IterateLineTo %d", (int)lineCount);
BPoint *p = linePoints;
for (int32 i = 0; i < lineCount; i++) {
REPORT(kDebug, 0, "(%f, %f) ", p->x, p->y);
if (TransformPath()) {
fSubPath.AddPoint(*p);
} else {
PDF_lineto(Pdf(), tx(p->x), ty(p->y));
}
fCurrentPoint = *p;
p++;
}
return B_OK;
}
// --------------------------------------------------
status_t
DrawShape::IterateMoveTo(BPoint *point)
{
REPORT(kDebug, 0, "IterateMoveTo ");
if (!TransformPath()) {
PDF_moveto(Pdf(), tx(point->x), ty(point->y));
} else {
EndSubPath();
fSubPath.MakeEmpty();
fSubPath.AddPoint(*point);
}
REPORT(kDebug, 0, "(%f, %f)", point->x, point->y);
fCurrentPoint = *point;
return B_OK;
}
| 24.821782 | 158 | 0.594535 | deep-1 |
cbedab134d53bff3e272b7a6b088b4fe8e192f68 | 1,506 | cpp | C++ | cpp/src/exercise/e0200/e0149.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0200/e0149.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0200/e0149.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | // https://leetcode-cn.com/problems/max-points-on-a-line/
#include "extern.h"
typedef pair<int, int> pii;
class S0149 {
void gcd(pii& p) {
int l = abs(p.first), r = abs(p.second);
if (r == 0) p = make_pair(1, 0);
else if (l == 0) p = make_pair(0, 1);
else {
if (l < r) swap(l, r);
while (r != 0) {
l -= (l / r) * r;
swap(l, r);
}
if (p.first < 0) l *= -1;
p.first /= l, p.second /= l;
}
}
public:
int maxPoints(vector<vector<int>>& points) {
int ps = points.size();
if (ps == 0) return 0;
int result = 1;
map<pii, int> s;
for (int i = 0; i < ps; ++i) {
int rep_point = 1;
s.clear();
for (int j = i + 1; j < ps; ++j) {
pii k = make_pair(points[j][0] - points[i][0], points[j][1] - points[i][1]);
if (k.first == 0 && k.second == 0) rep_point += 1;
else { gcd(k); s[k] += 1; }
}
result = max(rep_point, result);
for (auto& p : s)
result = max(p.second + rep_point, result);
}
return result;
}
};
TEST(e0200, e0149) {
vector<vector<int>> points;
points = str_to_mat<int>("[[1,1],[2,2],[3,3]]");
ASSERT_EQ(S0149().maxPoints(points), 3);
points = str_to_mat<int>("[[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]");
ASSERT_EQ(S0149().maxPoints(points), 4);
}
| 29.529412 | 92 | 0.434263 | ajz34 |
cbef4911f3ffa13f77cf15b9834b2717f9982061 | 1,271 | cpp | C++ | src/critics/goal_critic.cpp | doisyg/mppic | e9cd561c5e108061bd90cf157f0f73327b21e51a | [
"MIT"
] | null | null | null | src/critics/goal_critic.cpp | doisyg/mppic | e9cd561c5e108061bd90cf157f0f73327b21e51a | [
"MIT"
] | null | null | null | src/critics/goal_critic.cpp | doisyg/mppic | e9cd561c5e108061bd90cf157f0f73327b21e51a | [
"MIT"
] | null | null | null | // Copyright 2022 FastSense, Samsung Research
#include "mppic/critics/goal_critic.hpp"
namespace mppi::critics
{
void GoalCritic::initialize()
{
auto node = parent_.lock();
auto getParam = utils::getParamGetter(node, name_);
getParam(power_, "goal_cost_power", 1);
getParam(weight_, "goal_cost_weight", 20.0);
RCLCPP_INFO(
logger_, "GoalCritic instantiated with %d power and %f weight.",
power_, weight_);
}
void GoalCritic::score(
const geometry_msgs::msg::PoseStamped & /*robot_pose*/,
const optimization::State & /*state*/,
const xt::xtensor<double, 3> & trajectories,
const xt::xtensor<double, 2> & path,
xt::xtensor<double, 1> & costs,
nav2_core::GoalChecker * /*goal_checker*/)
{
const auto goal_points = xt::view(path, -1, xt::range(0, 2));
auto trajectories_end =
xt::view(trajectories, xt::all(), -1, xt::range(0, 2));
auto dim = trajectories_end.dimension() - 1;
auto && dists_trajectories_end_to_goal =
xt::norm_l2(std::move(trajectories_end) - goal_points, {dim});
costs += xt::pow(std::move(dists_trajectories_end_to_goal) * weight_, power_);
}
} // namespace mppi::critics
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(mppi::critics::GoalCritic, mppi::critics::CriticFunction)
| 28.244444 | 80 | 0.707317 | doisyg |
cbf176038b5218527024600bf137be49963ea712 | 2,212 | cpp | C++ | Binary Tree/Diameter.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Binary Tree/Diameter.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Binary Tree/Diameter.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //Find the diameter of a tree
/*
approach 1: TC: O(n^2):
We find the left height and right height also for the possibility that
there might exist a subtree greater than the current left or right
approach 2: TC:O(n):
We find the height in the same recursive call only.
*/
#include<iostream>
using namespace std;
struct Node{
int data;
Node* right;
Node* left;
};
//creates node
Node* createNode(int data){
Node* node = new Node;
if(node){
node->left = node->right = NULL;
node->data = data;
return node;
}
return NULL;
}
//preorder traversal
void preOrderTraversal(Node* root){
if(!root)
return;
cout<<root->data<<" ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
//for finding the height of a tree
int findHeight(Node* root){
if(!root)
return 0;
return max( findHeight(root->left), findHeight(root->right)) + 1;
}
//finds the diameter using separate height calls
int findDiameter1(Node* root){
if(root == NULL)
return 0;
//find the left and right heights
int lh = findHeight(root->left);
int rh = findHeight(root->right);
//find the left and right diameters
int ld = findDiameter1(root->left);
int rd = findDiameter1(root->right);
//now decide whether the current subtree or the greatest subtree on left
//or on right should be selected
return max( lh + rh + 1, max(ld, rd) );
}
//finds the diameter
/*
We update the height in each recursive call itself using pointers to them
*/
int findDiameter2(Node* root, int* h){
if(!root )
return 0;
int lh = 0;
int rh = 0;
int ld = findDiameter2(root->left, &lh);
int rd = findDiameter2(root->right, &rh);
*h = max(lh ,rh) + 1;
return max( lh +rh + 1, max(ld,rd));
}
//finds the diameter using 2nd approach
int findDiameter2Driver(Node* root){
int h = 0;
int d = findDiameter2(root, &h);
return d;
}
main(){
/* 1
/ \
2 3
/ \
4 5
*/
Node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
preOrderTraversal(root);
cout<<endl;
cout<< findDiameter1(root);
cout<<endl;
cout<< findDiameter2Driver(root);
}
| 20.867925 | 74 | 0.657776 | susantabiswas |
cbf22d95707136e9855e8fcd66bb0aeab0f25db3 | 972 | cpp | C++ | Bit Manipulation/8divideWithoutUsingDivideOperator.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | 1 | 2021-01-18T14:51:20.000Z | 2021-01-18T14:51:20.000Z | Bit Manipulation/8divideWithoutUsingDivideOperator.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | null | null | null | Bit Manipulation/8divideWithoutUsingDivideOperator.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | null | null | null | // C++ implementation to Divide two
// integers without using multiplication,
// division and mod operator
#include <bits/stdc++.h>
using namespace std;
// Function to divide a by b and
// return floor value it
int divide(long long dividend, long long divisor) {
// Calculate sign of divisor i.e.,
// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^
(divisor < 0)) ? -1 : 1;
// remove sign of operands
dividend = abs(dividend);
divisor = abs(divisor);
// Initialize the quotient
long long quotient = 0, temp = 0;
// test down from the highest bit and
// accumulate the tentative value for
// valid bit
for (int i = 31; i >= 0; --i) {
if (temp + (divisor << i) <= dividend) {
temp += divisor << i;
quotient |= 1LL << i;
}
}
return sign * quotient;
}
// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) << "\n";
a = 43, b = -8;
cout << divide(a, b);
return 0;
}
| 19.44 | 51 | 0.641975 | Coderangshu |
cbf470a0292ce7fdd8f7703835534eb65713fff2 | 5,252 | cpp | C++ | src/stellarium.cpp | racerxdl/esp32-rotracker | db5adaae9edfaa13595c92027933afa9d8874b92 | [
"MIT"
] | null | null | null | src/stellarium.cpp | racerxdl/esp32-rotracker | db5adaae9edfaa13595c92027933afa9d8874b92 | [
"MIT"
] | null | null | null | src/stellarium.cpp | racerxdl/esp32-rotracker | db5adaae9edfaa13595c92027933afa9d8874b92 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <math.h>
#include <AsyncTCP.h>
#include <map>
#include "stellarium.h"
#include "clock.h"
#include "storage.h"
#include "steppers.h"
#include "Sideral.h"
#include "log.h"
#define TCP_SERVER_PORT 10001
AsyncServer stellariumServer(TCP_SERVER_PORT);
std::map<AsyncClient *, int> stellariumConnectedClients;
float lastAscension;
float lastDeclination;
int lastUpdateElSteps = 0;
int lastUpdateAzSteps = 0;
bool stellariumTracking = false;
void GetRADEC(float *rightAscension, float *declination) {
int elSteps = getElStepper().currentPosition();
int azSteps = getAzStepper().currentPosition();
float elAngle = deg2rad(elStepToDeg(elSteps) + GetElevationOffset());
float azAngle = deg2rad(azStepToDeg(azSteps) + GetAzimuthOffset());
AltAztoRADEC(getSideralTime(), elAngle, azAngle, rightAscension, declination);
}
void GoToRADEC(float rightAscension, float declination) {
float elAngle, azAngle;
RADECtoAltAz(getSideralTime(), rightAscension, declination, &elAngle, &azAngle);
int elSteps = elDegToStep(elAngle - GetElevationOffset());
int azSteps = azDegToStep(azAngle - GetAzimuthOffset());
//Log::println("Going to %.4f - %.4f", elAngle, azAngle);
getElStepper().moveTo(elSteps);
getAzStepper().moveTo(azSteps);
lastAscension = rightAscension;
lastDeclination = declination;
}
float stellariumGetLastAscension() {
return lastAscension;
}
float stellariumGetLastDeclination() {
return lastDeclination;
}
// TCP Server
StellariumPacket rxPacket;
void stellariumHandleData(void *arg, AsyncClient *client, void *data, size_t len) {
if (len > sizeof(StellariumPacket)) {
len = sizeof(StellariumPacket);
}
memset(&rxPacket, 0, sizeof(StellariumPacket));
memcpy(&rxPacket, data, len);
float RA = (float)rxPacket.rightAscension;
RA /= 0x80000000u;
RA *= PI;
float dec = (float)rxPacket.declination;
dec /= 0x80000000u;
dec *= PI;
dec = rad2deg(dec);
RA = rad2deg(RA) / 15;
// Serial.printf("M;Stellarium RAW: %08x %08x\r\n", packet.rightAscension, packet.declination);
// Serial.printf("M;Stellarium rxdata IP: %s - RA=%0.4f | DEC=%0.4f\r\n", client->remoteIP().toString().c_str(), RA, dec);
Serial.printf("M;Stellarium goto from IP: %s - RA=%0.4f | DEC=%0.4f\r\n", client->remoteIP().toString().c_str(), RA, dec);
if (stellariumTracking) {
stellariumTracking = false;
lastAscension = RA;
lastDeclination = dec;
}
stellariumTracking = true;
GoToRADEC(RA, dec);
}
void stellariumHandleError(void *arg, AsyncClient *client, int8_t error) {
Serial.printf("M;Stellarium error from client IP: %s - %s\r\n", client->remoteIP().toString().c_str(), client->errorToString(error));
}
void stellariumHandleDisconnect(void *arg, AsyncClient *client) {
Serial.printf("M;Stellarium disconnected. IP: %s\r\n", client->remoteIP().toString().c_str());
stellariumConnectedClients.erase(client);
stellariumTracking = false;
}
void stellariumHandleTimeout(void *arg, AsyncClient *client, uint32_t time) {
Serial.printf("M;Stellarium timeout. IP: %s\r\n", client->remoteIP().toString().c_str());
stellariumConnectedClients.erase(client);
}
void stellariumHandleNewClient(void *arg, AsyncClient *client) {
Serial.printf("M;New client on stellarium. IP: %s\r\n", client->remoteIP().toString().c_str());
client->onData(&stellariumHandleData, NULL);
client->onError(&stellariumHandleError, NULL);
client->onDisconnect(&stellariumHandleDisconnect, NULL);
client->onTimeout(&stellariumHandleTimeout, NULL);
stellariumConnectedClients[client] = 1;
}
void stellariumBroadcastTcpMessage(const StellariumPacket &packet) {
for (const std::pair<AsyncClient*,int> pair : stellariumConnectedClients) {
pair.first->write((char *)&packet, sizeof(StellariumPacket));
}
}
void stellariumDisconnectAll() {
for (const std::pair<AsyncClient*,int> pair : stellariumConnectedClients) {
pair.first->close();
}
stellariumConnectedClients.clear();
}
void initStellarium() {
initSideral(GetLatitude(), GetLongitude());
stellariumServer.onClient(&stellariumHandleNewClient, &stellariumServer);
stellariumServer.begin();
Serial.printf("M;Started Stellarium TCP Server at port %d\r\n", TCP_SERVER_PORT);
}
unsigned long lastStellariumUpdate = 0;
unsigned long lastStellariumTrack = 0;
StellariumPacket packet;
void updateStellarium() {
static float ra, dec; // Avoid alocating memory
unsigned long updateDelta = millis() - lastStellariumUpdate;
unsigned long trackDelta = millis() - lastStellariumTrack;
if (updateDelta >= 250 && !stellariumConnectedClients.empty()) {
GetRADEC(&ra, &dec);
ra = deg2rad(ra * 15);
dec = deg2rad(dec);
packet.length = sizeof(StellariumPacket);
packet.type = 0;
packet.rightAscension = static_cast<uint32_t>(floor(0.5 + ra*((static_cast<unsigned int>(0x80000000))/PI)));;
packet.declination = static_cast<int32_t>(floor(0.5 + dec*((static_cast<unsigned int>(0x80000000))/PI)));
packet.time = getEpoch();
packet.status = 0;
stellariumBroadcastTcpMessage(packet);
lastStellariumUpdate = millis();
}
if (stellariumTracking && trackDelta >= 100) {
GoToRADEC(lastAscension, lastDeclination);
lastStellariumTrack = millis();
}
} | 33.031447 | 135 | 0.728104 | racerxdl |
cbf4e39f3e27ddb133a8af29bc7c3d622ff85873 | 377 | cpp | C++ | cpp/inform.cpp | ELIFE-ASU/informjs | 2a894fe11724bcef1feda50e7a5b5ba95a36a6a7 | [
"MIT"
] | null | null | null | cpp/inform.cpp | ELIFE-ASU/informjs | 2a894fe11724bcef1feda50e7a5b5ba95a36a6a7 | [
"MIT"
] | null | null | null | cpp/inform.cpp | ELIFE-ASU/informjs | 2a894fe11724bcef1feda50e7a5b5ba95a36a6a7 | [
"MIT"
] | null | null | null | #include "./series.h"
namespace inform {
using namespace v8;
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "mutualInfo", inform::mutual_info);
NODE_SET_METHOD(exports, "activeInfo", inform::active_info);
NODE_SET_METHOD(exports, "transferEntropy", inform::transfer_entropy);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, init);
}
| 26.928571 | 78 | 0.697613 | ELIFE-ASU |
cbf57af14d6430b38abc962b5904864e14db87ea | 525 | hh | C++ | models/cad/include/env/wind_no.hh | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | null | null | null | models/cad/include/env/wind_no.hh | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | null | null | null | models/cad/include/env/wind_no.hh | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | 2 | 2021-05-05T14:59:37.000Z | 2021-06-17T03:19:45.000Z | #ifndef __wind_no_HH__
#define __wind_no_HH__
/********************************* TRICK HEADER *******************************
PURPOSE:
(constant wind model)
LIBRARY DEPENDENCY:
((../../src/env/wind_no.cpp))
*******************************************************************************/
#include "env/wind.hh"
namespace cad {
class Wind_No : public Wind {
public:
Wind_No();
virtual ~Wind_No();
virtual void set_altitude(double altitude_in_meter);
};
} // namespace cad
#endif // __wind_no__
| 21.875 | 80 | 0.493333 | cihuang123 |
cbf57bcfe413d3b3dd58c1787f50c4eae5a8ebcc | 14,503 | cpp | C++ | src/zlib/Win32app.cpp | FreeAllegiance/AllegianceDX7 | 3955756dffea8e7e31d3a55fcf6184232b792195 | [
"MIT"
] | 76 | 2015-08-18T19:18:40.000Z | 2022-01-08T12:47:22.000Z | src/zlib/Win32app.cpp | StudentAlleg/Allegiance | e91660a471eb4e57e9cea4c743ad43a82f8c7b18 | [
"MIT"
] | 37 | 2015-08-14T22:44:12.000Z | 2020-01-21T01:03:06.000Z | src/zlib/Win32app.cpp | StudentAlleg/Allegiance | e91660a471eb4e57e9cea4c743ad43a82f8c7b18 | [
"MIT"
] | 42 | 2015-08-13T23:31:35.000Z | 2022-03-17T02:20:26.000Z | #include "Win32app.h"
#include "regkey.h"
#include "SlmVer.h"
//Imago 7/10
#include <dbghelp.h>
#include <crtdbg.h>
#include "zstring.h"
#include "VersionInfo.h"
#include <ctime>
#include "zmath.h"
#include "window.h"
#include "Logger.h"
#ifndef NO_STEAM
#include "steam_api.h"
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Some assertion functions
//
//////////////////////////////////////////////////////////////////////////////
Win32App *g_papp;
// Patch for SetUnhandledExceptionFilter
const uint8_t PatchBytes[5] = { 0x33, 0xC0, 0xC2, 0x04, 0x00 };
// Original bytes at the beginning of SetUnhandledExceptionFilter
uint8_t OriginalBytes[5] = {0};
int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
char szPathName[MAX_PATH] = "";
GetModuleFileNameA(nullptr, szPathName, MAX_PATH);
const char* p1 = strrchr(szPathName, '\\');
char* p = strrchr(szPathName, '\\');
if (!p)
p = szPathName;
else
p++;
if (!p1)
p1 = "mini";
else
p1++;
ZString zApp = p1;
uint32_t dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime(&stLocalTime);
snprintf(p, szPathName + sizeof(szPathName) - p, "%s", (PCC)zApp);
ZVersionInfo vi; ZString zInfo = (LPCSTR)vi.GetFileVersionString();
char* offsetString = p + zApp.GetLength();
snprintf(offsetString, szPathName + sizeof(szPathName) - offsetString, "-%s-%04d%02d%02d%02d%02d%02d-%ld-%ld.dmp", (PCC)zInfo,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileA(szPathName, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ, nullptr, CREATE_ALWAYS, 0, nullptr);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
MINIDUMP_TYPE mdt = (MINIDUMP_TYPE)
(MiniDumpWithDataSegs |
MiniDumpWithHandleData |
MiniDumpWithThreadInfo |
MiniDumpWithUnloadedModules |
MiniDumpWithProcessThreadData);
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, mdt, &ExpParam, nullptr, nullptr);
#ifndef NO_STEAM
// BT - STEAM
SteamAPI_SetMiniDumpComment(p);
// The 0 here is a build ID, we don't set it
SteamAPI_WriteMiniDump(0, pExceptionPointers, int(rup)); // Now including build and release number in steam errors.
#endif
return EXCEPTION_EXECUTE_HANDLER;
}
//Imago 6/10
int Win32App::GenerateDump(EXCEPTION_POINTERS* pExceptionPointers)
{
return ::GenerateDump(pExceptionPointers);
}
//////////////////////////////////////////////////////////////////////////////
//
// Some assertion functions
//
//////////////////////////////////////////////////////////////////////////////
void ZAssertImpl(bool bSucceeded, const char* psz, const char* pszFile, int line, const char* pszModule)
{
if (!bSucceeded) {
//
// Just in case this was a Win32 error get the last error
//
uint32_t dwError = GetLastError();
#ifdef _MSC_VER
if (!g_papp) {
// Imago removed asm (x64) on ?/?, integrated with mini dump on 6/10
__try {
(*(int*)nullptr) = 0;
}
__except(GenerateDump(GetExceptionInformation())) {}
} else if (g_papp->OnAssert(psz, pszFile, line, pszModule)) {
g_papp->OnAssertBreak();
}
#else
::abort();
#endif
}
}
std::string GetExecutablePath() {
char pCharModulePath[MAX_PATH];
GetModuleFileName(nullptr, pCharModulePath, MAX_PATH);
std::string pathFull = std::string(pCharModulePath);
std::string pathDirectory = pathFull.substr(0, pathFull.find_last_of("\\", pathFull.size()));
return pathDirectory;
}
std::shared_ptr<SettableLogger> g_pDebugFileLogger = std::make_shared<SettableLogger>(std::make_shared<FileLogger>(GetExecutablePath() + "/debug.log", false));
std::shared_ptr<SettableLogger> g_pDebugOutputLogger = std::make_shared<SettableLogger>(std::make_shared<OutputLogger>());
ILogger* g_pDebugLogger = new MultiLogger(std::vector<std::shared_ptr<ILogger>>({
g_pDebugOutputLogger,
g_pDebugFileLogger
}));
void ZDebugOutputImpl(const char *psz)
{
g_pDebugLogger->Log(std::string(psz));
}
void retailf(const char* format, ...)
{
const size_t size = 2048; //Avalance: Changed to log longer messages. (From 512)
char bfr[size];
va_list vl;
va_start(vl, format);
_vsnprintf_s(bfr, size, (size - 1), format, vl); //Avalanche: Fix off by one error.
va_end(vl);
ZDebugOutputImpl(bfr);
}
// mmf log to file on SRVLOG define as well as _DEBUG
#ifdef _DEBUG
#define SRVLOG
#endif
#ifdef SRVLOG // mmf changed this from _DEBUG
void ZWarningImpl(bool bSucceeded, const char* psz, const char* pszFile, int line, const char* pszModule)
{
if (!bSucceeded) {
debugf("%s(%d) : ShouldBe failed: '%s'\n", pszFile, line, psz);
}
}
bool ZFailedImpl(HRESULT hr, const char* pszFile, int line, const char* pszModule)
{
bool bFailed = FAILED(hr);
ZAssertImpl(!bFailed, "Function Failed", pszFile, line, pszModule);
return bFailed;
}
bool ZSucceededImpl(HRESULT hr, const char* pszFile, int line, const char* pszModule)
{
bool bSucceeded = SUCCEEDED(hr);
ZAssertImpl(bSucceeded, "Function Failed", pszFile, line, pszModule);
return bSucceeded;
}
#ifdef _TRACE
bool g_bEnableTrace = false;
ZString g_strSpaces;
int g_indent = 0;
int g_line = 0;
void SetStrSpaces()
{
g_strSpaces =
" "
+ ZString((float)g_indent, 2, 0)
+ ZString(' ', g_indent * 2 + 1);
}
void ZTraceImpl(const char* pcc)
{
if (g_bEnableTrace) {
ZDebugOutput(ZString((float)g_line, 4, 0) + g_strSpaces + ZString(pcc) + "\n");
}
g_line++;
}
void ZEnterImpl(const char* pcc)
{
ZTraceImpl("enter " + ZString(pcc));
g_indent += 1;
SetStrSpaces();
}
void ZExitImpl(const char* pcc)
{
g_indent -= 1;
SetStrSpaces();
ZTraceImpl("exit " + ZString(pcc));
}
void ZStartTraceImpl(const char* pcc)
{
g_indent = 0;
g_line = 0;
SetStrSpaces();
ZTraceImpl(pcc);
}
#endif
void debugf(const char* format, ...)
{
const size_t size = 2048; //Avalanche: Changed to handle longer messages (from 512)
char bfr[size];
va_list vl;
va_start(vl, format);
_vsnprintf_s(bfr, size, (size - 1), format, vl); //Avalanche: Fix off by one error.
va_end(vl);
ZDebugOutputImpl(bfr);
}
void GlobalConfigureLoggers(bool bLogToOutput, bool bLogToFile)
{
g_pDebugLogger->Log("Changing logging method based on configuration");
//on startup this is logging to a generic logfile
if (bLogToFile) {
g_pDebugFileLogger->Log("Stopping file log, logging continued in timestamped log file");
g_pDebugFileLogger->SetLogger(
CreateTimestampedFileLogger(GetExecutablePath() + "/debug_")
);
}
else {
g_pDebugFileLogger->Log("Stopping file log.");
g_pDebugFileLogger->SetLogger(
NullLogger::GetInstance()
);
}
//this is enabled on startup
if (bLogToOutput == false) {
g_pDebugFileLogger->Log("Stopping output log");
g_pDebugOutputLogger->SetLogger(NullLogger::GetInstance());
}
g_pDebugLogger->Log("Logging configuration completed");
}
#endif // SRVLOG or _DEBUG
//////////////////////////////////////////////////////////////////////////////
//
// Win32 Application
//
//////////////////////////////////////////////////////////////////////////////
Win32App::Win32App()
{
g_papp = this;
}
Win32App::~Win32App()
{
}
HRESULT Win32App::Initialize(const ZString& strCommandLine)
{
return S_OK;
}
void Win32App::Terminate()
{
}
void Win32App::Exit(int value)
{
_CrtSetDbgFlag(0);
_exit(value);
}
int Win32App::OnException(uint32_t code, EXCEPTION_POINTERS* pdata)
{
GenerateDump(pdata);
return EXCEPTION_CONTINUE_SEARCH;
}
//Imago 6/10
LONG __stdcall Win32App::ExceptionHandler( EXCEPTION_POINTERS* pep )
{
GenerateDump(pep);
return EXCEPTION_EXECUTE_HANDLER;
}
#ifdef MemoryOutput
TList<ZString> g_listOutput;
#endif
void Win32App::DebugOutput(const char *psz)
{
#ifdef MemoryOutput
g_listOutput.PushFront(ZString(psz));
if (g_listOutput.GetCount() > 100) {
g_listOutput.PopEnd();
}
#else
g_pDebugLogger->Log(psz);
#endif
}
bool Win32App::OnAssert(const char* psz, const char* pszFile, int line, const char* pszModule)
{
ZDebugOutput(
ZString("assertion failed: '")
+ psz
+ "' ("
+ pszFile
+ ":"
+ ZString(line)
+ ")\n"
);
//return _CrtDbgReport(_CRT_ASSERT, pszFile, line, pszModule, psz) == 1;
return true;
}
void Win32App::OnAssertBreak()
{
#ifdef MemoryOutput
ZString str;
TList<ZString>::Iterator iter(g_listOutput);
while (!iter.End()) {
str = iter.Value() + str;
iter.Next();
}
#endif
//
// Cause an exception
//
// Imago integrated with mini dump on 6/10
#ifdef _MSC_VER
__try {
(*(int*)nullptr) = 0;
}
__except(GenerateDump(GetExceptionInformation())) {}
#else
::abort();
#endif
}
// KGJV - added for DX9 behavior - default is false. override in parent to change this
bool Win32App::IsBuildDX9()
{
return false;
}
bool Win32App::WriteMemory( uint8_t* pTarget, const uint8_t* pSource, uint32_t Size )
{
uint32_t ErrCode = 0;
// Check parameters
if( pTarget == nullptr )
{
_ASSERTE( !_T("Target address is null.") );
return false;
}
if( pSource == nullptr )
{
_ASSERTE( !_T("Source address is null.") );
return false;
}
if( Size == 0 )
{
_ASSERTE( !_T("Source size is null.") );
return false;
}
if( IsBadReadPtr( pSource, Size ) )
{
_ASSERTE( !_T("Source is unreadable.") );
return false;
}
// Modify protection attributes of the target memory page
uint32_t OldProtect = 0;
if( !VirtualProtect( pTarget, Size, PAGE_EXECUTE_READWRITE, LPDWORD(&OldProtect) ) )
{
ErrCode = GetLastError();
_ASSERTE( !_T("VirtualProtect() failed.") );
return false;
}
// Write memory
memcpy( pTarget, pSource, Size );
// Restore memory protection attributes of the target memory page
uint32_t Temp = 0;
if( !VirtualProtect( pTarget, Size, OldProtect, LPDWORD(&Temp) ) )
{
ErrCode = GetLastError();
_ASSERTE( !_T("VirtualProtect() failed.") );
return false;
}
// Success
return true;
}
bool Win32App::EnforceFilter( bool bEnforce )
{
uint32_t ErrCode = 0;
// Obtain the address of SetUnhandledExceptionFilter
HMODULE hLib = GetModuleHandle( _T("kernel32.dll") );
if( hLib == nullptr )
{
ErrCode = GetLastError();
_ASSERTE( !_T("GetModuleHandle(kernel32.dll) failed.") );
return false;
}
uint8_t* pTarget = (uint8_t*)GetProcAddress( hLib, "SetUnhandledExceptionFilter" );
if( pTarget == nullptr )
{
ErrCode = GetLastError();
_ASSERTE( !_T("GetProcAddress(SetUnhandledExceptionFilter) failed.") );
return false;
}
if( IsBadReadPtr( pTarget, sizeof(OriginalBytes) ) )
{
_ASSERTE( !_T("Target is unreadable.") );
return false;
}
if( bEnforce )
{
// Save the original contents of SetUnhandledExceptionFilter
memcpy( OriginalBytes, pTarget, sizeof(OriginalBytes) );
// Patch SetUnhandledExceptionFilter
if( !WriteMemory( pTarget, PatchBytes, sizeof(PatchBytes) ) )
return false;
}
else
{
// Restore the original behavior of SetUnhandledExceptionFilter
if( !WriteMemory( pTarget, OriginalBytes, sizeof(OriginalBytes) ) )
return false;
}
// Success
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Win Main
//
//////////////////////////////////////////////////////////////////////////////
__declspec(dllexport) int WINAPI Win32Main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
HRESULT hr;
// seed the random number generator with the current time
// (GetTickCount may be semi-predictable on server startup, so we add the
// clock time to shake things up a bit)
srand(GetTickCount() + (int)time(nullptr));
// mmf why is this done?
// shift the stack locals and the heap by a random amount.
char* pzSpacer = new char[4 * (int)random(21, 256)];
pzSpacer[0] = *(char*)_alloca(4 * (int)random(1, 256));
//Imago 6/10 // BT - STEAM - Replacing this with steam logging.
/*SetUnhandledExceptionFilter(Win32App::ExceptionHandler);
g_papp->EnforceFilter( true );
__try { */
do {
BreakOnError(hr = Window::StaticInitialize());
// BUILD_DX9 - KGJV use runtime dynamic instead at preprocessor level
if (g_papp->IsBuildDX9())
{
BreakOnError(hr = g_papp->Initialize(lpszCmdLine));
}
else
{
// Don't throw an error, if the user selects cancel it can return E_FAIL.
hr = g_papp->Initialize(lpszCmdLine);
}
// BUILD_DX9
//
// Win32App::Initialize() return S_FALSE if this is a command line app and
// we shouldn't run the message loop
//
if (SUCCEEDED(hr) && S_FALSE != hr) {
Window::MessageLoop();
}
g_papp->Terminate();
Window::StaticTerminate();
} while (false);
// BT - STEAM - Replacing this with steam logging.
/* } __except (g_papp->OnException(_exception_code(), (EXCEPTION_POINTERS*)_exception_info())){
}
delete pzSpacer;
if( !g_papp->EnforceFilter( false ) )
{
debugf("EnforceFilter(false) failed.\n");
return 0;
}*/
return 0;
}
| 24.498311 | 159 | 0.605116 | FreeAllegiance |