hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0523a9d28fa2439ada43f94402518b04e3129cc9
6,846
cpp
C++
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
null
null
null
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
1
2021-10-02T02:34:32.000Z
2021-10-02T02:34:32.000Z
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
2
2021-09-30T11:46:32.000Z
2022-01-10T17:34:10.000Z
#include "Southpole.hpp" struct Pulse : Module { enum ParamIds { TRIG_PARAM, REPEAT_PARAM, RESET_PARAM, RANGE_PARAM, DELAY_PARAM, TIME_PARAM, AMP_PARAM, // OFFSET_PARAM, SLEW_PARAM, NUM_PARAMS }; enum InputIds { TRIG_INPUT, CLOCK_INPUT, // REPEAT_INPUT, // RESET_INPUT, DELAY_INPUT, TIME_INPUT, AMP_INPUT, // OFFSET_INPUT, SLEW_INPUT, NUM_INPUTS }; enum OutputIds { CLOCK_OUTPUT, GATE_OUTPUT, EOC_OUTPUT, NUM_OUTPUTS }; enum LightIds { EOC_LIGHT, GATE_LIGHT, NUM_LIGHTS }; dsp::SchmittTrigger clock; dsp::SchmittTrigger trigger; dsp::SchmittTrigger triggerBtn; dsp::PulseGenerator clkPulse; dsp::PulseGenerator eocPulse; unsigned long delayt = 0; unsigned long gatet = 0; unsigned long clockt = 0; unsigned long clockp = 0; unsigned long delayTarget = 0; unsigned long gateTarget = 0; float level = 0; bool reset = true; bool repeat = false; bool range = false; bool gateOn = false; bool delayOn = false; float amp; float slew; static const int ndurations = 12; const float durations[ndurations] = { 1 / 256., 1 / 128., 1 / 64., 1 / 32., 1 / 16., 1 / 8., 3. / 16., 1 / 4., 1 / 3., 1 / 2., 3. / 4., .99 //,2.,3.,4. //,5.,6.,7.,8.,12.,16. }; Pulse() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(Pulse::TRIG_PARAM, 0.0, 1.0, 0., ""); configParam(Pulse::RESET_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::REPEAT_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::RANGE_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::TIME_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::DELAY_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::AMP_PARAM, 0.0, 1.0, 1.0, ""); configParam(Pulse::SLEW_PARAM, 0.0, 1.0, 0., ""); } void process(const ProcessArgs &args) override; }; void Pulse::process(const ProcessArgs &args) { bool triggered = false; reset = params[RESET_PARAM].getValue(); repeat = params[REPEAT_PARAM].getValue(); range = params[RANGE_PARAM].getValue(); if (triggerBtn.process(params[TRIG_PARAM].getValue())) { triggered = true; } if (trigger.process(inputs[TRIG_INPUT].getNormalVoltage(0.))) { triggered = true; //printf("%lu\n", gateTarget); } if (clock.process(inputs[CLOCK_INPUT].getNormalVoltage(0.))) { triggered = true; clkPulse.trigger(1e-3); clockp = clockt; clockt = 0; } float dt = 1e-3 * args.sampleRate; float sr = args.sampleRate; amp = clamp(params[AMP_PARAM].getValue() + inputs[AMP_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); slew = clamp(params[SLEW_PARAM].getValue() + inputs[SLEW_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); slew = pow(2., (1. - slew) * log2(sr)) / sr; if (range) slew *= .1; float delayTarget_ = clamp(params[DELAY_PARAM].getValue() + inputs[DELAY_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); float gateTarget_ = clamp(params[TIME_PARAM].getValue() + inputs[TIME_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); if (inputs[CLOCK_INPUT].isConnected()) { clockt++; delayTarget = clockp * durations[int((ndurations - 1) * delayTarget_)]; gateTarget = clockp * durations[int((ndurations - 1) * gateTarget_)]; if (gateTarget < dt) gateTarget = dt; } else { unsigned int r = range ? 10 : 1; delayTarget = r * delayTarget_ * sr; gateTarget = r * gateTarget_ * sr + dt; } if (triggered && (reset || !gateOn || !delayOn)) { delayt = 0; delayOn = true; gateOn = false; } if (delayOn) { if (delayt < delayTarget) { delayt++; } else { delayOn = false; gateOn = true; gatet = 0; } } if (gateOn) { if (gatet < gateTarget) { gatet++; } else { eocPulse.trigger(1e-3); gateOn = false; if (repeat) { delayt = 0; delayOn = true; } } if (level < 1.) level += slew; if (level > 1.) level = 1.; } else { if (level > 0.) level -= slew; if (level < 0.) level = 0.; } outputs[CLOCK_OUTPUT].setVoltage(10. * clkPulse.process(1.0 / args.sampleRate)); outputs[EOC_OUTPUT].value = 10. * eocPulse.process(1.0 / args.sampleRate); outputs[GATE_OUTPUT].value = clamp(10.f * level * amp, -10.f, 10.f); lights[EOC_LIGHT].setSmoothBrightness(outputs[EOC_OUTPUT].value, args.sampleTime); lights[GATE_LIGHT].setSmoothBrightness(outputs[GATE_OUTPUT].value, args.sampleTime); } struct PulseWidget : ModuleWidget { PulseWidget(Module *module) { setModule(module); box.size = Vec(15 * 4, 380); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Pulse.svg"))); const float x1 = 5.; const float x2 = 35.; const float y1 = 40.; const float yh = 35.; addInput(createInput<sp_Port>(Vec(x1, y1 + 0 * yh), module, Pulse::CLOCK_INPUT)); addOutput(createOutput<sp_Port>(Vec(x2, y1 + 0 * yh), module, Pulse::CLOCK_OUTPUT)); addInput(createInput<sp_Port>(Vec(x1, y1 + 1 * yh), module, Pulse::TRIG_INPUT)); addParam(createParam<TL1105>(Vec(x2, y1 + 1 * yh), module, Pulse::TRIG_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 1.75 * yh), module, Pulse::RESET_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.25 * yh), module, Pulse::REPEAT_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.75 * yh), module, Pulse::RANGE_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 4 * yh), module, Pulse::TIME_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 4 * yh), module, Pulse::TIME_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 5 * yh), module, Pulse::DELAY_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 5 * yh), module, Pulse::DELAY_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 6 * yh), module, Pulse::AMP_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 6 * yh), module, Pulse::AMP_PARAM)); //addInput(createInput<sp_Port> (Vec(x1, y1+7*yh), module, Pulse::OFFSET_INPUT)); //addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1+7*yh), module, Pulse::OFFSET_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 7 * yh), module, Pulse::SLEW_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 7 * yh), module, Pulse::SLEW_PARAM)); addOutput(createOutput<sp_Port>(Vec(x1, y1 + 8.25 * yh), module, Pulse::EOC_OUTPUT)); addOutput(createOutput<sp_Port>(Vec(x2, y1 + 8.25 * yh), module, Pulse::GATE_OUTPUT)); addChild(createLight<SmallLight<RedLight>>(Vec(x1 + 7, y1 + 7.65 * yh), module, Pulse::EOC_LIGHT)); addChild(createLight<SmallLight<RedLight>>(Vec(x2 + 7, y1 + 7.65 * yh), module, Pulse::GATE_LIGHT)); } }; Model *modelPulse = createModel<Pulse, PulseWidget>("Pulse");
29.25641
124
0.631756
SteveRussell33
0526d13aee63e9bf31145a969bebee925a18542c
2,642
cpp
C++
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
#include <sstream> #include <stdio.h> #include <string> #include <cstring> #include <iostream> #include <vector> #include <map> #include <stack> #include <queue> #include <cmath> #include <algorithm> #include <cfloat> #include <climits> //#include <unordered_map> using namespace std; /* Time Complexity : O(n) Space Complexity : O(n) Trick: since it requires max gap between sorted elements, so we need to sort it anyway. Trick is to use Bucket Sort! Since they are all int, maxElem - minElem should be more than 1, avg gap is bucketSize=(maxElem - minElem)/size what we need is the max one, no need to calculate every gap, just those above avg. Special Cases : Summary: memset() : Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value. */ class Solution { public: int maximumGap(vector<int> &num) { int result = 0; if(num.size() == 0){ return result; } //get the min and max of the array int minElem = num[0]; int maxElem = num[0]; for(int i=1; i<num.size(); i++){ if(num[i] > maxElem){ maxElem = num[i]; }else if(num[i] < minElem){ minElem = num[i]; } } //init bucket sort int bucketSize = max(1, (maxElem - minElem)/(int)num.size()); int bucketNum = (maxElem - minElem)/bucketSize + 1; int bucketMin[bucketNum]; int bucketMax[bucketNum]; for(int i=0; i<bucketNum; i++){ bucketMin[i] = maxElem+1; bucketMax[i] = minElem-1; } for(int i=0; i<num.size(); i++){ int pos = (num[i] - minElem)/bucketSize; // cout<<"before :"<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl; if(bucketMin[pos] > num[i]){ bucketMin[pos] = num[i]; } if(bucketMax[pos] < num[i]){ bucketMax[pos] = num[i]; } // cout<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl; } //caculate max gap int lastMax = bucketMax[0]; for(int i=0; i<bucketNum; i++){ // cout<<bucketMin[i]<<", "<<bucketMax[i]<<endl; if(bucketMin[i] != maxElem+1){ result = max(result, bucketMin[i]-lastMax); lastMax = bucketMax[i]; } } return result; } }; int main(){ vector<int> input; input.push_back(1); input.push_back(10000000); Solution test; cout<<test.maximumGap(input)<<endl; return 0; }
29.032967
116
0.549205
Michael-Ma
0528eaf7fe79a9a2d4d4b46892fa36ac303fd382
3,223
cc
C++
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
3
2017-04-24T07:00:59.000Z
2020-04-13T04:53:06.000Z
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2017-01-10T04:23:55.000Z
2017-01-10T04:23:55.000Z
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2020-04-13T04:53:07.000Z
2020-04-13T04:53:07.000Z
void AESState::expand_generic(const uint8_t* key, std::size_t len) { uint32_t nk = (len / 4); uint32_t n = num_rounds * 4; for (uint32_t i = 0; i < nk; ++i) { enc.u32[i] = RBE32(key, i); } for (uint32_t i = nk; i < n; ++i) { uint32_t temp = enc.u32[i - 1]; uint32_t p = (i / nk); uint32_t q = (i % nk); if (q == 0) { temp = S0(ROL32(temp, 8)) ^ (uint32_t(POW_X[p - 1]) << 24); } else if (nk == 8 && q == 4) { temp = S0(temp); } enc.u32[i] = enc.u32[i - nk] ^ temp; } for (uint32_t i = 0; i < n; i += 4) { uint32_t ei = n - (i + 4); for (uint32_t j = 0; j < 4; ++j) { uint32_t x = enc.u32[ei + j]; if (i > 0 && (i + 4) < n) { x = TD(S0(x)); } dec.u32[i + j] = x; } } } void AESState::encrypt_generic(uint8_t* dst, const uint8_t* src, std::size_t len) const { uint32_t s0, s1, s2, s3; uint32_t t0, t1, t2, t3; uint32_t index; while (len >= 16) { // Round 1: just XOR s0 = enc.u32[0] ^ RBE32(src, 0); s1 = enc.u32[1] ^ RBE32(src, 1); s2 = enc.u32[2] ^ RBE32(src, 2); s3 = enc.u32[3] ^ RBE32(src, 3); // Rounds 2 .. N - 1: shuffle and XOR index = 4; for (uint32_t i = 2; i < num_rounds; ++i) { t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = enc.u32[index + 0] ^ TE(t0, t1, t2, t3); s1 = enc.u32[index + 1] ^ TE(t1, t2, t3, t0); s2 = enc.u32[index + 2] ^ TE(t2, t3, t0, t1); s3 = enc.u32[index + 3] ^ TE(t3, t0, t1, t2); index += 4; } // Round N: S-box and XOR t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = enc.u32[index + 0] ^ S0(t0, t1, t2, t3); s1 = enc.u32[index + 1] ^ S0(t1, t2, t3, t0); s2 = enc.u32[index + 2] ^ S0(t2, t3, t0, t1); s3 = enc.u32[index + 3] ^ S0(t3, t0, t1, t2); WBE32(dst, 0, s0); WBE32(dst, 1, s1); WBE32(dst, 2, s2); WBE32(dst, 3, s3); src += 16; dst += 16; len -= 16; } DCHECK_EQ(len, 0U); } void AESState::decrypt_generic(uint8_t* dst, const uint8_t* src, std::size_t len) const { while (len >= 16) { // Round 1: just XOR uint32_t s0 = dec.u32[0] ^ RBE32(src, 0); uint32_t s1 = dec.u32[1] ^ RBE32(src, 1); uint32_t s2 = dec.u32[2] ^ RBE32(src, 2); uint32_t s3 = dec.u32[3] ^ RBE32(src, 3); uint32_t t0, t1, t2, t3; // Rounds 2 .. N - 1: shuffle and XOR uint32_t i = 4; for (uint32_t round = 2; round < num_rounds; ++round) { t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = dec.u32[i + 0] ^ TD(t0, t3, t2, t1); s1 = dec.u32[i + 1] ^ TD(t1, t0, t3, t2); s2 = dec.u32[i + 2] ^ TD(t2, t1, t0, t3); s3 = dec.u32[i + 3] ^ TD(t3, t2, t1, t0); i += 4; } // Round N: S-box and XOR t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = dec.u32[i + 0] ^ S1(t0, t3, t2, t1); s1 = dec.u32[i + 1] ^ S1(t1, t0, t3, t2); s2 = dec.u32[i + 2] ^ S1(t2, t1, t0, t3); s3 = dec.u32[i + 3] ^ S1(t3, t2, t1, t0); WBE32(dst, 0, s0); WBE32(dst, 1, s1); WBE32(dst, 2, s2); WBE32(dst, 3, s3); src += 16; dst += 16; len -= 16; } DCHECK_EQ(len, 0U); }
25.579365
68
0.462302
chronos-tachyon
05354fa0a9663a8df41bc2d9162fe388f2c40333
11,402
cpp
C++
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "dummy_perception_publisher/node.hpp" #include "dummy_perception_publisher/signed_distance_function.hpp" #include <pcl/impl/point_types.hpp> #include <pcl/filters/voxel_grid_occlusion_estimation.h> #include <tf2/LinearMath/Transform.h> #include <tf2/LinearMath/Vector3.h> #include <functional> #include <limits> #include <memory> namespace { static constexpr double epsilon = 0.001; static constexpr double step = 0.05; static constexpr double vertical_theta_step = (1.0 / 180.0) * M_PI; static constexpr double vertical_min_theta = (-15.0 / 180.0) * M_PI; static constexpr double vertical_max_theta = (15.0 / 180.0) * M_PI; static constexpr double horizontal_theta_step = (0.1 / 180.0) * M_PI; static constexpr double horizontal_min_theta = (-180.0 / 180.0) * M_PI; static constexpr double horizontal_max_theta = (180.0 / 180.0) * M_PI; pcl::PointXYZ getPointWrtBaseLink( const tf2::Transform & tf_base_link2moved_object, double x, double y, double z) { const auto p_wrt_base = tf_base_link2moved_object(tf2::Vector3(x, y, z)); return pcl::PointXYZ(p_wrt_base.x(), p_wrt_base.y(), p_wrt_base.z()); } } // namespace void ObjectCentricPointCloudCreator::create_object_pointcloud( const ObjectInfo & obj_info, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud) const { std::normal_distribution<> x_random(0.0, obj_info.std_dev_x); std::normal_distribution<> y_random(0.0, obj_info.std_dev_y); std::normal_distribution<> z_random(0.0, obj_info.std_dev_z); const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object; const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); pcl::PointCloud<pcl::PointXYZ> horizontal_candidate_pointcloud; pcl::PointCloud<pcl::PointXYZ> horizontal_pointcloud; { const double y = -1.0 * (obj_info.width / 2.0); for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon); x += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double y = 1.0 * (obj_info.width / 2.0); for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon); x += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double x = -1.0 * (obj_info.length / 2.0); for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon); y += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double x = 1.0 * (obj_info.length / 2.0); for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon); y += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } // 2D ray tracing size_t ranges_size = std::ceil((horizontal_max_theta - horizontal_min_theta) / horizontal_theta_step); std::vector<double> horizontal_ray_traced_2d_pointcloud; horizontal_ray_traced_2d_pointcloud.assign(ranges_size, std::numeric_limits<double>::infinity()); const int no_data = -1; std::vector<int> horizontal_ray_traced_pointcloud_indices; horizontal_ray_traced_pointcloud_indices.assign(ranges_size, no_data); for (size_t i = 0; i < horizontal_candidate_pointcloud.points.size(); ++i) { double angle = std::atan2(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x); double range = std::hypot(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x); if (angle < horizontal_min_theta || angle > horizontal_max_theta) { continue; } int index = (angle - horizontal_min_theta) / horizontal_theta_step; if (range < horizontal_ray_traced_2d_pointcloud[index]) { horizontal_ray_traced_2d_pointcloud[index] = range; horizontal_ray_traced_pointcloud_indices.at(index) = i; } } for (const auto & pointcloud_index : horizontal_ray_traced_pointcloud_indices) { if (pointcloud_index != no_data) { // generate vertical point horizontal_pointcloud.push_back(horizontal_candidate_pointcloud.at(pointcloud_index)); const double distance = std::hypot( horizontal_candidate_pointcloud.at(pointcloud_index).x, horizontal_candidate_pointcloud.at(pointcloud_index).y); for (double vertical_theta = vertical_min_theta; vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) { const double z = distance * std::tan(vertical_theta); if (min_z <= z && z <= max_z + epsilon) { pcl::PointXYZ point; point.x = horizontal_candidate_pointcloud.at(pointcloud_index).x + x_random(random_generator); point.y = horizontal_candidate_pointcloud.at(pointcloud_index).y + y_random(random_generator); point.z = z + z_random(random_generator); pointcloud->push_back(point); } } } } } std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> ObjectCentricPointCloudCreator::create_pointclouds( const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const { std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds_tmp; pcl::PointCloud<pcl::PointXYZ>::Ptr merged_pointcloud_tmp(new pcl::PointCloud<pcl::PointXYZ>); for (const auto & obj_info : obj_infos) { pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_shared_ptr(new pcl::PointCloud<pcl::PointXYZ>); this->create_object_pointcloud( obj_info, tf_base_link2map, random_generator, pointcloud_shared_ptr); pointclouds_tmp.push_back(pointcloud_shared_ptr); } for (const auto & cloud : pointclouds_tmp) { for (const auto & pt : *cloud) { merged_pointcloud_tmp->push_back(pt); } } if (!enable_ray_tracing_) { merged_pointcloud = merged_pointcloud_tmp; return pointclouds_tmp; } pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_merged_pointcloud_ptr( new pcl::PointCloud<pcl::PointXYZ>); pcl::VoxelGridOcclusionEstimation<pcl::PointXYZ> ray_tracing_filter; ray_tracing_filter.setInputCloud(merged_pointcloud_tmp); ray_tracing_filter.setLeafSize(0.25, 0.25, 0.25); ray_tracing_filter.initializeVoxelGrid(); std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds; for (size_t i = 0; i < pointclouds_tmp.size(); ++i) { pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_pointcloud_ptr( new pcl::PointCloud<pcl::PointXYZ>); for (size_t j = 0; j < pointclouds_tmp.at(i)->size(); ++j) { Eigen::Vector3i grid_coordinates = ray_tracing_filter.getGridCoordinates( pointclouds_tmp.at(i)->at(j).x, pointclouds_tmp.at(i)->at(j).y, pointclouds_tmp.at(i)->at(j).z); int grid_state; if (ray_tracing_filter.occlusionEstimation(grid_state, grid_coordinates) != 0) { RCLCPP_ERROR(rclcpp::get_logger("dummy_perception_publisher"), "ray tracing failed"); } if (grid_state == 1) { // occluded continue; } else { // not occluded ray_traced_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j)); ray_traced_merged_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j)); } } pointclouds.push_back(ray_traced_pointcloud_ptr); } merged_pointcloud = ray_traced_merged_pointcloud_ptr; return pointclouds; } std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> EgoCentricPointCloudCreator::create_pointclouds( const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const { std::vector<std::shared_ptr<signed_distance_function::AbstractSignedDistanceFunction>> sdf_ptrs; for (const auto & obj_info : obj_infos) { const auto sdf_ptr = std::make_shared<signed_distance_function::BoxSDF>( obj_info.length, obj_info.width, tf_base_link2map * obj_info.tf_map2moved_object); sdf_ptrs.push_back(sdf_ptr); } const auto composite_sdf = signed_distance_function::CompositeSDF(sdf_ptrs); std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds(obj_infos.size()); for (size_t i = 0; i < obj_infos.size(); ++i) { pointclouds.at(i) = (pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>)); } std::vector<double> min_zs(obj_infos.size()); std::vector<double> max_zs(obj_infos.size()); for (size_t idx = 0; idx < obj_infos.size(); ++idx) { const auto & obj_info = obj_infos.at(idx); const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object; const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); min_zs.at(idx) = min_z; max_zs.at(idx) = max_z; } double angle = 0.0; const auto n_scan = static_cast<size_t>(std::floor(2 * M_PI / horizontal_theta_step)); for (size_t i = 0; i < n_scan; ++i) { angle += horizontal_theta_step; const auto dist = composite_sdf.getSphereTracingDist(0.0, 0.0, angle, visible_range_); if (std::isfinite(dist)) { const auto x_hit = dist * cos(angle); const auto y_hit = dist * sin(angle); const auto idx_hit = composite_sdf.nearest_sdf_index(x_hit, y_hit); const auto obj_info_here = obj_infos.at(idx_hit); const auto min_z_here = min_zs.at(idx_hit); const auto max_z_here = max_zs.at(idx_hit); std::normal_distribution<> x_random(0.0, obj_info_here.std_dev_x); std::normal_distribution<> y_random(0.0, obj_info_here.std_dev_y); std::normal_distribution<> z_random(0.0, obj_info_here.std_dev_z); for (double vertical_theta = vertical_min_theta; vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) { const double z = dist * std::tan(vertical_theta); if (min_z_here <= z && z <= max_z_here + epsilon) { pointclouds.at(idx_hit)->push_back(pcl::PointXYZ( x_hit + x_random(random_generator), y_hit + y_random(random_generator), z + z_random(random_generator))); } } } } for (const auto & cloud : pointclouds) { for (const auto & pt : *cloud) { merged_pointcloud->push_back(pt); } } return pointclouds; }
43.353612
100
0.70628
meliketanrikulu
0536d938a6384b5a1119f032f2d0c84c64fd1773
1,581
hpp
C++
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
3
2018-11-05T19:49:48.000Z
2018-11-10T18:03:22.000Z
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
1
2018-11-10T19:00:24.000Z
2018-11-11T18:49:46.000Z
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
1
2018-11-06T00:09:57.000Z
2018-11-06T00:09:57.000Z
#include <string> #include <iostream> #pragma once enum log_level {DEBUG = 0, INFO, WARNING, ERROR, LogLevelMax}; class Loggeable { public: void mute() {m_mute = true;}; void unmute() {m_mute = false;}; void filter(log_level min_lvl) {m_min_lvl = min_lvl;}; void prefix(std::string prefix) {m_prefix = std::move(prefix);}; template<typename... T> void log(log_level lvl, const char* fmt, T ... args) { if(lvl >= m_min_lvl && !m_mute) { *out_streams[lvl] << m_prefix; // don't store on the stack; no need to be reentrant and allows coroutines to have a tiny stack static char buff[2048]; std::snprintf(&buff[0], 2048, fmt, args...); // No buffer overflow there, sir ! *out_streams[lvl] << &buff[0]; } }; bool m_mute = false; log_level m_min_lvl = INFO; std::string m_prefix; std::ostream* out_streams[LogLevelMax] = { &std::clog, // DEBUG &std::cout, // INFO &std::cerr, // WARNING &std::cerr // ERROR }; }; inline Loggeable global_logger; template<typename... T> void log(log_level lvl, const char* fmt, T ... args) { global_logger.log(lvl, fmt, args...); } template<typename... T> void info(const char* fmt, T ... args) { global_logger.log(INFO, fmt, args...); } template<typename... T> void warn(const char* fmt, T ... args) { global_logger.log(WARNING, fmt, args...); } template<typename... T> void error(const char* fmt, T ... args) { global_logger.log(ERROR, fmt, args...); }
23.954545
108
0.595193
NematodCorp
053716be9aa19f62334322f7af88470a0a12524b
1,652
cc
C++
pdb/src/logicalPlan/source/LogicalPlan.cc
SeraphL/plinycompute
7788bc2b01d83f4ff579c13441d0ba90734b54a2
[ "Apache-2.0" ]
3
2019-05-04T05:17:30.000Z
2020-02-21T05:01:59.000Z
pdb/src/logicalPlan/source/LogicalPlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
3
2020-02-20T19:50:46.000Z
2020-06-25T14:31:51.000Z
pdb/src/logicalPlan/source/LogicalPlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
5
2019-02-19T23:17:24.000Z
2020-08-03T01:08:04.000Z
#include <LogicalPlan.h> #include <Lexer.h> #include <Parser.h> namespace pdb { LogicalPlan::LogicalPlan(const std::string &tcap, Vector<Handle<Computation>> &computations) { init(tcap, computations); } LogicalPlan::LogicalPlan(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) { init(computationsIn, allComputations); } void LogicalPlan::init(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) { computations = computationsIn; for (int i = 0; i < allComputations.size(); i++) { std::string compType = allComputations[i]->getComputationType(); compType += "_"; compType += std::to_string(i); pdb::ComputationNode temp(allComputations[i]); allConstituentComputations[compType] = temp; } } void LogicalPlan::init(const std::string &tcap, Vector<Handle<Computation>> &allComputations) { // get the string to compile std::string myLogicalPlan = tcap; myLogicalPlan.push_back('\0'); // where the result of the parse goes AtomicComputationList *myResult; // now, do the compilation yyscan_t scanner; LexerExtra extra{""}; yylex_init_extra(&extra, &scanner); const YY_BUFFER_STATE buffer{yy_scan_string(myLogicalPlan.data(), scanner)}; const int parseFailed{yyparse(scanner, &myResult)}; yy_delete_buffer(buffer, scanner); yylex_destroy(scanner); // if it didn't parse, get outta here if (parseFailed) { std::cout << "Parse error when compiling TCAP: " << extra.errorMessage; exit(1); } // copy all the computations init(*myResult, allComputations); delete myResult; } }
28.982456
126
0.72276
SeraphL
053c2d811dfd686c00564d58c6632bc76de66a0c
3,218
cpp
C++
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
161
2015-01-13T15:52:06.000Z
2020-02-13T01:26:04.000Z
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
281
2015-01-06T12:46:40.000Z
2019-01-06T13:06:57.000Z
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
51
2015-03-03T19:56:12.000Z
2020-03-22T02:13:36.000Z
#include <xpcc/architecture/driver/accessor.hpp> namespace bitmap { FLASH_STORAGE(uint8_t skull_64x64[]) = { 64, 64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0x60, 0x30, 0x18, 0x08, 0x0c, 0x0c, 0x04, 0x06, 0x06, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x06, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x07, 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x0f, 0x7c, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xf0, 0x80, 0x03, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x03, 0x80, 0xf0, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0x40, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x0e, 0xfc, 0x7f, 0x00, 0x00, 0x3e, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x3c, 0x00, 0x00, 0x7f, 0xfc, 0x0e, 0x07, 0x01, 0x00, 0x00, 0x00, 0x80, 0x80, 0xc0, 0x80, 0x80, 0x00, 0x00, 0x00, 0xf0, 0xb8, 0x9e, 0x8f, 0x80, 0x80, 0x80, 0x83, 0x07, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x60, 0x6f, 0xfc, 0xf0, 0xe0, 0xc0, 0xc0, 0xc1, 0xc1, 0x83, 0x03, 0x01, 0x00, 0x00, 0x00, 0xfc, 0xfe, 0xff, 0x00, 0xff, 0xfe, 0xf8, 0x00, 0x00, 0x00, 0x01, 0x03, 0x83, 0x81, 0xc1, 0xc0, 0xe0, 0xe0, 0xf0, 0xfc, 0xcf, 0x40, 0x60, 0x30, 0x10, 0x1c, 0x0e, 0x03, 0x01, 0x00, 0x01, 0x1f, 0x30, 0x60, 0xc0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x63, 0xff, 0x31, 0x0d, 0xe3, 0x0f, 0x5c, 0xf0, 0x90, 0xf0, 0x11, 0xe1, 0x20, 0xe0, 0x10, 0xf1, 0x11, 0xf0, 0x90, 0x90, 0xdc, 0x0f, 0xf1, 0x0f, 0xf9, 0xff, 0xc7, 0x61, 0x61, 0x30, 0x30, 0x18, 0x18, 0x0c, 0x04, 0x06, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xb0, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x18, 0x08, 0x0c, 0x0c, 0x86, 0xc2, 0xc3, 0x6f, 0x7e, 0x70, 0xc1, 0x83, 0x82, 0x07, 0x04, 0x07, 0x08, 0x0f, 0x09, 0x0f, 0x09, 0x0f, 0x09, 0x05, 0x04, 0x05, 0x82, 0xc3, 0xe0, 0x70, 0x7f, 0x6f, 0xc6, 0xcc, 0x8c, 0x08, 0x18, 0x10, 0x30, 0x20, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x7e, 0x60, 0x40, 0x60, 0x30, 0x1c, 0x06, 0x02, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x02, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x02, 0x06, 0x1c, 0x30, 0x60, 0x40, 0x60, 0x3c, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00, }; }
160.9
385
0.664388
walmis
053fe1de8b7fab54dc2d72ddab913bb93f94350e
1,093
cpp
C++
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: string convert(string s, int n) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA if(n == 0 || n == 1) return s; string res; for(int i = 1; i <= n; i++) { int j = i-1; char dir = 'd'; while(j < s.length()) { if(i == 1 || i == n) { res.push_back(s[j]); j += (2*n - 2); } else { if(dir == 'd') { res.push_back(s[j]); j += 2*(n - i); dir = 'u'; } else { res.push_back(s[j]); j += 2*(i-1); dir = 'd'; } } } } return res; } };
26.02381
73
0.270814
Tiger-Team-01
0541a6396de3e6c962f643736055c56af454f607
697
cpp
C++
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) { vector<vector<int>> g(n); for (auto &v : edges) { g[v[0]].push_back(v[1]); g[v[1]].push_back(v[0]); } vector<int> ans(n); dfs(ans, g, labels); return ans; } vector<int> dfs(vector<int> &ans, vector<vector<int>> &g, string &labels, int i = 0, int parent = -1) { vector<int> temp(26); for (int j : g[i]) { if (j == parent) continue; auto temp2 = dfs(ans, g, labels, j, i); for (int i = 0; i < 26; i++) temp[i] += temp2[i]; } ans[i] = ++temp[labels[i] - 'a']; return temp; } };
23.233333
79
0.503587
satu0king
0546b851cff43d48229d17b30e9a59085ce670de
7,264
c++
C++
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
// ModelView.c++ - an Abstract Base Class for a combined Model and View for OpenGL #include <iostream> #include "ModelView.h" #include "Controller.h" cryph::AffPoint ModelView::eye(0, 0, 2); cryph::AffPoint ModelView::center(0, 0, 0); cryph::AffVector ModelView::up(0, 1, 0); double ModelView::mcRegionOfInterest[6] = { -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 }; ProjectionType ModelView::projType = PERSPECTIVE; cryph::AffVector ModelView::obliqueProjectionDir(0.25, 0.5, 1.0); double ModelView::ecZmin = -2.0; double ModelView::ecZmax = -0.01; // for perspective, must be strictly < 0 double ModelView::zpp = -1.0; // for perspective, must be strictly < 0 double ModelView::dynamic_zoomScale = 1.0; // dynamic zoom cryph::Matrix4x4 ModelView::dynamic_view; // dynamic 3D rotation/pan ModelView::ModelView() { } ModelView::~ModelView() { } #if 0 void ModelView::addToGlobalRotationDegrees(double rx, double ry, double rz) { // TODO: 1. UPDATE dynamic_view // TODO: 2. Use dynamic_view in ModelView::getMatrices } #endif void ModelView::addToGlobalZoom(double increment) { dynamic_zoomScale += increment; // TODO: Use dynamic_zoomScale in ModelView::getMatrices } // compute2DScaleTrans determines the current model coordinate region of // interest and then uses linearMap to determine how to map coordinates // in the region of interest to their proper location in Logical Device // Space. (Returns float[] because glUniform currently favors float[].) void ModelView::compute2DScaleTrans(float* scaleTransF) // CLASS METHOD { double xmin = mcRegionOfInterest[0]; double xmax = mcRegionOfInterest[1]; double ymin = mcRegionOfInterest[2]; double ymax = mcRegionOfInterest[3]; // preserve aspect ratio. Make "region of interest" wider or taller to // match the Controller's viewport aspect ratio. double vAR = Controller::getCurrentController()->getViewportAspectRatio(); matchAspectRatio(xmin, xmax, ymin, ymax, vAR); double scaleTrans[4]; linearMap(xmin, xmax, -1.0, 1.0, scaleTrans[0], scaleTrans[1]); linearMap(ymin, ymax, -1.0, 1.0, scaleTrans[2], scaleTrans[3]); for (int i=0 ; i<4 ; i++) scaleTransF[i] = static_cast<float>(scaleTrans[i]); } #if 0 void ModelView::getMatrices(cryph::Matrix4x4& mc_ec, cryph::Matrix4x4& ec_lds) { // TODO: // 1. Create the mc_ec matrix: // Matrix M_ECu is created from the eye, center, and up. You can use the // following utility from Matrix4x4: // // cryph::Matrix4x4 cryph::Matrix4x4::lookAt( // const cryph::AffPoint& eye, const cryph::AffPoint& center, // const cryph::AffVector& up); // // NOTE: eye, center, and up are specified in MODEL COORDINATES (MC) // // So, for example: // cryph::Matrix4x4 M_ECu = cryph::Matrix4x4::lookAt(eye, center, up); // // a) For project 2: mc_ec = M_ECu // b) For project 3: mc_ec = dynamic_view * M_ECu // // 2. Create the ec_lds matrix: // Using the WIDTHS of the established mcRegionOfInterest: // i) Adjust in the x OR y direction to match the viewport aspect ratio; // ii) Scale both widths by dynamic_zoom; // iii) create the matrix using the method for the desired type of projection. // // Any of the three Matrix4x4 methods shown below (declared in Matrix4x4.h) // can be used to create ec_lds. On a given call to this "getMatrices" routine, // you will use EXACTLY ONE of them, depending on what type of projection you // currently want. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!! All coordinate data in the parameter lists below are specified !!!!!! // !!!!! in EYE COORDINATES (EC)! Be VERY sure you understand what that !!!!!! // !!!!! means! (This is why I emphasized "WIDTHS" above.) !!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /* The three choices: cryph::Matrix4x4 cryph::Matrix4x4::orthogonal(double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax); cryph::Matrix4x4 cryph::Matrix4x4::perspective(double zpp, double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax); cryph::Matrix4x4 cryph::Matrix4x4::oblique(double zpp, double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax, const cryph::AffVector& projDir); */ // For example: // ec_lds = cryph::Matrix4x4::perspective(zpp, ecXmin, ecXmax, ecYmin, ecYmax, ecZmin, ecZmax); // // RECALL: Use the class variables ecZmin, ecZmax, and zpp in these calls. // THEN IN THE CALLER OF THIS METHOD: // // float mat[16]; // glUniformMatrix4fv(ppuLoc_mc_ec, 1, false, mc_ec.extractColMajor(mat)); // glUniformMatrix4fv(ppuLoc_ec_lds, 1, false, ec_lds.extractColMajor(mat)); // // (The extractColMajor method copies the elements of the matrix into the given // array which is assumed to be of length 16. It then returns the array pointer // so it can be used as indicated in the two calls. Since the array is immediately // copied by glUniformMatrix to the GPU, "mat" can be reused as indicated.) } #endif // linearMap determines the scale and translate parameters needed in // order to map a value, f (fromMin <= f <= fromMax) to its corresponding // value, t (toMin <= t <= toMax). Specifically: t = scale*f + trans. void ModelView::linearMap(double fromMin, double fromMax, double toMin, double toMax, double& scale, double& trans) // CLASS METHOD { scale = (toMax - toMin) / (fromMax - fromMin); trans = toMin - scale*fromMin; } void ModelView::matchAspectRatio(double& xmin, double& xmax, double& ymin, double& ymax, double vAR) { double wHeight = ymax - ymin; double wWidth = xmax - xmin; double wAR = wHeight / wWidth; if (wAR > vAR) { // make window wider wWidth = wHeight / vAR; double xmid = 0.5 * (xmin + xmax); xmin = xmid - 0.5*wWidth; xmax = xmid + 0.5*wWidth; } else { // make window taller wHeight = wWidth * vAR; double ymid = 0.5 * (ymin + ymax); ymin = ymid - 0.5*wHeight; ymax = ymid + 0.5*wHeight; } } GLint ModelView::ppUniformLocation(GLuint glslProgram, const std::string& name) { GLint loc = glGetUniformLocation(glslProgram, name.c_str()); if (loc < 0) std::cerr << "Could not locate per-primitive uniform: '" << name << "'\n"; return loc; } GLint ModelView::pvAttribLocation(GLuint glslProgram, const std::string& name) { GLint loc = glGetAttribLocation(glslProgram, name.c_str()); if (loc < 0) std::cerr << "Could not locate per-vertex attribute: '" << name << "'\n"; return loc; } void ModelView::setECZminZmax(double zMinIn, double zMaxIn) { ecZmin = zMinIn; ecZmax = zMaxIn; } void ModelView::setEyeCenterUp(cryph::AffPoint E, cryph::AffPoint C, cryph::AffVector Up) { eye = E; center = C; up = Up; } void ModelView::setMCRegionOfInterest(double xyz[6]) { for (int i=0 ; i<6 ; i++) mcRegionOfInterest[i] = xyz[i]; } void ModelView::setProjection(ProjectionType pType) { projType = pType; } void ModelView::setProjectionPlaneZ(double zppIn) { zpp = zppIn; }
33.62963
96
0.664372
kevinbajaj
d73235eda23c9c0ffa54e7accceacfbe68c9f960
268
cc
C++
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
#include "day4.h" #include <iostream> int main(void) { static constexpr auto input = "yzbqklnj"; std::cout << "Day 4, part 1: " << day4::mineAdventCoin(input, false) << '\n'; std::cout << "Day 4, part 2: " << day4::mineAdventCoin(input, true) << '\n'; }
26.8
81
0.593284
LesnyRumcajs
d73460f4f5cde88221298654ff58a40e734caa23
5,328
cpp
C++
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
#include "controllers/SmartController.h" using namespace wml::controllers; bool SmartController::Exists(tAxis axis, bool value) { try { _axes.at(axis.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(tButton button, bool value) { try { _buttons.at(button.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(tPOV pov, bool value) { try { _POVs.at(pov.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(std::vector<tAxis> axi, bool value) { bool val = value; for (auto axis : axi) val |= Exists(axis, value); return val; } bool SmartController::Exists(std::vector<tButton> buttons, bool value) { bool val = value; for (auto button : buttons) val |= Exists(button, value); return val; } bool SmartController::Exists(std::vector<tPOV> povs, bool value) { bool val = value; for (auto pov : povs) val |= Exists(pov, value); return val; } inputs::ContAxis *SmartController::GetObj(tAxis axis) { return Exists(axis) ? _axes.at(axis.id) : nullptr; } inputs::ContButton *SmartController::GetObj(tButton button) { return Exists(button) ? _buttons.at(button.id) : nullptr; } inputs::ContPOV *SmartController::GetObj(tPOV pov) { return Exists(pov) ? _POVs.at(pov.id) : nullptr; } void SmartController::Map(tAxis axis, inputs::ContAxis *newAxis, bool force) { if (!force) if (Exists(axis)) return; _axes[axis.id] = newAxis; } void SmartController::Map(tButton button, inputs::ContButton *newButton, bool force) { if (!force) if (Exists(button)) return; _buttons[button.id] = newButton; } void SmartController::Map(tPOV pov, inputs::ContPOV *newPOV, bool force) { if (!force) if (Exists(pov)) return; _POVs[pov.id] = newPOV; } void SmartController::Map(tAxis map_axis, tButton virt_button, double threshold, bool force) { if (!Exists(map_axis)) return; Map(virt_button, inputs::MakeAxisButton(GetObj(map_axis), threshold).at(0), force); // _axes.erase(_axes.find(map_axis.id)); } void SmartController::Map(tAxis map_axis, std::vector<tButton> virt_buttons, bool force) { if (!Exists(map_axis)) return; std::vector<inputs::AxisSelectorButton*> buttons = inputs::MakeAxisSelectorButtons(GetObj(map_axis), virt_buttons.size()); for (unsigned int i = 0; i < buttons.size(); i++) { if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force); } // _axes.erase(_axes.find(map_axis.id)); } void SmartController::PairAxis(tAxis primary_axis, tAxis secondary_axis, bool squared) { if (!Exists(primary_axis) || !Exists(secondary_axis)) return; std::pair<inputs::FieldAxis*, inputs::FieldAxis*> axi = inputs::MakeFieldAxi(new inputs::Field(std::make_pair<inputs::ContAxis*, inputs::ContAxis*>(GetObj(primary_axis), GetObj(secondary_axis)), squared)); Map(primary_axis, axi.first, true); Map(secondary_axis, axi.second, true); } void SmartController::Map(std::pair<tButton, tButton> map_buttons, std::vector<tButton> virt_buttons, bool wrap, bool force) { if (!Exists(std::vector<tButton>({ map_buttons.first, map_buttons.second }))) return; std::vector<inputs::ButtonSelectorButton*> buttons = inputs::MakeButtonSelectorButtons({ GetObj(map_buttons.first), GetObj(map_buttons.second) }, virt_buttons.size(), wrap); for (unsigned int i = 0; i < buttons.size(); i++) { if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force); } // _buttons.erase(_buttons.find(map_buttons.first.id)); // _buttons.erase(_buttons.find(map_buttons.second.id)); } void SmartController::Map(tPOV map_POV, std::map<Controller::POVPos, tButton> virt_buttons, bool force) { if (!Exists(map_POV)) return; std::map<Controller::POVPos, inputs::POVButton*> buttons = inputs::MakePOVButtons(GetObj(map_POV)); for (auto pair : virt_buttons) { if (pair.second != noButton) Map(pair.second, buttons.at(pair.first), force); } // _POVs.erase(_POVs.find(map_POV.id)); } // --------------------------------------------- INPUT GETTERS --------------------------------------------- double SmartController::Get(tAxis axis) { if (Exists(axis, false)) return 0; return GetObj(axis)->Get(); } bool SmartController::Get(tButton button, SmartController::ButtonMode mode) { if (Exists(button, false)) return false; switch (mode) { case ButtonMode::RAW: return GetObj(button)->Get(); case ButtonMode::ONRISE: return GetObj(button)->GetOnRise(); case ButtonMode::ONFALL: return GetObj(button)->GetOnFall(); case ButtonMode::ONCHANGE: return GetObj(button)->GetOnChange(); } return false; } wml::controllers::Controller::POVPos SmartController::Get(tPOV pov) { if (Exists(pov, false)) return kNone; return GetObj(pov)->Get(); } // ------------------------------------------- FEEDBACK SETTERS -------------------------------------------- void SmartController::Set(tRumble rumble, double value) { _cont->SetRumble(rumble.type, value); } // --------------------------------------------- UPDATE FUNCS ---------------------------------------------- void SmartController::UpdateButtonSelectors() { for (auto pair : _buttons) UpdateButtonSelector(tButton(-1, pair.first)); }
28.491979
207
0.665728
JaciBrunning
d73e1dbfd60bd978a0197c0a6322f580467bd0d5
2,820
cpp
C++
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
/** Sunny and Johnny together have MM dollars they want to spend on ice cream. The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount. You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M. Input Format The first line of the input contains T; T test cases follow. Each test case follows the format detailed below: The first line contains M. The second line contains N. The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci. Output Format Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N. Constraints 1 <= T <= 50 2 <= M <= 10000 2 <= N <= 10000 1 <= ci <= 10000, where i in [1,N] The prices of any two items may be the same and each test case has a unique solution. Sample Input 2 4 5 1 4 5 3 2 4 4 2 2 4 3 Sample Output 1 4 1 2 Explanation The sample input has two test cases. For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sum up to 4. For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sum up to 4. **/ /** NOTE: http://stackoverflow.com/questions/4720271/find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number There are 3 approaches to this solution: Let the sum be T and n be the size of array Approach 1: The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2). Approach 2: A better way would be to sort the array. This takes O(n log n) Then for each x in array A, use binary search to look for T-x. This will take O(nlogn). So, overall search is O(n log n) Approach 3 : The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion. Then for every x, we can just look up its complement, T-x, which is O(1). Overall the run time of this approach is O(n). **/ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int t = 0; cin >> t; while(t--){ unsigned M = 0; unsigned N = 0; cin >> M >> N; unordered_map<int,unsigned> prices; for(unsigned i = 0; i < N; i++){ unsigned price = 0; cin >> price; prices.insert({price,i}); unordered_map<int,unsigned>::const_iterator got = prices.find(M-price); if(got != prices.end() && got->second != i){ cout << got->second + 1 << " " << i+1; } } cout << "\n"; } return 0; }
27.920792
152
0.673404
whitehatty
d7427ec84324c3945f28973ffb18eda2d0383f2e
3,300
cc
C++
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 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 // // 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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/bigquery/v2/model.proto #include "google/cloud/bigquery/internal/model_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/bigquery/v2/model.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace bigquery_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ModelServiceLogging::ModelServiceLogging( std::shared_ptr<ModelServiceStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::GetModel( grpc::ClientContext& context, google::cloud::bigquery::v2::GetModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::GetModelRequest const& request) { return child_->GetModel(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::bigquery::v2::ListModelsResponse> ModelServiceLogging::ListModels( grpc::ClientContext& context, google::cloud::bigquery::v2::ListModelsRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::ListModelsRequest const& request) { return child_->ListModels(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::PatchModel( grpc::ClientContext& context, google::cloud::bigquery::v2::PatchModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::PatchModelRequest const& request) { return child_->PatchModel(context, request); }, context, request, __func__, tracing_options_); } Status ModelServiceLogging::DeleteModel( grpc::ClientContext& context, google::cloud::bigquery::v2::DeleteModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::DeleteModelRequest const& request) { return child_->DeleteModel(context, request); }, context, request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigquery_internal } // namespace cloud } // namespace google
38.372093
78
0.724848
sydney-munro
d743e0d24f60ca8e1950c283cdab218ff20e6678
31,899
cpp
C++
iRODS/clients/icommands/src/iticket.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
null
null
null
iRODS/clients/icommands/src/iticket.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
7
2019-12-02T17:55:49.000Z
2019-12-02T17:55:59.000Z
iRODS/clients/icommands/src/iticket.cpp
benlazarine/irods
83f3c4a6f8f7fc6422a1e73a297b97796a961322
[ "BSD-3-Clause" ]
1
2019-12-02T05:44:10.000Z
2019-12-02T05:44:10.000Z
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* This is an interface to the Ticket management system. */ #include "irods_client_api_table.hpp" #include "irods_pack_table.hpp" #include "rods.h" #include "rodsClient.h" #include "irods_random.hpp" #define MAX_SQL 300 #define BIG_STR 3000 extern int get64RandomBytes( char *buf ); char cwd[BIG_STR]; int debug = 0; int longMode = 0; /* more detailed listing */ char zoneArgument[MAX_NAME_LEN + 2] = ""; rcComm_t *Conn; rodsEnv myEnv; int lastCommandStatus = 0; int printCount = 0; int printedRows = 0; int usage( char *subOpt ); void showRestrictions( char *inColumn ); /* print the results of a general query. */ void printResultsAndSubQuery( rcComm_t *Conn, int status, genQueryOut_t *genQueryOut, char *descriptions[], int subColumn, int dashOpt ) { int i, j; lastCommandStatus = status; if ( status == CAT_NO_ROWS_FOUND ) { lastCommandStatus = 0; } if ( status != 0 && status != CAT_NO_ROWS_FOUND ) { printError( Conn, status, "rcGenQuery" ); } else { if ( status == CAT_NO_ROWS_FOUND ) { if ( printCount == 0 ) { printf( "No rows found\n" ); } } else { for ( i = 0; i < genQueryOut->rowCnt; i++ ) { printedRows++; char *subCol = ""; if ( i > 0 && dashOpt > 0 ) { printf( "----\n" ); } for ( j = 0; j < genQueryOut->attriCnt; j++ ) { char *tResult; tResult = genQueryOut->sqlResult[j].value; tResult += i * genQueryOut->sqlResult[j].len; if ( subColumn == j ) { subCol = tResult; } if ( *descriptions[j] != '\0' ) { if ( strstr( descriptions[j], "time" ) != 0 ) { char localTime[TIME_LEN]; getLocalTimeFromRodsTime( tResult, localTime ); if ( strcmp( tResult, "0" ) == 0 || *tResult == '\0' ) { strcpy( localTime, "none" ); } printf( "%s: %s\n", descriptions[j], localTime ); } else { printf( "%s: %s\n", descriptions[j], tResult ); printCount++; } } } if ( subColumn >= 0 ) { showRestrictions( subCol ); } } } } } void showRestrictionsByHost( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to host"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_HOST; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_HOST_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No host restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No host restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictionsByUser( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to user"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_USER_NAME; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_USER_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No user restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No user restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictionsByGroup( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to group"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_GROUP_NAME; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_GROUP_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No group restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No group restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictions( char *inColumn ) { showRestrictionsByHost( inColumn ); showRestrictionsByUser( inColumn ); showRestrictionsByGroup( inColumn ); return; } /* Via a general query, show the Tickets for this user */ int showTickets1( char *inOption, char *inName ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[20]; int i1b[20]; int i2a[20]; int i; char v1[MAX_NAME_LEN]; char *condVal[20]; int status; char *columnNames[] = {"id", "string", "ticket type", "obj type", "owner name", "owner zone", "uses count", "uses limit", "write file count", "write file limit", "write byte count", "write byte limit", "expire time", "collection name", "data collection"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ID; i1b[i++] = 0; i1a[i] = COL_TICKET_STRING; i1b[i++] = 0; i1a[i] = COL_TICKET_TYPE; i1b[i++] = 0; i1a[i] = COL_TICKET_OBJECT_TYPE; i1b[i++] = 0; i1a[i] = COL_TICKET_OWNER_NAME; i1b[i++] = 0; i1a[i] = COL_TICKET_OWNER_ZONE; i1b[i++] = 0; i1a[i] = COL_TICKET_USES_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_USES_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_FILE_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_FILE_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_BYTE_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_BYTE_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_EXPIRY_TS; i1b[i++] = 0; i1a[i] = COL_TICKET_COLL_NAME; i1b[i++] = 0; if ( strstr( inOption, "data" ) != 0 ) { i--; i1a[i] = COL_TICKET_DATA_NAME; columnNames[i] = "data-object name"; i1b[i++] = 0; i1a[i] = COL_TICKET_DATA_COLL_NAME; i1b[i++] = 0; } if ( strstr( inOption, "basic" ) != 0 ) { /* skip the COLL or DATA_NAME so it's just a query on the ticket tables */ i--; } genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; genQueryInp.condInput.len = 0; if ( inName != NULL && *inName != '\0' ) { if ( isInteger( inName ) == 1 ) { /* Could have an all-integer ticket but in most cases this is a good guess */ i2a[0] = COL_TICKET_ID; } else { i2a[0] = COL_TICKET_STRING; } snprintf( v1, sizeof( v1 ), "='%s'", inName ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; } genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; if ( zoneArgument[0] != '\0' ) { addKeyVal( &genQueryInp.condInput, ZONE_KW, zoneArgument ); } status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { return 0; } if ( status == CAT_NO_ROWS_FOUND ) { return 0; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 1 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( genQueryOut->rowCnt > 0 ) { printf( "----\n" ); } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 1 ); } return 0; } void showTickets( char *inName ) { printedRows = 0; showTickets1( "data", inName ); if ( printedRows > 0 ) { printf( "----\n" ); } showTickets1( "collection", inName ); if ( printedRows == 0 ) { /* try a more basic query in case the data obj or collection is gone */ showTickets1( "basic", inName ); if ( printedRows > 0 && inName != NULL && *inName != '\0' ) { printf( "Warning: the data-object or collection for this ticket no longer exists\n" ); } } } std::string makeFullPath( const char *inName ) { std::stringstream fullPathStream; if ( strlen( inName ) == 0 ) { return std::string(); } if ( *inName != '/' ) { fullPathStream << cwd << "/"; } fullPathStream << inName; return fullPathStream.str(); } /* Create, modify, or delete a ticket */ int doTicketOp( const char *arg1, const char *arg2, const char *arg3, const char *arg4, const char *arg5 ) { ticketAdminInp_t ticketAdminInp; int status; ticketAdminInp.arg1 = strdup( arg1 ); ticketAdminInp.arg2 = strdup( arg2 ); ticketAdminInp.arg3 = strdup( arg3 ); ticketAdminInp.arg4 = strdup( arg4 ); ticketAdminInp.arg5 = strdup( arg5 ); ticketAdminInp.arg6 = ""; status = rcTicketAdmin( Conn, &ticketAdminInp ); lastCommandStatus = status; free( ticketAdminInp.arg1 ); free( ticketAdminInp.arg2 ); free( ticketAdminInp.arg3 ); free( ticketAdminInp.arg4 ); free( ticketAdminInp.arg5 ); if ( status < 0 ) { if ( Conn->rError ) { rError_t *Err; rErrMsg_t *ErrMsg; int i, len; Err = Conn->rError; len = Err->len; for ( i = 0; i < len; i++ ) { ErrMsg = Err->errMsg[i]; rodsLog( LOG_ERROR, "Level %d: %s", i, ErrMsg->msg ); } } char *mySubName = NULL; const char *myName = rodsErrorName( status, &mySubName ); rodsLog( LOG_ERROR, "rcTicketAdmin failed with error %d %s %s", status, myName, mySubName ); free( mySubName ); } return status; } void makeTicket( char *newTicket ) { const int ticket_len = 15; // random_bytes must be (unsigned char[]) to guarantee that following // modulo result is positive (i.e. in [0, 61]) unsigned char random_bytes[ticket_len]; irods::getRandomBytes( random_bytes, ticket_len ); const char characterSet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; for ( int i = 0; i < ticket_len; ++i ) { const int ix = random_bytes[i] % sizeof(characterSet); newTicket[i] = characterSet[ix]; } newTicket[ticket_len] = '\0'; printf( "ticket:%s\n", newTicket ); } /* Prompt for input and parse into tokens */ void getInput( char *cmdToken[], int maxTokens ) { int lenstr, i; static char ttybuf[BIG_STR]; int nTokens; int tokenFlag; /* 1: start reg, 2: start ", 3: start ' */ char *cpTokenStart; char *stat; memset( ttybuf, 0, BIG_STR ); fputs( "iticket>", stdout ); stat = fgets( ttybuf, BIG_STR, stdin ); if ( stat == 0 ) { printf( "\n" ); rcDisconnect( Conn ); if ( lastCommandStatus != 0 ) { exit( 4 ); } exit( 0 ); } lenstr = strlen( ttybuf ); for ( i = 0; i < maxTokens; i++ ) { cmdToken[i] = ""; } cpTokenStart = ttybuf; nTokens = 0; tokenFlag = 0; for ( i = 0; i < lenstr; i++ ) { if ( ttybuf[i] == '\n' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; return; } if ( tokenFlag == 0 ) { if ( ttybuf[i] == '\'' ) { tokenFlag = 3; cpTokenStart++; } else if ( ttybuf[i] == '"' ) { tokenFlag = 2; cpTokenStart++; } else if ( ttybuf[i] == ' ' ) { cpTokenStart++; } else { tokenFlag = 1; } } else if ( tokenFlag == 1 ) { if ( ttybuf[i] == ' ' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } else if ( tokenFlag == 2 ) { if ( ttybuf[i] == '"' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } else if ( tokenFlag == 3 ) { if ( ttybuf[i] == '\'' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } } } /* handle a command, return code is 0 if the command was (at least partially) valid, -1 for quitting, -2 for if invalid -3 if empty. */ int doCommand( char *cmdToken[] ) { if ( strcmp( cmdToken[0], "help" ) == 0 || strcmp( cmdToken[0], "h" ) == 0 ) { usage( cmdToken[1] ); return 0; } if ( strcmp( cmdToken[0], "quit" ) == 0 || strcmp( cmdToken[0], "q" ) == 0 ) { return -1; } if ( strcmp( cmdToken[0], "create" ) == 0 || strcmp( cmdToken[0], "make" ) == 0 || strcmp( cmdToken[0], "mk" ) == 0 ) { char myTicket[30]; if ( strlen( cmdToken[3] ) > 0 ) { snprintf( myTicket, sizeof( myTicket ), "%s", cmdToken[3] ); } else { makeTicket( myTicket ); } std::string fullPath = makeFullPath( cmdToken[2] ); doTicketOp( "create", myTicket, cmdToken[1], fullPath.c_str(), cmdToken[3] ); return 0; } if ( strcmp( cmdToken[0], "delete" ) == 0 ) { doTicketOp( "delete", cmdToken[1], cmdToken[2], cmdToken[3], cmdToken[4] ); return 0; } if ( strcmp( cmdToken[0], "mod" ) == 0 ) { doTicketOp( "mod", cmdToken[1], cmdToken[2], cmdToken[3], cmdToken[4] ); return 0; } if ( strcmp( cmdToken[0], "ls" ) == 0 ) { showTickets( cmdToken[1] ); return 0; } if ( strcmp( cmdToken[0], "ls-all" ) == 0 ) { printf( "Listing all of your tickets, even those for which the target collection\nor data-object no longer exists:\n" ); showTickets1( "basic", "" ); return 0; } if ( *cmdToken[0] != '\0' ) { printf( "unrecognized command, try 'help'\n" ); return -2; } return -3; } int main( int argc, char **argv ) { signal( SIGPIPE, SIG_IGN ); int status, i, j; rErrMsg_t errMsg; rodsArguments_t myRodsArgs; char *mySubName; int argOffset; int maxCmdTokens = 20; char *cmdToken[20]; int keepGoing; int firstTime; rodsLogLevel( LOG_ERROR ); status = parseCmdLineOpt( argc, argv, "vVhgrcGRCdulz:", 0, &myRodsArgs ); if ( status ) { printf( "Use -h for help.\n" ); exit( 1 ); } if ( myRodsArgs.help == True ) { usage( "" ); exit( 0 ); } if ( myRodsArgs.zone == True ) { strncpy( zoneArgument, myRodsArgs.zoneName, MAX_NAME_LEN ); } if ( myRodsArgs.longOption ) { longMode = 1; } argOffset = myRodsArgs.optind; if ( argOffset > 1 ) { if ( argOffset > 2 ) { if ( *argv[1] == '-' && *( argv[1] + 1 ) == 'z' ) { if ( *( argv[1] + 2 ) == '\0' ) { argOffset = 3; /* skip -z zone */ } else { argOffset = 2; /* skip -zzone */ } } else { argOffset = 1; /* Ignore the parseCmdLineOpt parsing as -d etc handled below*/ } } else { argOffset = 1; /* Ignore the parseCmdLineOpt parsing as -d etc handled below*/ } } status = getRodsEnv( &myEnv ); if ( status < 0 ) { rodsLog( LOG_ERROR, "main: getRodsEnv error. status = %d", status ); exit( 1 ); } strncpy( cwd, myEnv.rodsCwd, BIG_STR ); if ( strlen( cwd ) == 0 ) { strcpy( cwd, "/" ); } for ( i = 0; i < maxCmdTokens; i++ ) { cmdToken[i] = ""; } j = 0; for ( i = argOffset; i < argc; i++ ) { cmdToken[j++] = argv[i]; } #if defined(linux_platform) /* imeta cp -d TestFile1 -d TestFile3 comes in as: -d -d cp TestFile1 TestFile3 so switch it to: cp -d -d TestFile1 TestFile3 */ if ( cmdToken[0] != NULL && *cmdToken[0] == '-' ) { /* args were toggled, switch them back */ if ( cmdToken[1] != NULL && *cmdToken[1] == '-' ) { cmdToken[0] = argv[argOffset + 2]; cmdToken[1] = argv[argOffset]; cmdToken[2] = argv[argOffset + 1]; } else { cmdToken[0] = argv[argOffset + 1]; cmdToken[1] = argv[argOffset]; } } #else /* tested on Solaris, not sure other than Linux/Solaris */ /* imeta cp -d TestFile1 -d TestFile3 comes in as: cp -d TestFile1 -d TestFile3 so switch it to: cp -d -d TestFile1 TestFile3 */ if ( cmdToken[0] != NULL && cmdToken[1] != NULL && *cmdToken[1] == '-' && cmdToken[2] != NULL && cmdToken[3] != NULL && *cmdToken[3] == '-' ) { /* two args */ cmdToken[2] = argv[argOffset + 3]; cmdToken[3] = argv[argOffset + 2]; } #endif if ( strcmp( cmdToken[0], "help" ) == 0 || strcmp( cmdToken[0], "h" ) == 0 ) { usage( cmdToken[1] ); exit( 0 ); } if ( strcmp( cmdToken[0], "spass" ) == 0 ) { char scrambled[MAX_PASSWORD_LEN + 100]; if ( strlen( cmdToken[1] ) > MAX_PASSWORD_LEN - 2 ) { printf( "Password exceeds maximum length\n" ); } else { obfEncodeByKey( cmdToken[1], cmdToken[2], scrambled ); printf( "Scrambled form is:%s\n", scrambled ); } exit( 0 ); } // =-=-=-=-=-=-=- // initialize pluggable api table irods::api_entry_table& api_tbl = irods::get_client_api_table(); irods::pack_entry_table& pk_tbl = irods::get_pack_table(); init_api_table( api_tbl, pk_tbl ); Conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName, myEnv.rodsZone, 0, &errMsg ); if ( Conn == NULL ) { const char *myName = rodsErrorName( errMsg.status, &mySubName ); rodsLog( LOG_ERROR, "rcConnect failure %s (%s) (%d) %s", myName, mySubName, errMsg.status, errMsg.msg ); exit( 2 ); } status = clientLogin( Conn ); if ( status != 0 ) { if ( !debug ) { exit( 3 ); } } keepGoing = 1; firstTime = 1; while ( keepGoing ) { int status; status = doCommand( cmdToken ); if ( status == -1 ) { keepGoing = 0; } if ( firstTime ) { if ( status == 0 ) { keepGoing = 0; } if ( status == -2 ) { keepGoing = 0; lastCommandStatus = -1; } firstTime = 0; } if ( keepGoing ) { getInput( cmdToken, maxCmdTokens ); } } printErrorStack( Conn->rError ); rcDisconnect( Conn ); if ( lastCommandStatus != 0 ) { exit( 4 ); } exit( 0 ); } /* Print the main usage/help information. */ void usageMain() { char *msgs[] = { "Usage: iticket [-h] [command]", " -h This help", "Commands are:", " create read/write Object-Name [string] (create a new ticket)", " mod Ticket_string-or-id uses/expire string-or-none (modify restrictions)", " mod Ticket_string-or-id write-bytes-or-file number-or-0 (modify restrictions)", " mod Ticket_string-or-id add/remove host/user/group string (modify restrictions)", " ls [Ticket_string-or-id] (non-admins will see just your own)", " ls-all (list all your tickets, even with missing targets)", " delete ticket_string-or-id", " quit", " ", "Tickets are another way to provide access to iRODS data-objects (files) or", "collections (directories or folders). The 'iticket' command allows you", "to create, modify, list, and delete tickets. When you create a ticket", "its 15 character string is given to you which you can share with others.", "This is less secure than normal iRODS login-based access control, but", "is useful in some situations. See the 'ticket-based access' page on", "irods.org for more information.", " ", "A blank execute line invokes the interactive mode, where iticket", "prompts and executes commands until 'quit' or 'q' is entered.", "Like other unix utilities, a series of commands can be piped into it:", "'cat file1 | iticket' (maintaining one connection for all commands).", " ", "Use 'help command' for more help on a specific command.", "" }; int i; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { break; } printf( "%s\n", msgs[i] ); } printReleaseInfo( "iticket" ); } /* Print either main usage/help information, or some more specific information on particular commands. */ int usage( char *subOpt ) { int i; if ( *subOpt == '\0' ) { usageMain(); } else { if ( strcmp( subOpt, "create" ) == 0 ) { char *msgs[] = { " create read/write Object-Name [string] (create a new ticket)", "Create a new ticket for Object-Name, which is either a data-object (file)", "or a collection (directory). ", "Example: create read myFile", "The ticket string, which can be used for access, will be displayed.", "If 'string' is provided on the command line, it is the ticket-string to use", "as the ticket instead of a randomly generated string of characters.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "mod" ) == 0 ) { char *msgs[] = { " mod Ticket-id uses/expire string-or-none", "or mod Ticket-id add/remove host/user/group string (modify restrictions)", "Modify a ticket to use one of the specialized options. By default a", "ticket can be used by anyone (and 'anonymous'), from any host, and any", "number of times, and for all time (until deleted). You can modify it to", "add (or remove) these types of restrictions.", " ", " 'mod Ticket-id uses integer-or-0' will make the ticket only valid", "the specified number of times. Use 0 to remove this restriction.", " ", " 'mod Ticket-id write-file integer-or-0' will make the write-ticket only", "valid for writing the specified number of times. Use 0 to remove this", "restriction.", " ", " 'mod Ticket-id write-byte integer-or-0' will make the write-ticket only", "valid for writing the specified number of bytes. Use 0 to remove this", "restriction.", " ", " 'mod Ticket-id add/remove user Username' will make the ticket only valid", "when used by that particular iRODS user. You can use multiple mod commands", "to add more users to the allowed list.", " ", " 'mod Ticket-id add/remove group Groupname' will make the ticket only valid", "when used by iRODS users in that particular iRODS group. You can use", "multiple mod commands to add more groups to the allowed list.", " ", " 'mod Ticket-id add/remove host Host/IP' will make the ticket only valid", "when used from that particular host computer. Host (full DNS name) will be", "converted to the IP address for use in the internal checks or you can enter", "the IP address itself. 'iticket ls' will display the IP addresses.", "You can use multiple mod commands to add more hosts to the list.", " ", " 'mod Ticket-id expire date.time-or-0' will make the ticket only valid", "before the specified date-time. You can cancel this expiration by using", "'0'. The time is year-mo-da.hr:min:sec, for example: 2012-05-07.23:00:00", " ", " The Ticket-id is either the ticket object number or the ticket-string", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "delete" ) == 0 ) { char *msgs[] = { " delete Ticket-string", "Remove a ticket from the system. Access will no longer be allowed", "via the ticket-string.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "ls" ) == 0 ) { char *msgs[] = { " ls [Ticket_string-or-id]", "List the tickets owned by you or, for admin users, all tickets.", "Include a ticket-string or the ticket-id (object number) to list only one", "(in this case, a numeric string is assumed to be an id).", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "ls-all" ) == 0 ) { char *msgs[] = { " ls-all", "Similar to 'ls' (with no ticket string-or-id) but will list all of your", "tickets even if the target collection or data-object no longer exists.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "quit" ) == 0 ) { char *msgs[] = { " Exits the interactive mode", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } printf( "Sorry, either %s is an invalid command or the help has not been written yet\n", subOpt ); } return 0; }
30.731214
259
0.508354
cyverse
d746ebb5da20f0a352815e378faf61a85d2ae4df
12,073
cc
C++
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 808 $ * * $Date: 2013-02-20 13:25:03 +0100 (Wed, 20 Feb 2013) $ * * * \*===========================================================================*/ /** \file SmootherT.cc */ //============================================================================= // // CLASS SmootherT - IMPLEMENTATION // //============================================================================= #define OPENMESH_SMOOTHERT_C //== INCLUDES ================================================================= #include <OpenMesh/Core/Utils/vector_cast.hh> #include <OpenMesh/Tools/Smoother/SmootherT.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Smoother { //== IMPLEMENTATION ========================================================== template <class Mesh> SmootherT<Mesh>:: SmootherT(Mesh& _mesh) : mesh_(_mesh), skip_features_(false) { // request properties mesh_.request_vertex_status(); mesh_.request_face_normals(); mesh_.request_vertex_normals(); // custom properties mesh_.add_property(original_positions_); mesh_.add_property(original_normals_); mesh_.add_property(new_positions_); mesh_.add_property(is_active_); // default settings component_ = Tangential_and_Normal; continuity_ = C0; tolerance_ = -1.0; } //----------------------------------------------------------------------------- template <class Mesh> SmootherT<Mesh>:: ~SmootherT() { // free properties mesh_.release_vertex_status(); mesh_.release_face_normals(); mesh_.release_vertex_normals(); // free custom properties mesh_.remove_property(original_positions_); mesh_.remove_property(original_normals_); mesh_.remove_property(new_positions_); mesh_.remove_property(is_active_); } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: initialize(Component _comp, Continuity _cont) { typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end()); // store smoothing settings component_ = _comp; continuity_ = _cont; // update normals mesh_.update_face_normals(); mesh_.update_vertex_normals(); // store original points & normals for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { mesh_.property(original_positions_, v_it) = mesh_.point(v_it); mesh_.property(original_normals_, v_it) = mesh_.normal(v_it); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_active_vertices() { typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end()); // is something selected? bool nothing_selected(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.status(v_it).selected()) { nothing_selected = false; break; } // tagg all active vertices bool active; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { active = ((nothing_selected || mesh_.status(v_it).selected()) && !mesh_.is_boundary(v_it) && !mesh_.status(v_it).locked()); if ( skip_features_ ) { active = active && !mesh_.status(v_it).feature(); typename Mesh::VertexOHalfedgeIter voh_it(mesh_,v_it); for ( ; voh_it ; ++voh_it ) { // If the edge is a feature edge, skip the current vertex while smoothing if ( mesh_.status(mesh_.edge_handle(voh_it.handle())).feature() ) active = false; typename Mesh::FaceHandle fh1 = mesh_.face_handle(voh_it.handle() ); typename Mesh::FaceHandle fh2 = mesh_.face_handle(mesh_.opposite_halfedge_handle(voh_it.handle() ) ); // If one of the faces is a feature, lock current vertex if ( fh1.is_valid() && mesh_.status( fh1 ).feature() ) active = false; if ( fh2.is_valid() && mesh_.status( fh2 ).feature() ) active = false; } } mesh_.property(is_active_, v_it) = active; } // C1: remove one ring of boundary vertices if (continuity_ == C1) { typename Mesh::VVIter vv_it; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.is_boundary(v_it)) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.property(is_active_, vv_it) = false; } // C2: remove two rings of boundary vertices if (continuity_ == C2) { typename Mesh::VVIter vv_it; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { mesh_.status(v_it).set_tagged(false); mesh_.status(v_it).set_tagged2(false); } for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.is_boundary(v_it)) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.status(v_it).set_tagged(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.status(v_it).tagged()) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.status(v_it).set_tagged2(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { if (mesh_.status(v_it).tagged2()) mesh_.property(is_active_, vv_it) = false; mesh_.status(v_it).set_tagged(false); mesh_.status(v_it).set_tagged2(false); } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_relative_local_error(Scalar _err) { if (!mesh_.vertices_empty()) { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); // compute bounding box Point bb_min, bb_max; bb_min = bb_max = mesh_.point(v_it); for (++v_it; v_it!=v_end; ++v_it) { bb_min.minimize(mesh_.point(v_it)); bb_max.minimize(mesh_.point(v_it)); } // abs. error = rel. error * bounding-diagonal set_absolute_error(_err * (bb_max-bb_min).norm()); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_absolute_local_error(Scalar _err) { tolerance_ = _err; } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: disable_local_error_check() { tolerance_ = -1.0; } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: smooth(unsigned int _n) { // mark active vertices set_active_vertices(); // smooth _n iterations while (_n--) { compute_new_positions(); if (component_ == Tangential) project_to_tangent_plane(); else if (tolerance_ >= 0.0) local_error_check(); move_points(); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: compute_new_positions() { switch (continuity_) { case C0: compute_new_positions_C0(); break; case C1: compute_new_positions_C1(); break; case C2: break; } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: project_to_tangent_plane() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); // Normal should be a vector type. In some environment a vector type // is different from point type, e.g. OpenSG! typename Mesh::Normal translation, normal; for (; v_it != v_end; ++v_it) { if (is_active(v_it)) { translation = new_position(v_it)-orig_position(v_it); normal = orig_normal(v_it); normal *= dot(translation, normal); translation -= normal; translation += vector_cast<typename Mesh::Normal>(orig_position(v_it)); set_new_position(v_it, translation); } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: local_error_check() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); typename Mesh::Normal translation; typename Mesh::Scalar s; for (; v_it != v_end; ++v_it) { if (is_active(v_it)) { translation = new_position(v_it) - orig_position(v_it); s = fabs(dot(translation, orig_normal(v_it))); if (s > tolerance_) { translation *= (tolerance_ / s); translation += vector_cast<NormalType>(orig_position(v_it)); set_new_position(v_it, translation); } } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: move_points() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); for (; v_it != v_end; ++v_it) if (is_active(v_it)) mesh_.set_point(v_it, mesh_.property(new_positions_, v_it)); } //============================================================================= } // namespace Smoother } // namespace OpenMesh //=============================================================================
28.011601
109
0.495651
dmitriychunikhin
d74925529c06b5b049018b9b1fb8c6fb59cf5ca1
891
cpp
C++
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int longestStrChain(vector<string>& words) { set<pair<int, string>> lengthWordSet; unordered_map<string, int> dp; for(const string& WORD: words){ lengthWordSet.emplace(WORD.length(), WORD); dp[WORD] = 1; } int answer = 0; for(set<pair<int, string>>::const_reverse_iterator crit = lengthWordSet.crbegin(); crit != lengthWordSet.crend(); ++crit){ const string& WORD = crit->second; answer = max(dp[WORD], answer); for(int i = 0; i < (int)WORD.length(); ++i){ string nextWord = WORD.substr(0, i) + WORD.substr(i + 1); if(dp.count(nextWord)){ dp[nextWord] = max(1 + dp[WORD], dp[nextWord]); } } } return answer; } };
35.64
131
0.491582
Tudor67
d74a869695ab7d7bbc83137a4c4c78aa986ce401
497
cpp
C++
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define _ ios::sync_with_stdio(0);cin.tie(0); using namespace std; int main(){ long long int N,M; while(~scanf("%lld %lld",&N,&M)&&N){ int cnt[1024][128]={0}; int RUN=N*M-1; char str[1024]; getchar(); while(RUN--){ fgets(str,1024,stdin); for(int i=0;str[i]!='\n';i++){ cnt[i][str[i]]++; } } for(int i=0;i<1024;i++){ for(int j=0;j<128;j++){ if(cnt[i][j]%M){ printf("%c",j); j=128; } } } printf("\n"); } return 0; }
17.75
45
0.511066
tico88612
d74aa64be238d773ac772d3fe286d5bca7ea3b59
5,096
cpp
C++
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
/* Table.cpp By Jim Davies Jacobus Systems, Brighton & Hove, UK http://www.jacobus.co.uk Provided under the MIT license: https://github.com/jacobussystems/ArdJack/blob/master/LICENSE Copyright (c) 2019 James Davies, Jacobus Systems, Brighton & Hove, UK 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 "pch.h" #ifdef ARDUINO #define _strlwr strlwr #else #include "stdafx.h" #include <typeinfo> #endif #include "Globals.h" #include "Log.h" #include "Table.h" #include "Utils.h" Table::Table() { ColumnCount = 0; HorzLineChar = '_'; LeftMargin = 3; TotalWidth = 0; VertLineChar = '|'; for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++) ColumnDefs[i] = NULL; } Table::~Table() { for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++) { if (NULL != ColumnDefs[i]) { delete ColumnDefs[i]; ColumnDefs[i] = NULL; } } ColumnCount = 0; } bool Table::AddColumn(const char* caption, int width, int align, int padding) { TableColumnDef* colDef = new TableColumnDef(); ColumnDefs[ColumnCount++] = colDef; colDef->Alignment = align; strcpy(colDef->Caption, caption); colDef->Padding = padding; colDef->Width = width; TotalWidth += width; return true; } char* Table::AddLeftMargin(char* text) { Utils::RepeatChar(text, ' ', LeftMargin); return text; } char* Table::Cell(char* text, const char* colText, int col) { text[0] = NULL; if (col >= ColumnCount) return text; TableColumnDef* colDef = ColumnDefs[col]; if (Utils::StringIsNullOrEmpty(colText)) { // There's no text. return Utils::RepeatChar(text, ' ', colDef->Width); } char format[22]; char padding[82]; char temp[102]; // Left-side padding. Utils::RepeatChar(padding, ' ', colDef->Padding); strcat(text, padding); // Align the column text. int textWidth = colDef->Width - 2 * colDef->Padding; switch (colDef->Alignment) { case ARDJACK_HORZ_ALIGN_CENTRE: { int remainder = textWidth - (NULL != colText) ? Utils::StringLen(colText) : 0; if (remainder <= 0) strcat(text, colText); else { int spaces = remainder / 2; Utils::RepeatChar(padding, ' ', spaces); strcat(text, padding); strcat(text, colText); Utils::RepeatChar(padding, ' ', remainder - spaces); strcat(text, padding); } } break; case ARDJACK_HORZ_ALIGN_LEFT: sprintf(format, "%%-%ds", textWidth); sprintf(temp, format, (NULL != colText) ? colText : ""); strcat(text, temp); break; case ARDJACK_HORZ_ALIGN_RIGHT: sprintf(format, "%%%ds", textWidth); sprintf(temp, format, (NULL != colText) ? colText : ""); strcat(text, temp); break; } if (col < ColumnCount - 1) { // Right-side padding. Utils::RepeatChar(padding, ' ', colDef->Padding); strcat(text, padding); } return text; } char* Table::Header(char* text) { text[0] = NULL; AddLeftMargin(text); char temp[82]; for (int col = 0; col < ColumnCount; col++) { TableColumnDef* colDef = ColumnDefs[col]; Cell(temp, colDef->Caption, col); strcat(text, temp); } return text; } char* Table::HorizontalLine(char* text) { text[0] = NULL; AddLeftMargin(text); // A horizontal line. char temp[202]; Utils::RepeatChar(temp, HorzLineChar, TotalWidth); strcat(text, temp); return text; } char* Table::Row(char* text, const char* col0, const char* col1, const char* col2, const char* col3, const char* col4, const char* col5, const char* col6, const char* col7, const char* col8, const char* col9, const char* col10, const char* col11) { text[0] = NULL; AddLeftMargin(text); if (strlen(col0) == 0) return text; char work[102]; int col = 0; strcat(text, Cell(work, col0, col++)); strcat(text, Cell(work, col1, col++)); strcat(text, Cell(work, col2, col++)); strcat(text, Cell(work, col3, col++)); strcat(text, Cell(work, col4, col++)); strcat(text, Cell(work, col5, col++)); strcat(text, Cell(work, col6, col++)); strcat(text, Cell(work, col7, col++)); strcat(text, Cell(work, col8, col++)); strcat(text, Cell(work, col9, col++)); strcat(text, Cell(work, col10, col++)); strcat(text, Cell(work, col11, col++)); return text; }
22.350877
114
0.683673
jacobussystems
d74ef5b7b96345d05bde74f58bac90d4c0073d33
567
cpp
C++
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
1
2021-07-16T04:25:02.000Z
2021-07-16T04:25:02.000Z
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
4
2021-09-16T08:46:40.000Z
2022-03-12T05:12:20.000Z
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
null
null
null
// // Created by Spud on 7/16/21. // #include "npf/layout/ask.hpp" void Ask::populateBlocks(const JSON_ARRAY &array) { // TODO Comments blocks = std::vector<int>(array.Size()); for (JSON_ARRAY_ENTRY &entry : array) { if (entry.IsInt()) { blocks.push_back(entry.GetInt()); } } } void Ask::populateNPF(JSON_OBJECT entry) { // TODO Comments POPULATE_ARRAY(entry, "blocks", populateBlocks(entry["blocks"].GetArray());) POPULATE_OBJECT(entry, "attribution", Attribution attr; attr.populateNPF(entry["attribution"].GetObj()); attribution = attr;) }
22.68
77
0.689594
yeSpud
d75337db3fcf021e5b4f25798d76dac14a97140e
2,223
cpp
C++
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1 // Recursive and Iterative // TC: O(n) // SC: O(n) #include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class TreeNode { public: TreeNode *left; int val; TreeNode *right; TreeNode() { TreeNode(-1); } TreeNode(int _val) : left(NULL), val(_val), right(NULL) {} }; // Recusive void helper(TreeNode *root, map<int, pair<int, int>> &hash, int distance, int level) { if (root) { if (hash.find(distance) == hash.end() or level <= hash[distance].first) hash[distance] = {level, root->val}; helper(root->left, hash, distance - 1, level + 1); helper(root->right, hash, distance + 1, level + 1); } } vector<int> topView1(TreeNode *root) { vector<int> res{}; map<int, pair<int, int>> hash{}; helper(root, hash, 0, 0); for (auto i : hash) res.push_back(i.second.second); return res; } // Iterative vector<int> topView2(TreeNode *root) { vector<int> res{}; map<int, int> hash{}; queue<pair<TreeNode *, int>> qu; qu.push({root, 0}); while (!qu.empty()) { pair<TreeNode *, int> curr = qu.front(); qu.pop(); if (hash.find(curr.second) == hash.end()) hash[curr.second] = curr.first->val; if (curr.first->left) qu.push({curr.first->left, curr.second - 1}); if (curr.first->right) qu.push({curr.first->right, curr.second + 1}); } for (auto i : hash) res.push_back(i.second); return res; } void solve() { TreeNode *root = new TreeNode(10); root->left = new TreeNode(20); root->right = new TreeNode(30); root->left->left = new TreeNode(40); root->left->right = new TreeNode(60); vector<int> res; res = topView1(root); for (auto i : res) cout << i << " "; cout << endl; res = topView2(root); for (auto i : res) cout << i << " "; cout << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
21.171429
84
0.549708
premnaaath
d759f3acebc967a441b587b809c6d3107b3612b8
400
cpp
C++
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
1
2022-03-07T09:14:07.000Z
2022-03-07T09:14:07.000Z
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
// 06-point3.cpp : Point type with global operator+ defined import std.core; using namespace std; struct Point{ int x{}, y{}; }; Point operator+ (const Point& lhs, const Point& rhs) { Point result; result.x = lhs.x + rhs.x; result.y = lhs.y + rhs.y; return result; } int main() { Point p1{ 100, 200 }, p2{ 200, -50 }, p3; p3 = p1 + p2; cout << "p3 = (" << p3.x << ',' << p3.y << ")\n"; }
18.181818
59
0.5775
cpp-tutor
d75d1281bb923484e384a772e6140080715ab209
17,039
cxx
C++
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1
2017-04-27T17:28:15.000Z
2017-04-27T17:28:15.000Z
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
3
2017-07-13T10:54:50.000Z
2018-04-17T19:04:16.000Z
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
5
2017-03-29T12:21:12.000Z
2018-01-15T15:52:24.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <stdio.h> #include <TClonesArray.h> #include "AliAlgSens.h" #include "AliAlgAux.h" #include "AliLog.h" #include "AliGeomManager.h" #include "AliExternalTrackParam.h" #include "AliAlgPoint.h" #include "AliAlgDet.h" #include "AliAlgDOFStat.h" ClassImp(AliAlgSens) using namespace AliAlgAux; using namespace TMath; //_________________________________________________________ AliAlgSens::AliAlgSens(const char* name,Int_t vid, Int_t iid) : AliAlgVol(name,iid) ,fSID(0) ,fDet(0) ,fMatClAlg() ,fMatClAlgReco() { // def c-tor SetVolID(vid); fAddError[0] = fAddError[1] = 0; fConstrChild = 0; // sensors don't have children } //_________________________________________________________ AliAlgSens::~AliAlgSens() { // d-tor } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame // parameters in TGeoHMatrix convention. // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; // variation matrix in tracking frame for variation in sensor LOCAL frame GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. // NO check of parentship is done! // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // // 1st we need a matrix for transition between child and parent TRACKING frames // Let TRA,LOC are positions in tracking and local frame of parent, linked as LOC=T2L*TRA // and tra,loc are positions in tracking and local frame of child, linked as loc=t2l*tra // The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g // local2global matrices for parent and child // // Then, TRA = T2L^-1*LOC = T2L^-1*R*loc = T2L^-1*R*t2l*tra // -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l // Note that l2g*t2l are tracking to global matrices TGeoHMatrix matRel,t2gP; GetMatrixT2G(matRel); // t2g matrix of child parent->GetMatrixT2G(t2gP); // t2g matrix of parent matRel.MultiplyLeft(&t2gP.Inverse()); // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // calculate point position derivatives in tracking frame of sensor // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame(); switch(frame) { case kLOC : parent ? DPosTraDParGeomLOC(pnt,deriv,parent) : DPosTraDParGeomLOC(pnt,deriv); break; case kTRA : parent ? DPosTraDParGeomTRA(pnt,deriv,parent) : DPosTraDParGeomTRA(pnt,deriv); break; default : AliErrorF("Alignment frame %d is not implemented",parent->GetVarFrame()); break; } } //__________________________________________________________________ void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: // loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L Delta2Matrix(matMod, delta); matMod.Multiply(&GetMatrixT2L()); } //__________________________________________________________________ void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: // loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta Delta2Matrix(matMod, delta); matMod.MultiplyLeft(&GetMatrixT2L()); } //__________________________________________________________________ void AliAlgSens::AddChild(AliAlgVol*) { AliFatalF("Sensor volume cannot have childs: id=%d %s",GetVolID(),GetName()); } //__________________________________________________________________ Int_t AliAlgSens::Compare(const TObject* b) const { // compare VolIDs return GetUniqueID()<b->GetUniqueID() ? -1 : 1; } //__________________________________________________________________ void AliAlgSens::SetTrackingFrame() { // define tracking frame of the sensor // AliWarningF("Generic method called for %s",GetSymName()); double tra[3]={0},glo[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,glo); fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); fAlp = ATan2(glo[1],glo[0]); AliAlgAux::BringToPiPM(fAlp); // } //____________________________________________ void AliAlgSens::Print(const Option_t *opt) const { // print info TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n", CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp, fAddError[0],fAddError[1],fNProcPoints); printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); for (int i=0;i<kNDOFGeom;i++) printf("%d",IsFreeDOF(i) ? 1:0); printf("} in %s frame\n",fgkFrameName[fVarFrame]); // // // if (opts.Contains("par") && fParVals) { printf(" Lb: "); for (int i=0;i<fNDOFs;i++) printf("%10d ",GetParLab(i)); printf("\n"); printf(" Vl: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParVal(i)); printf("\n"); printf(" Er: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParErr(i)); printf("\n"); } // if (opts.Contains("mat")) { // print matrices printf("L2G ideal : "); GetMatrixL2GIdeal().Print(); printf("L2G misalign: "); GetMatrixL2G().Print(); printf("L2G RecoTime: "); GetMatrixL2GReco().Print(); printf("T2L : "); GetMatrixT2L().Print(); printf("ClAlg : "); GetMatrixClAlg().Print(); printf("ClAlgReco: "); GetMatrixClAlgReco().Print(); } // } //____________________________________________ void AliAlgSens::PrepareMatrixT2L() { // extract from geometry T2L matrix const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); if (!t2l) { Print("long"); AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); } SetMatrixT2L(*t2l); // } //____________________________________________ void AliAlgSens::PrepareMatrixClAlg() { // prepare alignment matrix in the LOCAL frame: delta = Gideal^-1 * G TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); ma *= GetMatrixL2G(); SetMatrixClAlg(ma); // } //____________________________________________ void AliAlgSens::PrepareMatrixClAlgReco() { // prepare alignment matrix used at reco time TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); ma *= GetMatrixL2GReco(); SetMatrixClAlgReco(ma); // } //____________________________________________ void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const { // update fDet->UpdatePointByTrackInfo(pnt,t); } //____________________________________________ void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration // deriv[0]=deriv[1]=deriv[2]=0; } //______________________________________________________ Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points if (st) FillDOFStat(st); return fNProcPoints; } //_________________________________________________________________ void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) { // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. // On top of what each volume does, also update misalignment matrix inverse // AliAlgVol::UpdateL2GRecoMatrices(algArr,cumulDelta); PrepareMatrixClAlgReco(); // } /* //_________________________________________________________________ AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) { // dummy converter AliError("Generic method, must be implemented in specific sensor"); return 0; } */ //_________________________________________________________________ void AliAlgSens::ApplyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents // const AliAlgVol* vol = this; TGeoHMatrix deltaG; // create global combined delta: // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy while(vol) { TGeoHMatrix deltaGJ; vol->CreateAlignmenMatrix(deltaGJ); deltaG.MultiplyLeft(&deltaGJ); vol = vol->GetParent(); } // // update misaligned L2G matrix deltaG *= GetMatrixL2GIdeal(); SetMatrixL2G(deltaG); // // update local misalignment matrix PrepareMatrixClAlg(); // } /* //_________________________________________________________________ void AliAlgSens::ApplyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents double delta[kNDOFGeom]={0}; // TGeoHMatrix matMod; // // sensor proper variation GetParValGeom(delta); IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta); fMatClAlg.MultiplyLeft(&matMod); // AliAlgVol* parent = this; while ((parent==parent->GetParent())) { // this is the matrix for transition from sensor to parent volume frame parent->GetParValGeom(delta); TGeoHMatrix matRel,t2gP; if (parent->IsFrameTRA()) { GetMatrixT2G(matRel); // t2g matrix of child parent->GetMatrixT2G(t2gP); // t2g matrix of parent matRel.MultiplyLeft(&t2gP.Inverse()); GetDeltaT2LmodTRA(matMod, delta, matRel); } else { matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); GetDeltaT2LmodLOC(matMod, delta, matRel); } fMatClAlg.MultiplyLeft(&matMod); } // } */
34.98768
113
0.681671
AllaMaevskaya
d76039ede79217000084ddf0cc1897ac8d06ac15
1,856
hpp
C++
lib/primitive/src/thread/Task.hpp
tkeycoin/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
3
2020-01-24T04:45:14.000Z
2020-06-30T13:49:58.000Z
lib/primitive/src/thread/Task.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-06-18T15:51:36.000Z
2020-06-20T17:25:45.000Z
lib/primitive/src/thread/Task.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-10-20T06:50:13.000Z
2020-10-20T06:50:13.000Z
// Copyright (c) 2017-2019 Tkeycoin Dao. All rights reserved. // Copyright (c) 2019-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved. // Website: www.tkeycoin.com // // 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. // // Task.hpp #pragma once #include <functional> #include <chrono> #include <ucontext.h> #include "../utils/Shareable.hpp" class Task final { public: using Func = std::function<void()>; using Clock = std::chrono::steady_clock; using Duration = Clock::duration; using Time = Clock::time_point; private: Func _function; Time _until; const char* _label; mutable ucontext_t* _parentTaskContext; public: explicit Task(Func&& function, Time until, const char* label = "-"); virtual ~Task() = default; // Разрешаем перемещение Task(Task&& that) noexcept; Task& operator=(Task&& that) noexcept; // Запрещаем любое копирование Task(const Task&) = delete; Task& operator=(const Task&) = delete; // Планирование времени const Time& until() const { return _until; } // Метка задачи (имя, название и т.п., для отладки) const char* label() const { return _label; } // Сравнение по времени bool operator<(const Task &that) const { return this->_until > that._until; } // Исполнение void execute(); // Пустышка (остаток от перемещения) bool isDummy() const { return !_function; } };
22.361446
78
0.706897
tkeycoin
d762c3a4125cc44871fbc25d7c1e6a4bd27167c5
3,852
cpp
C++
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "ShooterRecord.h" #include "Msg.h" #include "Resource.h" #define SEPARATOR ";" ShooterRecord::ShooterRecord( LPCTSTR membership_number /* = NULL */, LPCTSTR shooter_name /* = NULL */, LPCTSTR license /* = NULL */, LPCTSTR club /* = NULL */, LPCTSTR category /* = NULL */, __time64_t license_expiry_time /* = 0 */) : m_membership_number(membership_number), m_shooter_name(shooter_name), m_license(license), m_club(club), m_category(category), m_license_expiry_time(license_expiry_time) { } ShooterRecord::ShooterRecord( const ShooterRecord& rec) : m_membership_number(rec.m_membership_number), m_shooter_name(rec.m_shooter_name), m_license(rec.m_license), m_club(rec.m_club), m_category(rec.m_category), m_license_expiry_time(rec.m_license_expiry_time) { } ShooterRecord::~ShooterRecord(void) { } bool ShooterRecord::operator==(const ShooterRecord& rec) const { return ( m_membership_number == rec.m_membership_number && m_shooter_name == rec.m_shooter_name && m_license == rec.m_license && m_club == rec.m_club && m_category == rec.m_category && m_license_expiry_time == rec.m_license_expiry_time ); } CStringA ShooterRecord::ToAsciiString() const { CStringA result; char buf[256]; result += m_membership_number; result += SEPARATOR; result += m_shooter_name; result += SEPARATOR; result += m_license; result += SEPARATOR; result += m_club; result += SEPARATOR; result += m_category; if (!_i64toa_s(m_license_expiry_time, buf, 256, 10)) { result += SEPARATOR; result += buf; } return result; } void ShooterRecord::FromAsciiString(const char * str) { CStringA s(str); CStringA token; int curPos = 0; bool parseError = false; if ( !parseError ) { // parse membership number token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_membership_number = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Membership Number"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse shooter name token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_shooter_name = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Shooter Name"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse license token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_license = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse club token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_club = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Club"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse category token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_category = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Category"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_license_expiry_time = _atoi64((const char *) token); } // optional - don't consider this a failure //else //{ // parseError = true; // CString wholestr(str); // ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License Expiry Time"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); //} } } CString ShooterRecord::ToSearchResultString() const { CString result; result.Format(_T("%-25s %-16s %-20s"), m_shooter_name, m_membership_number, m_club ); return result; }
21.281768
118
0.678089
sbweeden
d7637633be8552f113c0fe6ee190722bd318a079
29,874
cpp
C++
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
2
2021-12-28T15:49:43.000Z
2022-03-27T08:05:12.000Z
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
null
null
null
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
null
null
null
#include "eventmanager_p.h" #include "cachemanager_p.h" #include "interfacemanager_p.h" #include "client.h" #include "channel.h" #include "connection.h" #include "exception.h" #include "teamspeakevents.h" namespace TeamSpeakSdk { class EventManagerPrivate { public: EventManagerPrivate() { memset(&clientUIFunctions, 0, sizeof(struct ClientUIFunctions)); } ~EventManagerPrivate() { } ClientUIFunctions clientUIFunctions; // ClientUIFunctionsRare clientUIRareFunctions; }; static EventManager* m_instance = Q_NULLPTR; static EventManagerPrivate* d = Q_NULLPTR; EventManager* EventManager::instance() { return m_instance; } EventManager::~EventManager() { m_instance = Q_NULLPTR; delete d;d = Q_NULLPTR; } EventManager::EventManager(QObject* parent) : QObject(parent) { d = new EventManagerPrivate; d->clientUIFunctions.onConnectStatusChangeEvent = onConnectStatusChangeEventWrapper; d->clientUIFunctions.onServerProtocolVersionEvent = onServerProtocolVersionEventWrapper; d->clientUIFunctions.onNewChannelEvent = onNewChannelEventWrapper; d->clientUIFunctions.onNewChannelCreatedEvent = onNewChannelCreatedEventWrapper; d->clientUIFunctions.onDelChannelEvent = onDelChannelEventWrapper; d->clientUIFunctions.onChannelMoveEvent = onChannelMoveEventWrapper; d->clientUIFunctions.onUpdateChannelEvent = onUpdateChannelEventWrapper; d->clientUIFunctions.onUpdateChannelEditedEvent = onUpdateChannelEditedEventWrapper; d->clientUIFunctions.onUpdateClientEvent = onUpdateClientEventWrapper; d->clientUIFunctions.onClientMoveEvent = onClientMoveEventWrapper; d->clientUIFunctions.onClientMoveSubscriptionEvent = onClientMoveSubscriptionEventWrapper; d->clientUIFunctions.onClientMoveTimeoutEvent = onClientMoveTimeoutEventWrapper; d->clientUIFunctions.onClientMoveMovedEvent = onClientMoveMovedEventWrapper; d->clientUIFunctions.onClientKickFromChannelEvent = onClientKickFromChannelEventWrapper; d->clientUIFunctions.onClientKickFromServerEvent = onClientKickFromServerEventWrapper; d->clientUIFunctions.onClientIDsEvent = onClientIDsEventWrapper; d->clientUIFunctions.onClientIDsFinishedEvent = onClientIDsFinishedEventWrapper; d->clientUIFunctions.onServerEditedEvent = onServerEditedEventWrapper; d->clientUIFunctions.onServerUpdatedEvent = onServerUpdatedEventWrapper; d->clientUIFunctions.onServerErrorEvent = onServerErrorEventWrapper; d->clientUIFunctions.onServerStopEvent = onServerStopEventWrapper; d->clientUIFunctions.onTextMessageEvent = onTextMessageEventWrapper; d->clientUIFunctions.onTalkStatusChangeEvent = onTalkStatusChangeEventWrapper; d->clientUIFunctions.onIgnoredWhisperEvent = onIgnoredWhisperEventWrapper; d->clientUIFunctions.onConnectionInfoEvent = onConnectionInfoEventWrapper; d->clientUIFunctions.onServerConnectionInfoEvent = onServerConnectionInfoEventWrapper; d->clientUIFunctions.onChannelSubscribeEvent = onChannelSubscribeEventWrapper; d->clientUIFunctions.onChannelSubscribeFinishedEvent = onChannelSubscribeFinishedEventWrapper; d->clientUIFunctions.onChannelUnsubscribeEvent = onChannelUnsubscribeEventWrapper; d->clientUIFunctions.onChannelUnsubscribeFinishedEvent = onChannelUnsubscribeFinishedEventWrapper; d->clientUIFunctions.onChannelDescriptionUpdateEvent = onChannelDescriptionUpdateEventWrapper; d->clientUIFunctions.onChannelPasswordChangedEvent = onChannelPasswordChangedEventWrapper; d->clientUIFunctions.onPlaybackShutdownCompleteEvent = onPlaybackShutdownCompleteEventWrapper; d->clientUIFunctions.onSoundDeviceListChangedEvent = onSoundDeviceListChangedEventWrapper; d->clientUIFunctions.onEditPlaybackVoiceDataEvent = onEditPlaybackVoiceDataEventWrapper; d->clientUIFunctions.onEditPostProcessVoiceDataEvent = onEditPostProcessVoiceDataEventWrapper; d->clientUIFunctions.onEditMixedPlaybackVoiceDataEvent = onEditMixedPlaybackVoiceDataEventWrapper; d->clientUIFunctions.onEditCapturedVoiceDataEvent = onEditCapturedVoiceDataEventWrapper; d->clientUIFunctions.onCustom3dRolloffCalculationClientEvent = onCustom3dRolloffCalculationClientEventWrapper; d->clientUIFunctions.onCustom3dRolloffCalculationWaveEvent = onCustom3dRolloffCalculationWaveEventWrapper; d->clientUIFunctions.onUserLoggingMessageEvent = onUserLoggingMessageEventWrapper; d->clientUIFunctions.onProvisioningSlotRequestResultEvent = onProvisioningSlotRequestResultEventWrapper; d->clientUIFunctions.onCheckServerUniqueIdentifierEvent = onCheckServerUniqueIdentifierEventWrapper; d->clientUIFunctions.onFileTransferStatusEvent = onFileTransferStatusEventWrapper; d->clientUIFunctions.onFileListEvent = onFileListEventWrapper; d->clientUIFunctions.onFileListFinishedEvent = onFileListFinishedEventWrapper; d->clientUIFunctions.onFileInfoEvent = onFileInfoEventWrapper; d->clientUIFunctions.onCustomPacketEncryptEvent = onCustomPacketEncryptEventWrapper; d->clientUIFunctions.onCustomPacketDecryptEvent = onCustomPacketDecryptEventWrapper; d->clientUIFunctions.onClientPasswordEncrypt = onClientPasswordEncryptEventWrapper; m_instance = this; } ClientUIFunctions* EventManager::clientUIFunctions() { return &d->clientUIFunctions; } ClientUIFunctionsRare* EventManager::clientUIFunctionsRare() { return nullptr; } void EventManager::onConnectStatusChangeEventWrapper(uint64 serverId, int newStatus, uint errorNumber) { auto server = Library::getServer(serverId); auto event = new ConnectStatusChangedEvent; event->newStatus = static_cast<ConnectStatus>(newStatus); event->errorNumber = ReturnCode(errorNumber); QCoreApplication::postEvent(server, event); } void EventManager::onServerProtocolVersionEventWrapper(uint64 serverId, int protocolVersion) { auto server = Library::getServer(serverId); auto event = new ServerProtocolVersionEvent; event->protocolVersion = protocolVersion; QCoreApplication::postEvent(server, event); } void EventManager::onNewChannelEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID) { auto server = Library::getServer(serverId); auto event = new NewChannelEvent; event->channel = server->getChannel(channelID); event->channelParent = server->getChannel(channelParentID); QCoreApplication::postEvent(server, event); } void EventManager::onNewChannelCreatedEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new NewChannelCreatedEvent; event->channel = server->getChannel(channelID); event->channelParent = server->getChannel(channelParentID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onDelChannelEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelDeletedEvent; event->channel = server->getChannel(channelID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onChannelMoveEventWrapper(uint64 serverId, uint64 channelID, uint64 newChannelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelMovedEvent; event->channel = server->getChannel(channelID); event->newChannelParent = server->getChannel(newChannelParentID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateChannelEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelUpdatedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateChannelEditedEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelEditedEvent; event->channel = server->getChannel(channelID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateClientEventWrapper(uint64 serverId, uint16 clientID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ClientUpdatedEvent; event->client = server->getClient(clientID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* moveMessage) { auto server = Library::getServer(serverId); auto event = new ClientMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->moveMessage = utils::to_string(moveMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveSubscriptionEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility) { auto server = Library::getServer(serverId); auto event = new SubscriptionClientMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveTimeoutEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* timeoutMessage) { auto server = Library::getServer(serverId); auto event = new ClientMoveTimeoutEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->timeoutMessage = utils::to_string(timeoutMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveMovedEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 moverID, const char* moverName, const char* moverUniqueIdentifier, const char* moveMessage) { auto server = Library::getServer(serverId); auto event = new ClientMoverMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->mover = server->getClient(moverID); event->moverName = utils::to_string(moverName); event->moverUniqueIdentifier = utils::to_string(moverUniqueIdentifier); event->moveMessage = utils::to_string(moveMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientKickFromChannelEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage) { auto server = Library::getServer(serverId); auto event = new ClientKickFromChannelEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->kicker = server->getClient(kickerID); event->kickerName = utils::to_string(kickerName); event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier); event->kickMessage = utils::to_string(kickMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientKickFromServerEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage) { auto server = Library::getServer(serverId); auto event = new ClientKickFromServerEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->kicker = server->getClient(kickerID); event->kickerName = utils::to_string(kickerName); event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier); event->kickMessage = utils::to_string(kickMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientIDsEventWrapper(uint64 serverId, const char* uniqueClientIdentifier, uint16 clientID, const char* clientName) { auto server = Library::getServer(serverId); auto event = new ClientIDsReceivedEvent; event->client = server->getClient(clientID); event->clientName = utils::to_string(clientName); event->uniqueClientIdentifier = utils::to_string(uniqueClientIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onClientIDsFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ClientIDsFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onServerEditedEventWrapper(uint64 serverId, uint16 editerID, const char* editerName, const char* editerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ServerEditedEvent; event->editer = server->getClient(editerID); event->editerName = utils::to_string(editerName); event->editerUniqueIdentifier = utils::to_string(editerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onServerUpdatedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ServerUpdatedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onServerErrorEventWrapper(uint64 serverId, const char* errorMessage, uint error, const char* returnCode, const char* extraMessage) { auto server = Library::getServer(serverId); auto event = new ServerErrorEvent; event->error = static_cast<ReturnCode>(error); event->returnCode = utils::to_string(returnCode); event->errorMessage = utils::to_string(errorMessage); event->extraMessage = utils::to_string(extraMessage); QCoreApplication::postEvent(server, event); } void EventManager::onServerStopEventWrapper(uint64 serverId, const char* shutdownMessage) { auto server = Library::getServer(serverId); auto event = new ServerStopEvent; event->shutdownMessage = utils::to_string(shutdownMessage); QCoreApplication::postEvent(server, event); } void EventManager::onTextMessageEventWrapper(uint64 serverId, uint16 targetMode, uint16 toID, uint16 fromID, const char* fromName, const char* fromUniqueIdentifier, const char* message) { auto server = Library::getServer(serverId); auto event = new TextMessageEvent; event->from = server->getClient(fromID); event->targetMode = static_cast<TargetMode>(targetMode); switch (event->targetMode) { case TargetMode::Client: event->to = server->getClient(toID); break; case TargetMode::Channel: case TargetMode::Server: default: event->to = Q_NULLPTR; break; } event->message = utils::to_string(message); event->fromName = utils::to_string(fromName); event->fromUniqueIdentifier = utils::to_string(fromUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onTalkStatusChangeEventWrapper(uint64 serverId, int status, int isReceivedWhisper, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new TalkStatusChangeEvent; event->client = server->getClient(clientID); event->status = static_cast<TalkStatus>(status); event->isReceivedWhisper = isReceivedWhisper != 0; QCoreApplication::postEvent(server, event); } void EventManager::onIgnoredWhisperEventWrapper(uint64 serverId, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new WhisperIgnoredEvent; event->client = server->getClient(clientID); QCoreApplication::postEvent(server, event); } void EventManager::onConnectionInfoEventWrapper(uint64 serverId, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new ConnectionInfoEvent; event->client = server->getClient(clientID); QCoreApplication::postEvent(server, event); } void EventManager::onServerConnectionInfoEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ServerConnectionInfoEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelSubscribeEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelSubscribedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelSubscribeFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ChannelSubscribesFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelUnsubscribeEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelUnsubscribedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelUnsubscribeFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ChannelUnsubscribesFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelDescriptionUpdateEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelDescriptionUpdatedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelPasswordChangedEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelPasswordChangedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onPlaybackShutdownCompleteEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new PlaybackShutdownCompletedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onSoundDeviceListChangedEventWrapper(const char* modeID, int playOrCap) { auto event = new SoundDeviceListChangedEvent; event->modeID = utils::to_string(modeID); event->playOrCap = playOrCap != 0; QCoreApplication::postEvent(Library::instance(), event); } void EventManager::onUserLoggingMessageEventWrapper(const char* logmessage, int logLevel, const char* logChannel, uint64 logID, const char* logTime, const char* completeLogString) { auto server = Library::getServer(logID); auto event = new UserLoggingMessageEvent; event->logLevel = static_cast<LogLevel>(logLevel); event->logmessage = utils::to_string(logmessage); event->logChannel = utils::to_string(logChannel); event->logTime = utils::to_string(logTime); event->completeLogString = utils::to_string(completeLogString); QCoreApplication::postEvent(Library::instance(), event); } void EventManager::onFileTransferStatusEventWrapper(uint16 transferID, uint status, const char* statusMessage, uint64 remotefileSize, uint64 serverId) { auto server = Library::getServer(serverId); auto event = new FileTransferStatusReceivedEvent; event->transfer = server->getTransfer(transferID); event->status = static_cast<ReturnCode>(status); event->statusMessage = utils::to_string(statusMessage); event->remotefileSize = remotefileSize; QCoreApplication::postEvent(server, event); } void EventManager::onFileListEventWrapper(uint64 serverId, uint64 channelID, const char* path, const char* name, uint64 size, uint64 datetime, int type, uint64 incompletesize, const char* returnCode) { auto server = Library::getServer(serverId); auto event = new FileListReceivedEvent; event->channel = server->getChannel(channelID); event->path = utils::to_string(path); event->name = utils::to_string(name); event->size = size; event->incompletesize = incompletesize; event->type = static_cast<FileListType>(type); event->datetime = utils::to_date_time(datetime); event->returnCode = utils::to_string(returnCode); QCoreApplication::postEvent(server, event); } void EventManager::onFileListFinishedEventWrapper(uint64 serverId, uint64 channelID, const char* path) { auto server = Library::getServer(serverId); auto event = new FileListFinishedEvent; event->channel = server->getChannel(channelID); event->path = utils::to_string(path); QCoreApplication::postEvent(server, event); } void EventManager::onFileInfoEventWrapper(uint64 serverId, uint64 channelID, const char* name, uint64 size, uint64 datetime) { auto server = Library::getServer(serverId); auto event = new FileInfoReceivedEvent; event->channel = server->getChannel(channelID); event->name = utils::to_string(name); event->size = size; event->datetime = utils::to_date_time(datetime); QCoreApplication::postEvent(server, event); } void EventManager::onEditPlaybackVoiceDataEventWrapper(uint64 serverId, uint16 clientID, short* samples, int sampleCount, int channels) { auto handler = Library::editPlaybackVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); auto vector = utils::make_vector<short>(samples, sampleCount); auto result = handler(client, vector, channels); utils::copy_vector(result, samples); } void EventManager::onEditPostProcessVoiceDataEventWrapper( uint64 serverId, uint16 clientID, short* samples, int sampleCount, int channels, const uint* channelSpeakers, uint* channelFillMask) { auto handler = Library::editPostProcessVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); auto vector_samples = utils::make_vector<short>(samples, sampleCount); auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels); auto result = handler(client, vector_samples, vector_speakers, (Speakers*)channelFillMask); if (0 != *channelFillMask) utils::copy_vector(result, samples); } void EventManager::onEditMixedPlaybackVoiceDataEventWrapper( uint64 serverId, short* samples, int sampleCount, int channels, const uint* channelSpeakers, uint* channelFillMask) { auto handler = Library::editMixedPlaybackVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto vector_samples = utils::make_vector<short>(samples, sampleCount * channels); auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels); auto result = handler(server, vector_samples, vector_speakers, (Speakers*)channelFillMask); if (0 != *channelFillMask) utils::copy_vector(result, samples); } void EventManager::onEditCapturedVoiceDataEventWrapper(uint64 serverId, short* samples, int sampleCount, int channels, int* bytes) { auto handler = Library::editCapturedVoiceDataHandler(); if (!handler) return; // TODO: handler call bool edited = (*bytes & 1) == 1; bool cancel = (*bytes & 2) == 0; auto server = Library::getServer(serverId); auto vector_samples = utils::make_vector<short>(samples, sampleCount); auto result = handler(server, vector_samples, channels, edited, cancel); if (edited && cancel == false) utils::copy_vector(result, samples); *bytes = (edited ? 1 : 0) | (cancel ? 0 : 2); } void EventManager::onCustom3dRolloffCalculationClientEventWrapper(uint64 serverId, uint16 clientID, float distance, float* volume) { auto handler = Library::custom3dRolloffCalculationClientHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); handler(client, distance, volume); } void EventManager::onCustom3dRolloffCalculationWaveEventWrapper(uint64 serverId, uint64 waveHandle, float distance, float* volume) { auto handler = Library::custom3dRolloffCalculationWaveHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto wave = server->getWaveHandle(waveHandle); handler(wave, distance, volume); } void EventManager::onProvisioningSlotRequestResultEventWrapper( uint error, uint64 requestHandle, const char* connectionKey) { auto key = utils::to_string(connectionKey); } void EventManager::onCheckServerUniqueIdentifierEventWrapper(uint64 serverId, const char* serverUniqueIdentifier, int* cancelConnect) { auto handler = Library::checkUniqueIdentifierHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto uniqueIdentifier = utils::to_string(serverUniqueIdentifier); auto result = handler(server, uniqueIdentifier); *cancelConnect = result; } #define CUSTOM_CRYPT_KEY 123 void EventManager::onCustomPacketEncryptEventWrapper(char** dataToSend, uint* sizeOfData) { auto handler = Library::customPacketEncryptHandler(); if (!handler) { #if defined(CUSTOM_CRYPT_KEY) for (uint i = 0; i < *sizeOfData; ++i) { (*dataToSend)[i] ^= CUSTOM_CRYPT_KEY; } #endif } else { // TODO: handler call } } void EventManager::onCustomPacketDecryptEventWrapper(char** dataReceived, uint* dataReceivedSize) { auto handler = Library::customPacketDecryptHandler(); if (!handler) { #if defined(CUSTOM_CRYPT_KEY) for (uint i = 0; i < *dataReceivedSize; ++i) { (*dataReceived)[i] ^= CUSTOM_CRYPT_KEY; } #endif } else { // TODO: handler call } } void EventManager::onClientPasswordEncryptEventWrapper(uint64 serverId, const char* plaintext, char* encryptedText, int encryptedTextByteSize) { auto handler = Library::clientPasswordEncryptHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto text = utils::to_byte(plaintext); auto result = handler(server, text, encryptedTextByteSize - 1); ::memcpy(encryptedText, result.data(), result.size()); } void __init_event_manager() { (void) new EventManager(qApp); } Q_COREAPP_STARTUP_FUNCTION(__init_event_manager) } // namespace TeamSpeakSdk
42.254597
248
0.726451
faming-wang
d76945ee00b8639a631774d8377a1473c992a5f6
314
cpp
C++
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#include "i_core.h" #include "../../../patterns.h" #include <utils/hooking/hooking.h> namespace SDK { namespace ue::sys::core { C_Core *I_Core::GetInstance() { return hook::this_call<C_Core *>(gPatterns.I_Core__GetInstance); } } // namespace ue::sys::core } // namespace SDK
22.428571
76
0.61465
mufty
d76a3f4b3a02f77886bcb78b79c0e41808f40084
372
cpp
C++
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstring> using std::cin; using std::cout; using std::endl; using std::cerr; using std::begin; using std::end; using std::strcmp; using std::strcpy; using std::strcat; int main() { const char a[] = "A test"; const char b[] = "about it"; char c[16]; strcpy(c, a); strcat(c, " "); strcat(c, b); cout << c << endl; }
21.882353
66
0.591398
Raymain1944
d772d7f0302d2b76fc471771253741f96497c7ae
4,732
cpp
C++
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------------------- // COPYRIGHT NOTICE // ---------------------------------------------------------------------------------------- // // The Source Code Store LLC // ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC // ActiveX Control // Copyright (c) 2002-2017 The Source Code Store LLC // // All Rights Reserved. No parts of this file may be reproduced, modified or transmitted // in any form or by any means without the written permission of the author. // // ---------------------------------------------------------------------------------------- #include "stdafx.h" #include "clsXML.h" #include "TaskBaseline_C.h" IMPLEMENT_DYNCREATE(TaskBaseline_C, CCmdTarget) //{5A5680D4-68DB-421F-972C-16C1C2B35985} static const IID IID_ITaskBaseline_C = { 0x5A5680D4, 0x68DB, 0x421F, { 0x97, 0x2C, 0x16, 0xC1, 0xC2, 0xB3, 0x59, 0x85} }; //{C8E849CD-4B77-47AF-97E1-56281F8FB6F1} IMPLEMENT_OLECREATE_FLAGS(TaskBaseline_C, "MSP2007.TaskBaseline_C", afxRegApartmentThreading, 0xC8E849CD, 0x4B77, 0x47AF, 0x97, 0xE1, 0x56, 0x28, 0x1F, 0x8F, 0xB6, 0xF1) BEGIN_DISPATCH_MAP(TaskBaseline_C, CCmdTarget) DISP_PROPERTY_EX_ID(TaskBaseline_C, "Count", 1, odl_GetCount, SetNotSupported, VT_I4) DISP_PROPERTY_PARAM_ID(TaskBaseline_C, "Item", 2, odl_Item, SetNotSupported, VT_DISPATCH, VTS_BSTR) DISP_FUNCTION_ID(TaskBaseline_C, "Add", 3, odl_Add, VT_DISPATCH, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Clear", 4, odl_Clear, VT_EMPTY, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Remove", 5, odl_Remove, VT_EMPTY, VTS_BSTR) DISP_FUNCTION_ID(TaskBaseline_C, "IsNull", 6, IsNull, VT_BOOL, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Initialize", 7, Initialize, VT_EMPTY, VTS_NONE) DISP_DEFVALUE(TaskBaseline_C, "Item") END_DISPATCH_MAP() BEGIN_INTERFACE_MAP(TaskBaseline_C, CCmdTarget) INTERFACE_PART(TaskBaseline_C, IID_ITaskBaseline_C, Dispatch) END_INTERFACE_MAP() BEGIN_MESSAGE_MAP(TaskBaseline_C, CCmdTarget) END_MESSAGE_MAP() TaskBaseline_C::TaskBaseline_C() { EnableAutomation(); AfxOleLockApp(); InitVars(); } void TaskBaseline_C::Initialize(void) { InitVars(); } void TaskBaseline_C::InitVars(void) { mp_oCollection = new clsCollectionBase("TaskBaseline"); } TaskBaseline_C::~TaskBaseline_C() { delete mp_oCollection; AfxOleUnlockApp(); } void TaskBaseline_C::OnFinalRelease() { CCmdTarget::OnFinalRelease(); } LONG TaskBaseline_C::odl_GetCount(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return GetCount(); } LONG TaskBaseline_C::GetCount(void) { return mp_oCollection->m_lCount(); } IDispatch* TaskBaseline_C::odl_Item(LPCTSTR Index) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return Item(Index)->GetIDispatch(TRUE); } IDispatch* TaskBaseline_C::odl_Add(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return Add()->GetIDispatch(TRUE); } void TaskBaseline_C::odl_Clear(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); Clear(); } void TaskBaseline_C::odl_Remove(LPCTSTR Index) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); Remove(Index); } BOOL TaskBaseline_C::IsNull(void) { BOOL bReturn = TRUE; if (GetCount() > 0) { bReturn = FALSE; } return bReturn; } TaskBaseline* TaskBaseline_C::Item(CString Index) { TaskBaseline *oTaskBaseline; oTaskBaseline = (TaskBaseline*)mp_oCollection->m_oItem(Index, MP_ITEM_1, MP_ITEM_2, MP_ITEM_3, MP_ITEM_4); return oTaskBaseline; } TaskBaseline* TaskBaseline_C::Add() { mp_oCollection->SetAddMode(TRUE); TaskBaseline* oTaskBaseline = new TaskBaseline(); oTaskBaseline->mp_oCollection = mp_oCollection; mp_oCollection->m_Add(oTaskBaseline, _T(""), MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3); return oTaskBaseline; } void TaskBaseline_C::Clear(void) { mp_oCollection->m_Clear(); } void TaskBaseline_C::Remove(CString Index) { mp_oCollection->m_Remove(Index, MP_REMOVE_1, MP_REMOVE_2, MP_REMOVE_3, MP_REMOVE_4); } void TaskBaseline_C::ReadObjectProtected(clsXML &oXML) { LONG lIndex; for (lIndex = 1; lIndex <= oXML.ReadCollectionCount(); lIndex++) { if (oXML.GetCollectionObjectName(lIndex) == "Baseline") { TaskBaseline* oTaskBaseline = new TaskBaseline(); oTaskBaseline->SetXML(oXML.ReadCollectionObject(lIndex)); mp_oCollection->SetAddMode(TRUE); CString sKey = _T(""); oTaskBaseline->mp_oCollection = mp_oCollection; mp_oCollection->m_Add(oTaskBaseline, sKey, MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3); } } } void TaskBaseline_C::WriteObjectProtected(clsXML &oXML) { LONG lIndex; TaskBaseline* oTaskBaseline; for (lIndex = 1; lIndex <= GetCount(); lIndex++) { oTaskBaseline = (TaskBaseline*) mp_oCollection->m_oReturnArrayElement(lIndex); oXML.WriteObject(oTaskBaseline->GetXML()); } }
27.835294
169
0.720837
jluzardo1971
d77648414a09632cd2856262e6251f30469035f6
2,172
hpp
C++
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
#pragma once #include <QString> #include <pajlada/settings.hpp> namespace AB_NAMESPACE { void _registerSetting(std::weak_ptr<pajlada::Settings::SettingData> setting); template <typename Type> class ChatterinoSetting : public pajlada::Settings::Setting<Type> { public: ChatterinoSetting(const std::string &path) : pajlada::Settings::Setting<Type>(path) { _registerSetting(this->getData()); } ChatterinoSetting(const std::string &path, const Type &defaultValue) : pajlada::Settings::Setting<Type>(path, defaultValue) { _registerSetting(this->getData()); } template <typename T2> ChatterinoSetting &operator=(const T2 &newValue) { this->setValue(newValue); return *this; } ChatterinoSetting &operator=(Type &&newValue) noexcept { pajlada::Settings::Setting<Type>::operator=(newValue); return *this; } using pajlada::Settings::Setting<Type>::operator==; using pajlada::Settings::Setting<Type>::operator!=; using pajlada::Settings::Setting<Type>::operator Type; }; using BoolSetting = ChatterinoSetting<bool>; using FloatSetting = ChatterinoSetting<float>; using DoubleSetting = ChatterinoSetting<double>; using IntSetting = ChatterinoSetting<int>; using StringSetting = ChatterinoSetting<std::string>; using QStringSetting = ChatterinoSetting<QString>; template <typename Enum> class EnumSetting : public ChatterinoSetting<typename std::underlying_type<Enum>::type> { using Underlying = typename std::underlying_type<Enum>::type; public: using ChatterinoSetting<Underlying>::ChatterinoSetting; EnumSetting(const std::string &path, const Enum &defaultValue) : ChatterinoSetting<Underlying>(path, Underlying(defaultValue)) { _registerSetting(this->getData()); } template <typename T2> EnumSetting<Enum> &operator=(Enum newValue) { this->setValue(Underlying(newValue)); return *this; } operator Enum() { return Enum(this->getValue()); } Enum getEnum() { return Enum(this->getValue()); } }; } // namespace AB_NAMESPACE
24.404494
77
0.683241
holysnipz
d7782ced05b4c171b035adfc673a35ae444f7135
9,671
cpp
C++
src/gui/MainWindow.cpp
guerinoni/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
1
2020-03-22T22:14:43.000Z
2020-03-22T22:14:43.000Z
src/gui/MainWindow.cpp
marsiliano/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
17
2019-11-20T09:51:45.000Z
2020-04-16T06:43:14.000Z
src/gui/MainWindow.cpp
marsiliano/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
3
2019-07-02T14:37:29.000Z
2019-11-13T15:38:26.000Z
#include "MainWindow.hpp" #include "ui_MainWindow.h" #include "ConfigViewFactory.hpp" #include "DialogAbout.hpp" #include "DialogSerialSettings.hpp" #include "MdiChild.hpp" #include "../parser/ConfigParser.hpp" #include "../core/Element.hpp" #include <QDockWidget> #include <QFileDialog> #include <QMdiSubWindow> #include <QMessageBox> #include <QSettings> #include <QStandardItemModel> #include <QStandardPaths> #include <QToolBar> #include <QTreeView> #include <QtDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Tino"); this->setWindowIcon(QIcon(":/logos/vector/isolated-layout.svg")); createActions(); createMenuBar(); createToolBar(); loadSettings(); connect(this, &MainWindow::importFinished, this, &MainWindow::createConfigView); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { QSettings settings("Tino"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); } void MainWindow::selectFile() { const auto filename = QFileDialog::getOpenFileName(this, tr("Open Config File"), m_importFilePath, tr("Config File (*.json)")); auto result = importConfig(filename); if (result.error) { QMessageBox::warning(this, tr("Load configuration"), tr(result.message.toUtf8().constData())); } } void MainWindow::createConfigView() { ui->mdiArea->closeAllSubWindows(); m_configViewDock.reset(ConfigViewFactory().makeConfigView(m_config->protocol)); m_configViewDock->setObjectName("ConfigView"); m_configViewDock->setFeatures(m_configViewDock->features() & ~QDockWidget::DockWidgetClosable); addDockWidget(Qt::DockWidgetArea::LeftDockWidgetArea, m_configViewDock.get(), Qt::Orientation::Vertical); auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); tree->setContextMenuPolicy(Qt::CustomContextMenu); connect(tree, &QTreeView::customContextMenuRequested, this, &MainWindow::customConfigViewContextMenu); } void MainWindow::customConfigViewContextMenu(const QPoint &point) { auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); QModelIndex index = tree->indexAt(point); if (!index.isValid()) { qWarning() << "index not valid" << index; return; } if (index.parent() != tree->rootIndex()) { qWarning() << "Not a root index"; return; } auto sModel = qobject_cast<QStandardItemModel *>(tree->model()); auto item = sModel->itemFromIndex(index); const auto protocolItemMenu = new QMenu(this); const auto view = new QAction("View", protocolItemMenu); view->setEnabled(item->accessibleText() == ConfigViewFactory::guiCreatable); connect(view, &QAction::triggered, this, [&]() { createWidgetRequested(item); }); protocolItemMenu->addAction(view); protocolItemMenu->exec(tree->viewport()->mapToGlobal(point)); } void MainWindow::connectClient() { if (!m_modbus->connectModbus(m_config->settings)) { QMessageBox::critical(this, tr("Tino"), tr("Modbus connection failed.")); return; } m_actions[Actions::Connect]->setEnabled(false); m_actions[Actions::Disconnect]->setEnabled(true); } void MainWindow::disconnectClient() { m_modbus->disconnectModbus(); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); const auto list = ui->mdiArea->subWindowList(); std::for_each(std::cbegin(list), std::cend(list), [](const auto &w) { auto mdiChild = dynamic_cast<MdiChild *>(w->widget()); mdiChild->resetToDefault(); }); } void MainWindow::createActions() { m_actions[Actions::Open] = std::make_unique<QAction>(tr("Open File...")); m_actions[Actions::Open]->setIcon(QIcon(":/flat/folder.png")); connect(m_actions[Actions::Open].get(), &QAction::triggered, this, &MainWindow::selectFile); m_actions[Actions::Connect] = std::make_unique<QAction>(tr("Connect")); m_actions[Actions::Connect]->setIcon(QIcon(":/flat/connected.png")); m_actions[Actions::Connect]->setEnabled(false); connect(m_actions[Actions::Connect].get(), &QAction::triggered, this, &MainWindow::connectClient); m_actions[Actions::Disconnect] = std::make_unique<QAction>(tr("Disconnect")); m_actions[Actions::Disconnect]->setIcon(QIcon(":/flat/disconnected.png")); m_actions[Actions::Disconnect]->setEnabled(false); connect(m_actions[Actions::Disconnect].get(), &QAction::triggered, this, &MainWindow::disconnectClient); m_actions[Actions::Settings] = std::make_unique<QAction>(tr("Setting...")); m_actions[Actions::Settings]->setIcon(QIcon(":/flat/settings.png")); m_actions[Actions::Settings]->setEnabled(false); connect(m_actions[Actions::Settings].get(), &QAction::triggered, this, [&]() { DialogSerialSettings(&m_config->settings).exec(); }); m_actions[Actions::About] = std::make_unique<QAction>(tr("About...")); m_actions[Actions::About]->setIcon(QIcon(":/flat/info.png")); connect(m_actions[Actions::About].get(), &QAction::triggered, this, []() { DialogAbout().exec(); }); m_actions[Actions::Quit] = std::make_unique<QAction>(tr("Quit")); m_actions[Actions::Quit]->setIcon(QIcon(":/flat/quit.png")); m_actions[Actions::Quit]->setShortcut(QKeySequence::StandardKey::Quit); connect(m_actions[Actions::Quit].get(), &QAction::triggered, this, []() { QApplication::exit(); }); } void MainWindow::createMenuBar() { const auto file = new QMenu("File", ui->menuBar); file->addAction(m_actions[Actions::Open].get()); file->addAction(m_actions[Actions::Quit].get()); ui->menuBar->addMenu(file); const auto comMenu = new QMenu(tr("Communication"), ui->menuBar); comMenu->addAction(m_actions[Actions::Connect].get()); comMenu->addAction(m_actions[Actions::Disconnect].get()); comMenu->addSeparator(); comMenu->addAction(m_actions[Actions::Settings].get()); ui->menuBar->addMenu(comMenu); const auto help = new QMenu("Help", ui->menuBar); help->addAction(m_actions[Actions::About].get()); ui->menuBar->addMenu(help); } void MainWindow::createToolBar() { m_toolbar = new QToolBar(this); m_toolbar->setObjectName("toolbar"); m_toolbar->setMovable(false); addToolBar(Qt::ToolBarArea::TopToolBarArea, m_toolbar); m_toolbar->addAction(m_actions[Actions::Open].get()); m_toolbar->addAction(m_actions[Actions::Connect].get()); m_toolbar->addAction(m_actions[Actions::Disconnect].get()); m_toolbar->addAction(m_actions[Actions::Settings].get()); } MainWindow::Error MainWindow::importConfig(const QString &filename) { if (filename.isNull() || filename.isEmpty()) { return Error{true, "Filename not valid!"}; } ConfigParser parser; m_config = std::make_unique<Configuration>(parser.parse(filename)); if (m_config == nullptr) { return Error{true, "Parsing configuration error!"}; } m_modbus = std::make_unique<ModbusCom>(m_config->protocol); connect(m_modbus.get(), &ModbusCom::updateGui, this, [this](int address) { const auto list = ui->mdiArea->subWindowList(); for (const auto &w : list) { auto mdi = dynamic_cast<MdiChild *>(w->widget()); // FIXME: maybe some ValueWidget are not refreshed if (mdi->hasElementWithAddress(address)) { mdi->updateGuiElemets(); return; } } }); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); m_actions[Actions::Settings]->setEnabled(true); emit importFinished({}); m_importFilePath = filename; saveSettings(); return {}; } void MainWindow::createWidgetRequested(QStandardItem *item) { const auto whatsThis = item->whatsThis(); const auto blockId = whatsThis.split('_').at(1).toInt(); const auto block = m_config->protocol.blocks.at(blockId); if (setFocusIfAlreadyExists(block)) { return; } const auto child = new MdiChild(block); connect(child, &MdiChild::updateModbus, m_modbus.get(), &ModbusCom::writeRegister); ui->mdiArea->addSubWindow(child); child->show(); } void MainWindow::saveSettings() { QSettings settings("Tino"); settings.setValue("importFilePath", m_importFilePath); } void MainWindow::loadSettings() { QSettings settings("Tino"); auto desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); m_importFilePath = settings.value("importFilePath", desktop).toString(); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); } bool MainWindow::setFocusIfAlreadyExists(const Block &block) const { const auto list = ui->mdiArea->subWindowList(); const auto it = std::find_if(std::cbegin(list), std::cend(list), [&](const auto &k) { return k->windowTitle() == block.description; }); if (it == list.cend()) { return false; } list.at(std::distance(std::cbegin(list), it))->setFocus(); return true; }
32.783051
99
0.656292
guerinoni
d778d577ea8efc1b356df1d7c017ecdf3188106a
6,221
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "LibWebRTCSocketFactory.h" #if USE(LIBWEBRTC) #include "NetworkProcessConnection.h" #include "NetworkRTCMonitorMessages.h" #include "NetworkRTCProviderMessages.h" #include "WebProcess.h" #include "WebRTCSocket.h" #include <wtf/MainThread.h> namespace WebKit { uint64_t LibWebRTCSocketFactory::s_uniqueSocketIdentifier = 0; uint64_t LibWebRTCSocketFactory::s_uniqueResolverIdentifier = 0; static inline rtc::SocketAddress prepareSocketAddress(const rtc::SocketAddress& address, bool disableNonLocalhostConnections) { auto result = RTCNetwork::isolatedCopy(address); if (disableNonLocalhostConnections) result.SetIP("127.0.0.1"); return result; } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateServerTcpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerTCP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort, options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateServerTCPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort, options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateUdpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::UDP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateUDPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateClientTcpSocket(const rtc::SocketAddress& localAddress, const rtc::SocketAddress& remoteAddress, const rtc::ProxyInfo&, const std::string&, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ClientTCP, localAddress, remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTING); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), localAddress = prepareSocketAddress(localAddress, m_disableNonLocalhostConnections), remoteAddress = prepareSocketAddress(remoteAddress, m_disableNonLocalhostConnections), options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateClientTCPSocket(identifier, RTCNetwork::SocketAddress(localAddress), RTCNetwork::SocketAddress(remoteAddress), options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::createNewConnectionSocket(LibWebRTCSocket& serverSocket, uint64_t newConnectionSocketIdentifier, const rtc::SocketAddress& remoteAddress) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerConnectionTCP, serverSocket.localAddress(), remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTED); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), newConnectionSocketIdentifier]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::WrapNewTCPConnection(identifier, newConnectionSocketIdentifier), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } void LibWebRTCSocketFactory::detach(LibWebRTCSocket& socket) { ASSERT(m_sockets.contains(socket.identifier())); m_sockets.remove(socket.identifier()); } rtc::AsyncResolverInterface* LibWebRTCSocketFactory::CreateAsyncResolver() { auto resolver = std::make_unique<LibWebRTCResolver>(++s_uniqueResolverIdentifier); auto* resolverPointer = resolver.get(); m_resolvers.set(resolverPointer->identifier(), WTFMove(resolver)); return resolverPointer; } } // namespace WebKit #endif // USE(LIBWEBRTC)
48.224806
250
0.756631
mlcldh
d779d8f0b194753a162cd7d6a24f749908c204ab
4,685
hpp
C++
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
1
2018-08-14T05:45:29.000Z
2018-08-14T05:45:29.000Z
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
// This file is part of CaptureTheBanana++. // // Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md) // This file is licensed under the MIT license; see LICENSE file in the root of this // project for details. #ifndef ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #define ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #include <Box2D/Box2D.h> namespace ctb { namespace engine { class Player; class Bot; class Door; class Fist; class Flag; class PhysicalObject; class PhysicalRenderable; class Projectile; /** * @brief Class, that handles special behavior for certain objects */ class LevelContactListener : public b2ContactListener { public: /** * @brief Constructor */ LevelContactListener(); ~LevelContactListener() override = default; /** * @brief What should happen at the beginning of a contact of two certain objects? * * @param contact all necessary contact information */ void BeginContact(b2Contact* contact) override; /** * @brief What should happen at the end of a contatc of two certain objects? * * @param contact all necessary contact information */ void EndContact(b2Contact* contact) override; /** * @brief What should happen before two certain objects are in contact? * * @param contact all necessary contact information * @param oldManifold for two touching convex shapes */ void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; /** * @brief Should be called after every step of the b2World. * Does tasks, that cannot be done during the normal contact events, * because in BeginContact, EndContact and PreContact the beWorld is locked */ virtual void update(); private: /** * @brief What should happen, if an player reaches the right door with the banana? * * @param contact all necessary contact information * @param player who reached the door * @param door which was reached */ void doorReached(b2Contact* contact, Player* player, Door* door); /** * @brief Makes, that the given player is the owner of the given flag * * @param player who whould be the owner of the flag * @param flag who should be owned by the player */ void flagOwned(Player* player, Flag* flag); /** * @brief Proves, if the given flag is owned by an player * * @param obj must be a flag * * @return Is the flag in use? */ bool isFlagInUse(PhysicalObject* obj); /** * @brief What should happen, if an player collides with a bot? * * @param player who is colliding * @param bot who is colliding */ void collidedBotPlayer(Player* player, Bot* bot); /** * @brief Perform a melee attack on an other player with a cooldown * * @param attacking the attacking player * @param hurt the player, who is attacked */ void meleeWithCooldown(Player* attacking, Player* hurt); /** * @brief What should happen, if an player collects a flag * * @param player who is colliding with a flag * @param flag which is colliding with an player */ void collectFlag(Player* player, Flag* flag); /** * @brief What should happen, if an player collides with a weapon * * @param player who is colliding with a weapon * @param weapon which is colliding with an player * @param contact information about the collision */ void collisionPlayerWeapon(Player* player, Fist* weapon, b2Contact* contact); /** * @brief What should happen, if a projectile collides with an other PhysicalObject * * @param projectile which is colliding with a PhysicalObject * @param obj which is colliding with a projectile * @param contact information about the collision */ void collisionWithProjectile(Projectile* projectile, PhysicalObject* obj, b2Contact* contact); /** * @brief Method for ignoring the contact betwen a door and an player * * @param door which is colliding with an player * @param player which is colliding with a door * @param contact information about the collision */ void doorIgnoring(Door* door, Player* player, b2Contact* contact); /// Reference to the first object, which is collided for the update method PhysicalRenderable* m_a; /// Reference to the second object, which is collided for the update method PhysicalRenderable* m_b; /// Reference to an player for the update method Player* m_player; }; } // namespace engine } // namespace ctb #endif
28.742331
98
0.672785
CaptureTheBanana
d780723d2d263f31f784eba9d2863690464d25b1
2,815
cpp
C++
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
2
2021-10-05T03:27:03.000Z
2021-12-14T02:56:25.000Z
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
7
2021-09-30T01:22:25.000Z
2022-01-07T01:33:07.000Z
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
null
null
null
#include <assert.h> #include <Arclight/Core/Application.h> #include <Arclight/Core/Input.h> #include <Arclight/Core/Logger.h> #include <Arclight/Core/ResourceManager.h> #include <Arclight/Core/ThreadPool.h> #include <Arclight/Core/Timer.h> #include <Arclight/Graphics/Rendering/Renderer.h> #include <Arclight/Platform/Platform.h> #include <Arclight/State/StateManager.h> #include <Arclight/Window/WindowContext.h> #ifdef ARCLIGHT_PLATFORM_UNIX #include <dlfcn.h> #include <unistd.h> #endif #ifdef ARCLIGHT_PLATFORM_WINDOWS #include <windows.h> #endif #include <chrono> #include <vector> using namespace Arclight; bool isRunning = true; #ifdef ARCLIGHT_SINGLE_EXECUTABLE extern "C" void game_init(); #endif #if defined(ARCLIGHT_PLATFORM_WINDOWS) int wmain(int argc, wchar_t** argv) { #else int main(int argc, char** argv) { #endif Platform::Initialize(); Logger::Debug("Using renderer: {}", Rendering::Renderer::instance()->get_name()); #if defined(ARCLIGHT_PLATFORM_WASM) void (*InitFunc)(void) = game_init; #elif defined(ARCLIGHT_PLATFORM_UNIX) if (argc >= 2) { chdir(argv[1]); } char cwd[4096]; getcwd(cwd, 4096); std::string gamePath = std::string(cwd) + "/" + "game.so"; Logger::Debug("Loading game executable: {}", gamePath); void* game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { // Try Build/game.so instead gamePath = std::string(cwd) + "/Build/" + "game.so"; game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { Logger::Debug("Error loading {}", dlerror()); return 1; } } void (*InitFunc)(void) = (void (*)())dlsym(game, "game_init"); #elif defined(ARCLIGHT_PLATFORM_WINDOWS) #ifndef ARCLIGHT_SINGLE_EXECUTABLE if (argc >= 2) { SetCurrentDirectoryW(argv[1]); } wchar_t cwd[_MAX_PATH]; DWORD cwdLen; if (cwdLen = GetCurrentDirectoryW(_MAX_PATH, cwd); cwdLen > _MAX_PATH || cwdLen == 0) { Logger::Error("Failed to get current working directory!"); return 1; } Arclight::UnicodeString dllPath = cwd; dllPath += L"\\game.dll"; HINSTANCE game = LoadLibraryW(as_wide_string(dllPath)); if (!game) { Logger::Debug("Error loading {}", dllPath); return 2; } void (*InitFunc)(void) = (void (*)())GetProcAddress(game, "game_init"); if (!InitFunc) { Logger::Debug("Could not resolve symbol GameInit from {}", dllPath); return 2; } #else void (*InitFunc)(void) = game_init; #endif #else #error "Unsupported platform!" #endif assert(InitFunc); { Application app; InitFunc(); } #if defined(ARCLIGHT_PLATFORM_WASM) return 0; #else Platform::Cleanup(); return 0; #endif }
22.701613
91
0.646892
ArclightEngine
d7864a53f29349e15f287da6273a4c442623c336
2,885
cc
C++
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "src/developer/forensics/testing/fakes/data_provider.h" #include <fuchsia/feedback/cpp/fidl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/syslog/cpp/macros.h> #include <memory> #include <vector> #include "src/developer/forensics/utils/archive.h" #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/strings/string_printf.h" namespace forensics { namespace fakes { namespace { using namespace fuchsia::feedback; std::string AnnotationsToJSON(const std::vector<Annotation>& annotations) { std::string json = "{\n"; for (const auto& annotation : annotations) { json += fxl::StringPrintf("\t\"%s\": \"%s\"\n", annotation.key.c_str(), annotation.value.c_str()); } json += "}\n"; return json; } std::vector<Annotation> CreateAnnotations() { return { Annotation{.key = "annotation_key_1", .value = "annotation_value_1"}, Annotation{.key = "annotation_key_2", .value = "annotation_value_2"}, Annotation{.key = "annotation_key_3", .value = "annotation_value_3"}, }; } Attachment CreateSnapshot() { std::map<std::string, std::string> attachments; attachments["annotations.json"] = AnnotationsToJSON(CreateAnnotations()); attachments["attachment_key"] = "attachment_value"; fsl::SizedVmo archive; Archive(attachments, &archive); return {.key = "snapshot.zip", .value = std::move(archive).ToTransport()}; } std::unique_ptr<Screenshot> LoadPngScreenshot() { fsl::SizedVmo image; FX_CHECK(fsl::VmoFromFilename("/pkg/data/checkerboard_100.png", &image)) << "Failed to create image vmo"; const size_t image_dim_in_px = 100u; fuchsia::math::Size dimensions; dimensions.width = image_dim_in_px; dimensions.height = image_dim_in_px; std::unique_ptr<Screenshot> screenshot = Screenshot::New(); screenshot->image = std::move(image).ToTransport(); screenshot->dimensions_in_px = dimensions; return screenshot; } } // namespace void DataProvider::GetAnnotations(fuchsia::feedback::GetAnnotationsParameters params, GetAnnotationsCallback callback) { callback(std::move(Annotations().set_annotations(CreateAnnotations()))); } void DataProvider::GetSnapshot(fuchsia::feedback::GetSnapshotParameters parms, GetSnapshotCallback callback) { callback( std::move(Snapshot().set_annotations(CreateAnnotations()).set_archive(CreateSnapshot()))); } void DataProvider::GetScreenshot(ImageEncoding encoding, GetScreenshotCallback callback) { switch (encoding) { case ImageEncoding::PNG: callback(LoadPngScreenshot()); default: callback(nullptr); } } } // namespace fakes } // namespace forensics
30.052083
98
0.709532
csrpi
d78a0060cdcf38ff388b7ff092a736c23791dad8
1,567
cpp
C++
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; // Max sum with no 3 consecutive is an extension of the below procedure // this is the implementation where no consecutive are in the max sum int maxSumNoConsecutiveElems(vector<int> &a){ // incl contains (prev element excluded sum + current element) // excl contains max(prev excluded sum, prev included sum) // NOTICE: incl adds the current element to the prev max sum, excl, // just stores the max sum found previously without including the // current element in the sum int incl = 0, excl = 0; for(int i=0;i<a.size();i++){ // storing the prev incl to be used in excl int tincl = incl; incl = excl+a[i]; excl = max(tincl,excl); } return max(incl,excl); } int Max(int a, int b, int c){ return max(a,max(b,c)); } int maxSumNo3consecutiveElems(vector<int> &a){ int n = a.size(); // dp array to store the max at each index vector<int> dp(n); for(int i=0;i<n;i++){ if(i==0) dp[i] = a[0]; else if(i==1) dp[i] = dp[0]+a[1]; // we take max of sum of 0&1 or 1&2 or 0&2 else if(i==2) dp[i] = Max(dp[i],a[1]+a[2],a[0]+a[2]); // we got 3 options: // (I) exclude a[i] // (II) exclude a[i-1] // (III) exclude a[i-2] // We have to choose the maximum of the 3 else dp[i] = Max(dp[i-1],dp[i-2]+a[i],dp[i-3]+a[i-1]+a[i]); } return dp[n-1]; } int main(){ vector<int> a = {5,5,10,40,50,35}; cout<<maxSumNoConsecutiveElems(a)<<endl; cout<<maxSumNo3consecutiveElems(a)<<endl; return 0; }
27.491228
71
0.601149
Coderangshu
d78ae7b565651f4759d2dc0b8b93cb4ac626af4a
5,305
cpp
C++
solved/0-b/8-puzzle/puzzle.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/8-puzzle/puzzle.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/8-puzzle/puzzle.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <stack> #include <vector> using namespace std; #define INF 1000 #define Zero(v) memset((v), 0, sizeof(v)) // goal[n]: coordinates of number n in the solution configuration const int goal[9][2] = { { 2, 2 }, { 0, 0 }, { 0, 1 }, { 0, 2 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 } }; // moves const int dd[4][2] = { { 1, 0 }, // down { 0, -1 }, // left { -1, 0 }, // up { 0, 1 } // right }; struct Game { int m[3][3]; int tmd; // total sum of manhattan distances int lc; // weight of linear conflicts int r, c; // row and column of blank tile int chl; // index of next children state int last; // last move performed Game() {} void init() { last = -1; tmd = 0; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { int n = m[i][j]; if (n == 0) { r = i, c = j; continue; } tmd += abs(i - goal[n][0]) + abs(j - goal[n][1]); } lc = 0; for (int i = 0; i < 3; ++i) { if (conflict_in_row(i)) lc += 2; if (conflict_in_col(i)) lc += 2; } } bool conflict_in_row(int r) { int c1, c2; for (c1 = 2; c1 > 0; --c1) if (m[r][c1] > 0 && goal[m[r][c1]][0] == r) break; if (c1 == 0) return false; for (c2 = 0; c2 < c1; ++c2) if (m[r][c2] > 0 && goal[m[r][c2]][0] == r && goal[m[r][c1]][1] < goal[m[r][c2]][1]) return true; return false; } bool conflict_in_col(int c) { int r1, r2; for (r1 = 2; r1 > 0; --r1) if (m[r1][c] > 0 && goal[m[r1][c]][1] == c) break; if (r1 == 0) return false; for (r2 = 0; r2 < r1; ++r2) if (m[r2][c] > 0 && goal[m[r2][c]][1] == c && goal[m[r1][c]][0] < goal[m[r2][c]][0]) return true; return false; } int h() { return tmd + lc; } bool is_solution() { return tmd == 0; } void reset() { chl = 0; } bool next(Game &child, int &dist, int &delta) { int r2, c2; int comp_move = last >= 0 ? (last + 2) % 4 : -1; for (; chl < 4; ++chl) { if (chl == comp_move) continue; r2 = r + dd[chl][0]; c2 = c + dd[chl][1]; if (r2 >= 0 && r2 < 3 && c2 >= 0 && c2 < 3) break; } if (chl >= 4) return false; child = *this; child.last = chl++; int n = child.m[r2][c2]; child.tmd += abs(r - goal[n][0]) + abs(c - goal[n][1]) - abs(r2 - goal[n][0]) - abs(c2 - goal[n][1]); swap(child.m[r][c], child.m[r2][c2]); child.r = r2, child.c = c2; if (r != r2) { if (conflict_in_row(r)) child.lc -= 2; if (conflict_in_row(r2)) child.lc -= 2; if (child.conflict_in_row(r)) child.lc += 2; if (child.conflict_in_row(r2)) child.lc += 2; } if (c != c2) { if (conflict_in_col(c)) child.lc -= 2; if (conflict_in_col(c2)) child.lc -= 2; if (child.conflict_in_col(c)) child.lc += 2; if (child.conflict_in_col(c2)) child.lc += 2; } dist = 1; return true; } bool is_solvable() { int invr = 0; for (int i = 0; i < 9; ++i) { int r = i / 3, c = i % 3; if (m[r][c] != 0) for (int j = 0; j < i; ++j) { int p = j / 3, q = j % 3; if (m[p][q] != 0 && m[p][q] > m[r][c]) ++invr; } } return invr % 2 == 0; } }; template <typename NT, typename DT> bool ida_dls(NT &node, int depth, int g, int &nxt, stack<DT> &st) { if (g == depth) return node.is_solution(); NT child; int dist; DT delta; for (node.reset(); node.next(child, dist, delta);) { int f = g + dist + child.h(); if (f > depth && f < nxt) nxt = f; if (f <= depth && ida_dls(child, depth, g + 1, nxt, st)) { if (st.empty()) st.push(dist); else { int steps = st.top(); st.pop(); st.push(steps + dist); } return true; } } return false; } template <typename NT, typename DT> bool ida_star(NT &root, int limit, stack<DT> &st) { for (int depth = root.h(); depth <= limit;) { int next_depth = INF; if (ida_dls(root, depth, 0, next_depth, st)) return true; if (next_depth == INF) return false; depth = next_depth; } return false; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { Game g; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) scanf("%d", &g.m[i][j]); g.init(); printf("Case %d: ", ++ncase); stack<int> st; if (g.is_solvable() && ida_star(g, INF, st)) printf("%d\n", st.empty() ? 0 : st.top()); else puts("impossible"); } return 0; }
26.004902
67
0.416211
abuasifkhan
d78c48b3a0a7604f54c219eb641eab6a3723ce43
3,538
hh
C++
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 SK Telecom Co., Ltd. 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. */ #ifndef __NUGU_CAPABILITY_AGENT_H__ #define __NUGU_CAPABILITY_AGENT_H__ #include <map> #include <memory> #include "base/nugu_event.h" #include "clientkit/capability_interface.hh" #include "directive_sequencer.hh" #include "focus_manager.hh" #include "interaction_control_manager.hh" #include "playsync_manager.hh" #include "session_manager.hh" namespace NuguCore { class CapabilityManager : public INetworkManagerListener, public IDirectiveSequencerListener { private: CapabilityManager(); virtual ~CapabilityManager(); public: static CapabilityManager* getInstance(); static void destroyInstance(); void resetInstance(); PlaySyncManager* getPlaySyncManager(); FocusManager* getFocusManager(); SessionManager* getSessionManager(); InteractionControlManager* getInteractionControlManager(); DirectiveSequencer* getDirectiveSequencer(); void addCapability(const std::string& cname, ICapabilityInterface* cap); void removeCapability(const std::string& cname); void requestEventResult(NuguEvent* event); // overriding INetworkManagerListener void onEventSendResult(const char* msg_id, bool success, int code) override; void onEventResponse(const char* msg_id, const char* data, bool success) override; void setWakeupWord(const std::string& word); std::string getWakeupWord(); std::string makeContextInfo(const std::string& cname, Json::Value& ctx); std::string makeAllContextInfo(); bool isSupportDirectiveVersion(const std::string& version, ICapabilityInterface* cap); bool sendCommand(const std::string& from, const std::string& to, const std::string& command, const std::string& param); void sendCommandAll(const std::string& command, const std::string& param); bool getCapabilityProperty(const std::string& cap, const std::string& property, std::string& value); bool getCapabilityProperties(const std::string& cap, const std::string& property, std::list<std::string>& values); void suspendAll(); void restoreAll(); // overriding IDirectiveSequencerListener bool onPreHandleDirective(NuguDirective* ndir) override; bool onHandleDirective(NuguDirective* ndir) override; void onCancelDirective(NuguDirective* ndir) override; private: ICapabilityInterface* findCapability(const std::string& cname); static CapabilityManager* instance; std::map<std::string, ICapabilityInterface*> caps; std::map<std::string, std::string> events; std::map<std::string, std::string> events_cname_map; std::string wword; std::unique_ptr<PlaySyncManager> playsync_manager; std::unique_ptr<FocusManager> focus_manager; std::unique_ptr<SessionManager> session_manager; std::unique_ptr<DirectiveSequencer> directive_sequencer; std::unique_ptr<InteractionControlManager> interaction_control_manager; }; } // NuguCore #endif
36.102041
123
0.749293
nugulinux
d78d1b0b34b8318286f233a42437759cf5b5c652
15,254
cpp
C++
src/system/kernel/posix/realtime_sem.cpp
waddlesplash/haiku
68d1b97e4f99fa0f190579f7ffd16fceda23ebce
[ "MIT" ]
2
2021-11-30T22:17:42.000Z
2022-02-04T20:57:17.000Z
src/system/kernel/posix/realtime_sem.cpp
grexe/haiku
4b0d8831c29fde017869ac7e77fdf7871bbc4b10
[ "MIT" ]
null
null
null
src/system/kernel/posix/realtime_sem.cpp
grexe/haiku
4b0d8831c29fde017869ac7e77fdf7871bbc4b10
[ "MIT" ]
null
null
null
/* * Copyright 2008-2011, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include <posix/realtime_sem.h> #include <string.h> #include <new> #include <OS.h> #include <AutoDeleter.h> #include <fs/KPath.h> #include <kernel.h> #include <lock.h> #include <syscall_restart.h> #include <team.h> #include <thread.h> #include <util/atomic.h> #include <util/AutoLock.h> #include <util/OpenHashTable.h> #include <util/StringHash.h> namespace { class SemInfo { public: SemInfo() : fSemaphoreID(-1) { } virtual ~SemInfo() { if (fSemaphoreID >= 0) delete_sem(fSemaphoreID); } sem_id SemaphoreID() const { return fSemaphoreID; } status_t Init(int32 semCount, const char* name) { fSemaphoreID = create_sem(semCount, name); if (fSemaphoreID < 0) return fSemaphoreID; return B_OK; } virtual sem_id ID() const = 0; virtual SemInfo* Clone() = 0; virtual void Delete() = 0; private: sem_id fSemaphoreID; }; class NamedSem : public SemInfo { public: NamedSem() : fName(NULL), fRefCount(1) { } virtual ~NamedSem() { free(fName); } const char* Name() const { return fName; } status_t Init(const char* name, mode_t mode, int32 semCount) { status_t error = SemInfo::Init(semCount, name); if (error != B_OK) return error; fName = strdup(name); if (fName == NULL) return B_NO_MEMORY; fUID = geteuid(); fGID = getegid(); fPermissions = mode; return B_OK; } void AcquireReference() { atomic_add(&fRefCount, 1); } void ReleaseReference() { if (atomic_add(&fRefCount, -1) == 1) delete this; } bool HasPermissions() const { if ((fPermissions & S_IWOTH) != 0) return true; uid_t uid = geteuid(); if (uid == 0 || (uid == fUID && (fPermissions & S_IWUSR) != 0)) return true; gid_t gid = getegid(); if (gid == fGID && (fPermissions & S_IWGRP) != 0) return true; return false; } virtual sem_id ID() const { return SemaphoreID(); } virtual SemInfo* Clone() { AcquireReference(); return this; } virtual void Delete() { ReleaseReference(); } NamedSem*& HashLink() { return fHashLink; } private: char* fName; int32 fRefCount; uid_t fUID; gid_t fGID; mode_t fPermissions; NamedSem* fHashLink; }; struct NamedSemHashDefinition { typedef const char* KeyType; typedef NamedSem ValueType; size_t HashKey(const KeyType& key) const { return hash_hash_string(key); } size_t Hash(NamedSem* semaphore) const { return HashKey(semaphore->Name()); } bool Compare(const KeyType& key, NamedSem* semaphore) const { return strcmp(key, semaphore->Name()) == 0; } NamedSem*& GetLink(NamedSem* semaphore) const { return semaphore->HashLink(); } }; class GlobalSemTable { public: GlobalSemTable() : fSemaphoreCount(0) { mutex_init(&fLock, "global named sem table"); } ~GlobalSemTable() { mutex_destroy(&fLock); } status_t Init() { return fNamedSemaphores.Init(); } status_t OpenNamedSem(const char* name, int openFlags, mode_t mode, uint32 semCount, NamedSem*& _sem, bool& _created) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem != NULL) { if ((openFlags & O_EXCL) != 0) return EEXIST; if (!sem->HasPermissions()) return EACCES; sem->AcquireReference(); _sem = sem; _created = false; return B_OK; } if ((openFlags & O_CREAT) == 0) return ENOENT; // does not exist yet -- create if (fSemaphoreCount >= MAX_POSIX_SEMS) return ENOSPC; sem = new(std::nothrow) NamedSem; if (sem == NULL) return B_NO_MEMORY; status_t error = sem->Init(name, mode, semCount); if (error != B_OK) { delete sem; return error; } error = fNamedSemaphores.Insert(sem); if (error != B_OK) { delete sem; return error; } // add one reference for the table sem->AcquireReference(); fSemaphoreCount++; _sem = sem; _created = true; return B_OK; } status_t UnlinkNamedSem(const char* name) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem == NULL) return ENOENT; if (!sem->HasPermissions()) return EACCES; fNamedSemaphores.Remove(sem); sem->ReleaseReference(); // release the table reference fSemaphoreCount--; return B_OK; } private: typedef BOpenHashTable<NamedSemHashDefinition, true> NamedSemTable; mutex fLock; NamedSemTable fNamedSemaphores; int32 fSemaphoreCount; }; static GlobalSemTable sSemTable; class TeamSemInfo { public: TeamSemInfo(SemInfo* semaphore, sem_t* userSem) : fSemaphore(semaphore), fUserSemaphore(userSem), fOpenCount(1) { } ~TeamSemInfo() { if (fSemaphore != NULL) fSemaphore->Delete(); } sem_id ID() const { return fSemaphore->ID(); } sem_id SemaphoreID() const { return fSemaphore->SemaphoreID(); } sem_t* UserSemaphore() const { return fUserSemaphore; } void Open() { fOpenCount++; } bool Close() { return --fOpenCount == 0; } TeamSemInfo* Clone() const { SemInfo* sem = fSemaphore->Clone(); if (sem == NULL) return NULL; TeamSemInfo* clone = new(std::nothrow) TeamSemInfo(sem, fUserSemaphore); if (clone == NULL) { sem->Delete(); return NULL; } clone->fOpenCount = fOpenCount; return clone; } TeamSemInfo*& HashLink() { return fHashLink; } private: SemInfo* fSemaphore; sem_t* fUserSemaphore; int32 fOpenCount; TeamSemInfo* fHashLink; }; struct TeamSemHashDefinition { typedef sem_id KeyType; typedef TeamSemInfo ValueType; size_t HashKey(const KeyType& key) const { return (size_t)key; } size_t Hash(TeamSemInfo* semaphore) const { return HashKey(semaphore->ID()); } bool Compare(const KeyType& key, TeamSemInfo* semaphore) const { return key == semaphore->ID(); } TeamSemInfo*& GetLink(TeamSemInfo* semaphore) const { return semaphore->HashLink(); } }; } // namespace struct realtime_sem_context { realtime_sem_context() : fSemaphoreCount(0) { mutex_init(&fLock, "realtime sem context"); } ~realtime_sem_context() { mutex_lock(&fLock); // delete all semaphores. SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { // Note, this uses internal knowledge about how the iterator works. // Ugly, but there's no good alternative. fSemaphores.RemoveUnchecked(sem); delete sem; } mutex_destroy(&fLock); } status_t Init() { fNextPrivateSemID = -1; return fSemaphores.Init(); } realtime_sem_context* Clone() { // create new context realtime_sem_context* context = new(std::nothrow) realtime_sem_context; if (context == NULL) return NULL; ObjectDeleter<realtime_sem_context> contextDeleter(context); MutexLocker _(fLock); context->fNextPrivateSemID = fNextPrivateSemID; // clone all semaphores SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { TeamSemInfo* clonedSem = sem->Clone(); if (clonedSem == NULL) return NULL; if (context->fSemaphores.Insert(clonedSem) != B_OK) { delete clonedSem; return NULL; } context->fSemaphoreCount++; } contextDeleter.Detach(); return context; } status_t OpenSem(const char* name, int openFlags, mode_t mode, uint32 semCount, sem_t* userSem, sem_t*& _usedUserSem, int32_t& _id, bool& _created) { NamedSem* sem = NULL; status_t error = sSemTable.OpenNamedSem(name, openFlags, mode, semCount, sem, _created); if (error != B_OK) return error; MutexLocker _(fLock); TeamSemInfo* teamSem = fSemaphores.Lookup(sem->ID()); if (teamSem != NULL) { // already open -- just increment the open count teamSem->Open(); sem->ReleaseReference(); _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } // not open yet -- create a new team sem // first check the semaphore limit, though if (fSemaphoreCount >= MAX_POSIX_SEMS_PER_TEAM) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return ENOSPC; } teamSem = new(std::nothrow) TeamSemInfo(sem, userSem); if (teamSem == NULL) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return B_NO_MEMORY; } error = fSemaphores.Insert(teamSem); if (error != B_OK) { delete teamSem; if (_created) sSemTable.UnlinkNamedSem(name); return error; } fSemaphoreCount++; _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } status_t CloseSem(sem_id id, sem_t*& deleteUserSem) { deleteUserSem = NULL; MutexLocker _(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; if (sem->Close()) { // last reference closed fSemaphores.Remove(sem); fSemaphoreCount--; deleteUserSem = sem->UserSemaphore(); delete sem; } return B_OK; } status_t AcquireSem(sem_id id, uint32 flags, bigtime_t timeout) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = acquire_sem_etc(id, 1, flags | B_CAN_INTERRUPT, timeout); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t ReleaseSem(sem_id id) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = release_sem(id); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t GetSemCount(sem_id id, int& _count) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); int32 count; status_t error = get_sem_count(id, &count); if (error != B_OK) return error; _count = count; return B_OK; } private: sem_id _NextPrivateSemID() { while (true) { if (fNextPrivateSemID >= 0) fNextPrivateSemID = -1; sem_id id = fNextPrivateSemID--; if (fSemaphores.Lookup(id) == NULL) return id; } } private: typedef BOpenHashTable<TeamSemHashDefinition, true> SemTable; mutex fLock; SemTable fSemaphores; int32 fSemaphoreCount; sem_id fNextPrivateSemID; }; // #pragma mark - implementation private static realtime_sem_context* get_current_team_context() { Team* team = thread_get_current_thread()->team; // get context realtime_sem_context* context = atomic_pointer_get( &team->realtime_sem_context); if (context != NULL) return context; // no context yet -- create a new one context = new(std::nothrow) realtime_sem_context; if (context == NULL || context->Init() != B_OK) { delete context; return NULL; } // set the allocated context realtime_sem_context* oldContext = atomic_pointer_test_and_set( &team->realtime_sem_context, context, (realtime_sem_context*)NULL); if (oldContext == NULL) return context; // someone else was quicker delete context; return oldContext; } static status_t copy_sem_name_to_kernel(const char* userName, KPath& buffer, char*& name) { if (userName == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; if (buffer.InitCheck() != B_OK) return B_NO_MEMORY; // copy userland path to kernel name = buffer.LockBuffer(); ssize_t actualLength = user_strlcpy(name, userName, buffer.BufferSize()); if (actualLength < 0) return B_BAD_ADDRESS; if ((size_t)actualLength >= buffer.BufferSize()) return ENAMETOOLONG; return B_OK; } // #pragma mark - kernel internal void realtime_sem_init() { new(&sSemTable) GlobalSemTable; if (sSemTable.Init() != B_OK) panic("realtime_sem_init() failed to init global sem table"); } void delete_realtime_sem_context(realtime_sem_context* context) { delete context; } realtime_sem_context* clone_realtime_sem_context(realtime_sem_context* context) { if (context == NULL) return NULL; return context->Clone(); } // #pragma mark - syscalls status_t _user_realtime_sem_open(const char* userName, int openFlagsOrShared, mode_t mode, uint32 semCount, sem_t* userSem, sem_t** _usedUserSem) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_NO_MEMORY; if (semCount > MAX_POSIX_SEM_VALUE) return B_BAD_VALUE; // userSem must always be given if (userSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userSem)) return B_BAD_ADDRESS; // check user pointers if (_usedUserSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_usedUserSem) || !IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; // open the semaphore sem_t* usedUserSem; bool created = false; int32_t id; error = context->OpenSem(name, openFlagsOrShared, mode, semCount, userSem, usedUserSem, id, created); if (error != B_OK) return error; // copy results back to userland if (user_memcpy(&userSem->u.named_sem_id, &id, sizeof(int32_t)) != B_OK || user_memcpy(_usedUserSem, &usedUserSem, sizeof(sem_t*)) != B_OK) { if (created) sSemTable.UnlinkNamedSem(name); sem_t* dummy; context->CloseSem(id, dummy); return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_close(sem_id semID, sem_t** _deleteUserSem) { if (_deleteUserSem != NULL && !IS_USER_ADDRESS(_deleteUserSem)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // close sem sem_t* deleteUserSem; status_t error = context->CloseSem(semID, deleteUserSem); if (error != B_OK) return error; // copy back result to userland if (_deleteUserSem != NULL && user_memcpy(_deleteUserSem, &deleteUserSem, sizeof(sem_t*)) != B_OK) { return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_unlink(const char* userName) { // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; return sSemTable.UnlinkNamedSem(name); } status_t _user_realtime_sem_get_value(sem_id semID, int* _value) { if (_value == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_value)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // get sem count int count; status_t error = context->GetSemCount(semID, count); if (error != B_OK) return error; // copy back result to userland if (user_memcpy(_value, &count, sizeof(int)) != B_OK) return B_BAD_ADDRESS; return B_OK; } status_t _user_realtime_sem_post(sem_id semID) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return context->ReleaseSem(semID); } status_t _user_realtime_sem_wait(sem_id semID, uint32 flags, bigtime_t timeout) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return syscall_restart_handle_post(context->AcquireSem(semID, flags, timeout)); }
18.739558
80
0.694375
waddlesplash
d78d1f9b1158a759beaa71ee7d7691a379527856
302
cpp
C++
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
3,457
2018-06-09T15:36:42.000Z
2020-06-01T22:09:25.000Z
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
851
2017-11-27T15:09:56.000Z
2022-03-31T22:26:38.000Z
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
1,380
2017-06-12T23:58:23.000Z
2022-03-31T14:52:48.000Z
#include "../Eigen/Sparse" #ifdef EIGEN_SHOULD_FAIL_TO_BUILD #define CV_QUALIFIER const #else #define CV_QUALIFIER #endif using namespace Eigen; void call_ref(Ref<SparseMatrix<float> > a) { } int main() { SparseMatrix<float> a(10,10); CV_QUALIFIER SparseMatrix<float>& ac(a); call_ref(ac); }
15.894737
46
0.735099
shareq2005
d78f2fb20a09ee0b8d8f582b63c44362766ad366
2,140
cpp
C++
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
102
2020-07-24T03:33:01.000Z
2022-03-29T01:21:47.000Z
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
35
2020-07-17T05:46:16.000Z
2022-03-21T08:56:00.000Z
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
19
2020-07-24T08:36:15.000Z
2021-12-19T18:46:47.000Z
#include <xcb/xcb.h> #include <i3ipc++/ipc.hpp> #include "common.hpp" #include "settings.hpp" #include "utils/i3.hpp" #include "utils/socket.hpp" #include "utils/string.hpp" #include "x11/connection.hpp" #include "x11/ewmh.hpp" #include "x11/icccm.hpp" POLYBAR_NS namespace i3_util { /** * Get all workspaces for given output */ vector<shared_ptr<workspace_t>> workspaces(const connection_t& conn, const string& output) { vector<shared_ptr<workspace_t>> result; for (auto&& ws : conn.get_workspaces()) { if (output.empty() || ws->output == output) { result.emplace_back(forward<decltype(ws)>(ws)); } } return result; } /** * Get currently focused workspace */ shared_ptr<workspace_t> focused_workspace(const connection_t& conn) { for (auto&& ws : conn.get_workspaces()) { if (ws->focused) { return ws; } } return nullptr; } /** * Get main root window */ xcb_window_t root_window(connection& conn) { auto children = conn.query_tree(conn.screen()->root).children(); const auto wm_name = [&](xcb_connection_t* conn, xcb_window_t win) -> string { string title; if (!(title = ewmh_util::get_wm_name(win)).empty()) { return title; } else if (!(title = icccm_util::get_wm_name(conn, win)).empty()) { return title; } else { return ""; } }; for (auto it = children.begin(); it != children.end(); it++) { if (wm_name(conn, *it) == "i3") { return *it; } } return XCB_NONE; } /** * Restack given window relative to the i3 root window * defined for the given monitor * * Fixes the issue with always-on-top window's */ bool restack_to_root(connection& conn, const xcb_window_t win) { const unsigned int value_mask = XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE; const unsigned int value_list[2]{root_window(conn), XCB_STACK_MODE_ABOVE}; if (value_list[0] != XCB_NONE) { conn.configure_window_checked(win, value_mask, value_list); return true; } return false; } } POLYBAR_NS_END
25.47619
94
0.634112
HughJass
d7909edf6498859f58ec5b5b0829689a0491d8fd
3,455
hpp
C++
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-07-29T01:28:10.000Z
2021-07-29T01:28:10.000Z
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
null
null
null
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2020-2021 the Autoware Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #ifndef JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #define JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #include <joystick_vehicle_interface/joystick_vehicle_interface.hpp> #include <joystick_vehicle_interface_nodes/visibility_control.hpp> #include <mpark_variant_vendor/variant.hpp> #include <rclcpp/rclcpp.hpp> #include <memory> #include <string> #include "autoware_auto_vehicle_msgs/msg/headlights_command.hpp" using autoware::common::types::bool8_t; using joystick_vehicle_interface::Axes; using joystick_vehicle_interface::Buttons; using joystick_vehicle_interface::AxisMap; using joystick_vehicle_interface::AxisScaleMap; using joystick_vehicle_interface::ButtonMap; namespace joystick_vehicle_interface_nodes { /// A node which translates sensor_msgs/msg/Joy messages into messages compatible with the vehicle /// interface. All participants use SensorDataQoS class JOYSTICK_VEHICLE_INTERFACE_NODES_PUBLIC JoystickVehicleInterfaceNode : public ::rclcpp::Node { public: /// ROS 2 parameter constructor explicit JoystickVehicleInterfaceNode(const rclcpp::NodeOptions & node_options); private: std::unique_ptr<joystick_vehicle_interface::JoystickVehicleInterface> m_core; JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void init( const std::string & control_command, const std::string & state_command_topic, const std::string & joy_topic, const bool8_t & recordreplay_command_enabled, const AxisMap & axis_map, const AxisScaleMap & axis_scale_map, const AxisScaleMap & axis_offset_map, const ButtonMap & button_map); /// Callback for joystick subscription: compute control and state command and publish JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void on_joy(const sensor_msgs::msg::Joy::SharedPtr msg); using HighLevelControl = autoware_auto_control_msgs::msg::HighLevelControlCommand; using BasicControl = autoware_auto_vehicle_msgs::msg::VehicleControlCommand; using RawControl = autoware_auto_vehicle_msgs::msg::RawControlCommand; template<typename T> using PubT = typename rclcpp::Publisher<T>::SharedPtr; using ControlPub = mpark::variant<PubT<RawControl>, PubT<BasicControl>, PubT<HighLevelControl>>; ControlPub m_cmd_pub{}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::VehicleStateCommand>::SharedPtr m_state_cmd_pub {}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::HeadlightsCommand>::SharedPtr m_headlights_cmd_pub{}; rclcpp::Publisher<std_msgs::msg::UInt8>::SharedPtr m_recordreplay_cmd_pub{}; rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr m_joy_sub{nullptr}; }; // class JoystickVehicleInterfaceNode } // namespace joystick_vehicle_interface_nodes #endif // JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_
41.626506
100
0.807236
ruvus
d79ae1b7bbda5efa225f13b85126be3c08ab891c
2,699
hpp
C++
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
1
2021-06-15T16:53:47.000Z
2021-06-15T16:53:47.000Z
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
null
null
null
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
3
2019-11-25T16:45:07.000Z
2021-11-27T02:56:43.000Z
/****************************************************************************** * MIT License * * Copyright (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ /** * @file IDectection.hpp * @author Kartik Madhira * @author Arjun Gupta * @author Aruna Baijal * @copyright MIT License (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * @brief Declares IDetection class */ #ifndef INCLUDE_IDETECTION_HPP_ #define INCLUDE_IDETECTION_HPP_ #include <ros/ros.h> #include <tf/transform_listener.h> #include <iostream> #include <vector> #include "geometry_msgs/PoseStamped.h" #include "std_msgs/Bool.h" /** * @brief Virtual Class for implementing the detection aspect of the bot */ class IDetection { public: /** * @brief function to set the tag ID for the tag * @param id associated with the ArUco marker of the object * @return void */ virtual void setTagId(int id) = 0; /** * @brief function to check if the tag is detected or not * @return bool if the tag is detected or not (true for yes) */ virtual bool detectTag() = 0; /** * @brief function to publish the pose of the detected object * @return void */ virtual void publishBoxPoses() = 0; /** * @brief function to check if the marker ID is same as the order * @return void */ virtual void detectionCallback(const \ std_msgs::Bool::ConstPtr& checkDetect) = 0; }; #endif // INCLUDE_IDETECTION_HPP_
36.472973
82
0.651723
Arjung27
d79ba9ac235a959ca0320e14e1486102d3b7c011
365
cpp
C++
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; bool isgiven_sum(int arr[],int n,int givsum){ int sum=0; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){//not working sum+=arr[j]; } if(givsum==sum){ return true; } } return false; } int main(){ int arr[]={1,4,20,3,10,5},n=6,givsum=33; cout<<isgiven_sum(arr,n,givsum)? "true": "false"; }
18.25
51
0.572603
ghostumar
d7a04cc8f2b9bc17331acb5bb62bfc755d3c7e16
727
cpp
C++
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include <iostream> #include <vector> using namespace std; vector<string> gss(string s){ // write your code here vector<string> x; if(s.length()==0){ x.push_back(""); return x; } string small=s.substr(0,s.length()-1); vector<string> getsub=gss(small); for(int i=0;i<getsub.size();i++){ x.push_back(getsub[i]+""); x.push_back(getsub[i]+s[s.length()-1]); } return x; } int main(){ string s; cin >> s; vector<string> ans = gss(s); int cnt = 0; cout << '['; for (string str : ans){ if (cnt != ans.size() - 1) cout << str << ", "; else cout << str; cnt++; } cout << ']'; }
19.648649
47
0.47868
anubhvshrma18
d7a2b17a1f66f7913737db71e7bb32adf02ce6e3
1,966
hpp
C++
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #define OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data_BA.hpp" namespace ceres { class CostFunction; } namespace openMVG { namespace cameras { struct IntrinsicBase; } } namespace openMVG { namespace sfm { struct SfM_Data; } } namespace openMVG { namespace sfm { /// Create the appropriate cost functor according the provided input camera intrinsic model /// Can be residual cost functor can be weighetd if desired (default 0.0 means no weight). ceres::CostFunction * IntrinsicsToCostFunction ( cameras::IntrinsicBase * intrinsic, const Vec2 & observation, const double weight = 0.0 ); class Bundle_Adjustment_Ceres : public Bundle_Adjustment { public: struct BA_Ceres_options { bool bVerbose_; unsigned int nb_threads_; bool bCeres_summary_; int linear_solver_type_; int preconditioner_type_; int sparse_linear_algebra_library_type_; double parameter_tolerance_; bool bUse_loss_function_; BA_Ceres_options(const bool bVerbose = true, bool bmultithreaded = true); }; private: BA_Ceres_options ceres_options_; public: explicit Bundle_Adjustment_Ceres ( const Bundle_Adjustment_Ceres::BA_Ceres_options & options = std::move(BA_Ceres_options()) ); BA_Ceres_options & ceres_options(); bool Adjust ( // the SfM scene to refine sfm::SfM_Data & sfm_data, // tell which parameter needs to be adjusted const Optimize_Options & options ) override; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_SFM_DATA_BA_CERES_HPP
27.305556
91
0.749746
Aurelio93
d7a3cab3d65cc1c3f9223dcc911714ac4b1e8059
2,438
cpp
C++
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
3
2019-10-30T07:37:47.000Z
2021-01-21T11:50:20.000Z
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
#define MAZE_TESTING #include "maze.h" #include "maze.cpp" #include "maze_generator.h" size_t size = 0; maze::Cell *real_cells; Directions maze::read_walls(maze::Position pos) { if (real_cells == nullptr) return Directions(); maze::Cell *cell = &real_cells[pos.y * size + pos.x]; return cell->walls; } Dir maze::choose_best_direction(Directions possible) { if (possible & Dir::N) return Dir::N; if (possible & Dir::S) return Dir::S; if (possible & Dir::E) return Dir::E; if (possible & Dir::W) return Dir::W; assert(0); } void maze::move_in_direction(Dir dir) { std::printf("Moving in direction %s\n", dir == Dir::N ? "N" : dir == Dir::S ? "S" : dir == Dir::E ? "E" : dir == Dir::W ? "W" : "ERROR"); } int main() { size = 4; const float mid = (size - 1) / 2.0; auto from = maze::Position(0, 0); auto to = maze::TargetPosition(int(mid)+1, int(mid)+1); // auto to = maze::TargetPosition(size-1, size-1); maze::Cell cells[size * size]; StaticStack<maze::Position, 64> stack; maze::Maze maze(size, size, cells, stack, from); // RANDOM MAZE GENERATION srand(time(NULL)); maze_gen::MazeGenerator generator; generator.create(size); real_cells = new maze::Cell[size * size]; for (int y = 0; y < generator._s; y++) { int yy = y * generator._s; for (int x = 0; x < generator._s; x++) { uint8_t b = generator._world[x + yy]; // change the Y addressing as they used standard gui addresing (y=0 at top) if( !( b & maze_gen::NOR ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::N; if( !( b & maze_gen::SOU ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::S; if( !( b & maze_gen::EAS ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::E; if( !( b & maze_gen::WES ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::W; } } StaticStack<maze::Position, 1> dummy_stack; maze::Maze real_maze(size, size, real_cells, dummy_stack, {0, 0}); real_maze.print(from, maze::Position(to.x, to.y)); std::cout << "Press enter to start." << std::endl; std::cin.get(); // RANDOM MAZE GENERATION bool success = maze.go_to(to); if (!success) std::cerr << "ERROR: could not finish maze!"; maze.print(maze.position(), maze::Position(to.x, to.y)); }
32.506667
95
0.566858
jedrzejboczar
d7a8e1ba84d571405b8c0f43e34128044661cb4e
1,880
cpp
C++
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
1
2018-01-30T19:37:27.000Z
2018-01-30T19:37:27.000Z
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
null
null
null
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
3
2017-04-01T23:41:35.000Z
2019-12-14T23:26:24.000Z
/*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Application.h" #include "M8rscript.h" static constexpr const char* WebServerRoot = "/sys/bin"; static m8r::Duration MainTaskSleepDuration = 10ms; m8r::Vector<const char*> fileList = { "scripts/mem.m8r", "scripts/mrsh.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/TimeZoneDBClient.m8r", "scripts/simple/basic.m8r", "scripts/simple/blink.m8r", "scripts/simple/hello.m8r", "scripts/simple/simpleFunction.m8r", "scripts/simple/simpleTest.m8r", "scripts/simple/simpleTest2.m8r", "scripts/timing/timing-esp.m8r", "scripts/timing/timing.m8r", "scripts/tests/TestBase64.m8r", "scripts/tests/TestClass.m8r", "scripts/tests/TestClosure.m8r", "scripts/tests/TestGibberish.m8r", "scripts/tests/TestIterator.m8r", "scripts/tests/TestLoop.m8r", "scripts/tests/TestTCPSocket.m8r", "scripts/tests/TestUDPSocket.m8r", }; m8rscript::M8rscriptScriptingLanguage m8rscriptScriptingLanguage; void m8rmain() { m8r::Application application(m8r::Application::HeartbeatType::Status, WebServerRoot, 23); // Upload files needed by web server m8r::Application::uploadFiles(fileList, WebServerRoot); m8r::system()->registerScriptingLanguage(&m8rscriptScriptingLanguage); application.runAutostartTask("/sys/bin/hello.m8r"); while(1) { application.runOneIteration(); MainTaskSleepDuration.sleep(); } }
31.864407
93
0.653723
cmarrin
d7a8ecaf32b327a527131adfd3093aa64dd3d4c4
3,544
cpp
C++
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/PSP-Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
11
2020-05-12T05:46:45.000Z
2020-07-13T13:11:56.000Z
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
6
2020-05-18T22:34:28.000Z
2020-07-11T01:17:55.000Z
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
1
2020-07-04T02:19:01.000Z
2020-07-04T02:19:01.000Z
#include "EntityManager.h" #include "../../Protocol/Play.h" #include "../World.h" #include "../../Utilities/Utils.h" #include <iostream> namespace Minecraft::Server::Internal::Entity { EntityManager::EntityManager() { } EntityManager::~EntityManager() { } void generateBaseObjectMeta(ByteBuffer* meta, Entity* obj){ //IDX meta->WriteBEInt8(0); //TYPE meta->WriteBEInt8(0); //VAL meta->WriteBEInt8(obj->flags); //IDX meta->WriteBEInt8(1); //TYPE meta->WriteBEInt8(1); //VAL meta->WriteVarInt32(obj->air); //IDX meta->WriteBEInt8(2); //TYPE meta->WriteBEInt8(5); //VAL if (obj->customName == "") { meta->WriteBool(false); }else{ meta->WriteBool(true); meta->WriteVarUTF8String(obj->customName); } //IDX meta->WriteBEInt8(3); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->isCustomNameAvailable); //IDX meta->WriteBEInt8(4); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->silent); //IDX meta->WriteBEInt8(5); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->noGravity); } void generateEndMeta(ByteBuffer* meta) { //IDX meta->WriteBEInt8(0xFF); } void generateItemMeta(ByteBuffer* meta, Inventory::Slot* slot){ //IDX meta->WriteBEInt8(6); //TYPE meta->WriteBEInt8(6); //SLOT DATA meta->WriteBool(slot->present); if(slot->present){ meta->WriteVarInt32(slot->id); meta->WriteBEInt8(slot->item_count); meta->WriteBEInt8(0); } } int EntityManager::addEntity(Entity* entity) { if (entity->objData != NULL) { //Spawn Protocol::Play::PacketsOut::send_spawn_object(entityCounter, entityCounter, entityCounter, entity->id, entity->objData->x, entity->objData->y, entity->objData->z, entity->objData->pitch, entity->objData->yaw, 1, entity->objData->vx, entity->objData->vy, entity->objData->vz); //Metadata ByteBuffer* meta = new ByteBuffer(128); //Meta generateBaseObjectMeta(meta, entity); if(entity->id == 2){ generateItemMeta(meta, &((ItemEntity*)entity)->item); } generateEndMeta(meta); Protocol::Play::PacketsOut::send_entity_metadata(entityCounter, *meta); //Velocity Protocol::Play::PacketsOut::send_entity_velocity(entityCounter, 0, 0, 0); } entities.emplace(entityCounter, entity); return entityCounter++; } void EntityManager::clearEntity() { //Probably should send client some info if this is called! //Probably should free ram too... entityCounter = 0; entities.clear(); } void EntityManager::init() { entityCounter = 0; entities.clear(); } void EntityManager::cleanup() { //TODO: DELETE! entityCounter = 0; entities.clear(); } void EntityManager::deleteEntity(int id) { Protocol::Play::PacketsOut::send_destroy_entities({ id }); if (entities.find(id) != entities.end()) { delete entities[id]; entities[id] = NULL; entities.erase(id); } } void EntityManager::update() { //Do something for (int i = 0; i < entities.size(); i++) { auto e = entities[i]; if (e != NULL) { if (e->id == 2) { if (Player::g_Player.x > e->objData->x - 1.0f && Player::g_Player.x < e->objData->x + 1.0f) { if (Player::g_Player.z > e->objData->z - 1.0f && Player::g_Player.z < e->objData->z + 1.0f) { if (Player::g_Player.y > e->objData->y - 2.75f && Player::g_Player.y < e->objData->y + 0.75f) { if (g_World->inventory.addItem(((ItemEntity*)e)->item)) { deleteEntity(i); } continue; } } } } } } } }
21.221557
278
0.634594
NT-Bourgeois-Iridescence-Technologies
92e4306b8a5fc7c904646aa26f8424a0ec5091ef
799
cpp
C++
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include <mutex> /* * This program tries to increment an integer 200 times in two threads. * We fix the race condition by locking a mutex before each increment. */ int main() { int nError = 0; for (int j = 0; j < 1000; j++) { int a = 0; std::mutex aMutex; // Increment the variable a 100 times: auto inc100 = [&a,&aMutex](){ for (int i = 0; i < 100; ++i) { std::scoped_lock lock{aMutex}; a++; } }; // Run with two threads std::thread t1(inc100); std::thread t2(inc100); for (auto t : {&t1,&t2}) t->join(); // Check if (a != 200) { std::cout << "Race: " << a << ' '; nError++; } else { std::cout << '.'; } } std::cout << '\n'; return nError; }
19.02381
71
0.516896
krasznaa
92eb006f07967cf8f11e35ea97f495edce2841c9
962
hpp
C++
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
1
2015-09-29T12:20:42.000Z
2015-09-29T12:20:42.000Z
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
null
null
null
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
null
null
null
#ifndef ATTACHMENTNYA_H #define ATTACHMENTNYA_H #include "CommonMail.hpp" #include <QIODevice> #include <QHash> #include <QByteArray> #include <QStringList> namespace Nya { class Attachment { QByteArray contentType; mutable s_p<QIODevice> content; QHash<QByteArray, QByteArray> extraHeaders; public: Attachment() : contentType("application/octet-stream") {} Attachment(const QString& filePath, const QByteArray& contentType = "application/octet-stream"); Attachment(QIODevice* device, const QByteArray& contentType = "application/octet-stream"); Attachment(const QByteArray* ba, const QByteArray& contentType = "application/octet-stream"); virtual ~Attachment(); QByteArray GetContentType() const { return contentType; } QHash<QByteArray, QByteArray>& GetExtraHeaders() { return extraHeaders; } void SetContentType(const QByteArray& contentType) { this->contentType = contentType;} QByteArray MimeData() const; }; } #endif // ATTACHMENTNYA_H
26.722222
97
0.774428
Akela1101
92eee5a17f2abd600bab5ca1cbc276ad3f1be60a
1,395
cpp
C++
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
25
2021-11-03T17:53:46.000Z
2022-03-29T00:52:47.000Z
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
70
2021-09-17T23:02:24.000Z
2022-03-30T02:30:16.000Z
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
5
2022-01-18T03:35:55.000Z
2022-03-20T09:35:40.000Z
#include <boost/ut.hpp> #include <libembeddedhal/static_callable.hpp> namespace embed { boost::ut::suite static_callable_test = []() { using namespace boost::ut; // Setup class dummy_driver {}; "static_callable void(void)"_test = []() { // Setup using callback1_signature = void (*)(void); bool callback1_was_called = false; auto callable1 = static_callable<dummy_driver, 1, void(void)>( [&callback1_was_called]() { callback1_was_called = true; }); callback1_signature callback1 = callable1.get_handler(); // Exercise & Verify expect(that % false == callback1_was_called); callback1(); expect(that % true == callback1_was_called); }; "static_callable void(bool)"_test = []() { // Setup using callback2_signature = void (*)(bool); bool callback2_was_called = false; bool captured_bool = false; auto callable2 = static_callable<dummy_driver, 2, void(bool)>( [&callback2_was_called, &captured_bool](bool value) { callback2_was_called = true; captured_bool = value; }); callback2_signature callback2 = callable2.get_handler(); // Exercise & Verify expect(that % false == captured_bool); callback2(true); expect(that % true == callback2_was_called); expect(that % true == captured_bool); callback2(false); expect(that % false == captured_bool); }; }; }
27.352941
66
0.664516
HuangDave
92f1187cbd7ec304bc0c541237d6949e7e72fe75
3,939
hh
C++
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
#include <getopt.h> #include "mmutil.hh" #include "io.hh" #include "mmutil_embedding.hh" #ifndef MMUTIL_ANNOTATE_EMBEDDING_HH_ #define MMUTIL_ANNOTATE_EMBEDDING_HH_ struct embedding_options_t { using Str = std::string; typedef enum { UNIFORM, CV, MEAN } sampling_method_t; const std::vector<Str> METHOD_NAMES; embedding_options_t() { out = "output.txt.gz"; embedding_dim = 2; embedding_epochs = 1000; exaggeration = 100; tol = 1e-8; verbose = false; l2_penalty = 1e-4; } Str data_file; Str prob_file; Str out; Index embedding_dim; Index embedding_epochs; Index exaggeration; Scalar tol; Scalar l2_penalty; bool verbose; }; template <typename T> int parse_embedding_options(const int argc, // const char *argv[], // T &options) { const char *_usage = "\n" "[Arguments]\n" "--data (-m) : data matrix file\n" "--prob (-p) : probability matrix file\n" "--out (-o) : Output file header\n" "\n" "--embedding_dim (-d) : latent dimensionality (default: 2)\n" "--embedding_epochs (-i) : Maximum iteration (default: 100)\n" "--l2 (-l) : L2 penalty (default: 1e-4)\n" "--tol (-t) : Convergence criterion (default: 1e-4)\n" "--verbose (-v) : Set verbose (default: false)\n" "\n"; const char *const short_opts = "m:p:o:d:i:t:l:hv"; const option long_opts[] = { { "data", required_argument, nullptr, 'm' }, // { "prob", required_argument, nullptr, 'p' }, // { "out", required_argument, nullptr, 'o' }, // { "embedding_dim", required_argument, nullptr, 'd' }, // { "embed_dim", required_argument, nullptr, 'd' }, // { "dim", required_argument, nullptr, 'd' }, // { "embedding_epochs", required_argument, nullptr, 'i' }, // { "l2", required_argument, nullptr, 'l' }, // { "l2_penalty", required_argument, nullptr, 'l' }, // { "tol", required_argument, nullptr, 't' }, // { "verbose", no_argument, nullptr, 'v' }, // { nullptr, no_argument, nullptr, 0 } }; while (true) { const auto opt = getopt_long(argc, // const_cast<char **>(argv), // short_opts, // long_opts, // nullptr); if (-1 == opt) break; switch (opt) { case 'm': options.data_file = std::string(optarg); break; case 'p': options.prob_file = std::string(optarg); break; case 'o': options.out = std::string(optarg); break; case 'd': options.embedding_dim = std::stoi(optarg); break; case 'i': options.embedding_epochs = std::stoi(optarg); break; case 't': options.tol = std::stof(optarg); break; case 'l': options.l2_penalty = std::stof(optarg); break; case 'v': // -v or --verbose options.verbose = true; break; case 'h': // -h or --help case '?': // Unrecognized option std::cerr << _usage << std::endl; return EXIT_FAILURE; default: // ; } } ERR_RET(!file_exists(options.data_file), "No data matrix file"); ERR_RET(!file_exists(options.prob_file), "No probability file"); return EXIT_SUCCESS; } #endif
28.751825
75
0.475248
YPARK
92f19fedfbad7ade5b9e148509bdae67ac704c43
5,809
cpp
C++
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
94
2021-04-23T03:31:15.000Z
2022-03-29T08:20:26.000Z
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
64
2021-05-05T21:51:15.000Z
2022-02-08T17:06:52.000Z
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
3
2021-07-06T04:58:27.000Z
2022-02-08T16:53:48.000Z
// // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #include "ppm.h" #include <cmath> #include <cstdio> #include <iostream> #include <stdexcept> #include <string> using namespace std; namespace { struct RGB { unsigned char r; unsigned char g; unsigned char b; }; } // end namespace bool is_ppm_image(const char *filename) { FILE *infile = nullptr; int numInputsRead = 0; char buffer[256]; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size int width, height; numInputsRead = sscanf(buffer, "%d %d", &width, &height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) int colors; numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); if (colors != 255) throw std::runtime_error("max color value must be 255."); fclose(infile); return true; } catch (const std::exception &e) { if (infile) fclose(infile); return false; } } float *load_ppm_image(const char *filename, int *width, int *height, int *numChannels) { FILE * infile = nullptr; float *img = nullptr; int colors; int numInputsRead = 0; float invColors; char buffer[256]; RGB * buf = nullptr; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); *numChannels = 3; // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size numInputsRead = sscanf(buffer, "%d %d", width, height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); invColors = 1.0f / colors; if (colors != 255) throw std::runtime_error("max color value must be 255."); img = new float[*width * *height * 3]; buf = new RGB[*width]; for (int y = 0; y < *height; ++y) { if (fread(buf, *width * sizeof(RGB), 1, infile) != 1) throw std::runtime_error("cannot read pixel data."); RGB * cur = buf; float *curLine = &img[y * *width * 3]; for (int x = 0; x < *width; x++) { curLine[3 * x + 0] = cur->r * invColors; curLine[3 * x + 1] = cur->g * invColors; curLine[3 * x + 2] = cur->b * invColors; cur++; } } delete[] buf; fclose(infile); return img; } catch (const std::exception &e) { delete[] buf; delete[] img; if (infile) fclose(infile); throw std::runtime_error(string("ERROR in load_ppm_image: ") + string(e.what()) + string(" Unable to read PPM file '") + filename + "'"); } } bool write_ppm_image(const char *filename, int width, int height, int numChannels, const unsigned char *data) { FILE *outfile = nullptr; try { outfile = fopen(filename, "wb"); if (!outfile) throw std::runtime_error("cannot open file."); // write header fprintf(outfile, "P6\n"); fprintf(outfile, "%d %d\n", width, height); fprintf(outfile, "255\n"); auto numChars = static_cast<size_t>(numChannels * width * height); if (fwrite(data, sizeof(unsigned char), numChars, outfile) != numChars) throw std::runtime_error("cannot write pixel data."); fclose(outfile); return true; } catch (const std::exception &e) { if (outfile) fclose(outfile); throw std::runtime_error(string("ERROR in write_ppm_image: ") + string(e.what()) + string(" Unable to write PPM file '") + string(filename) + "'"); } }
29.943299
114
0.542262
GhostatSpirit
92f49b08d0b67c77daad20287e89fd0574fd0434
16,314
cpp
C++
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
1
2022-03-09T10:01:13.000Z
2022-03-09T10:01:13.000Z
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
1
2021-11-18T02:16:15.000Z
2021-11-18T03:16:57.000Z
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
3
2021-11-08T16:21:16.000Z
2021-11-10T06:39:48.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <gtest/gtest.h> #include "graph/context/QueryContext.h" #include "graph/executor/algo/ProduceSemiShortestPathExecutor.h" #include "graph/planner/plan/Algo.h" namespace nebula { namespace graph { class ProduceSemiShortestPathTest : public testing::Test { protected: static bool compareShortestPath(Row& row1, Row& row2) { // row : dst | src | cost | {paths} if (row1.values[0] != row2.values[0]) { return row1.values[0] < row2.values[0]; } if (row1.values[1] != row2.values[1]) { return row1.values[1] < row2.values[1]; } if (row1.values[2] != row2.values[2]) { return row1.values[2] < row2.values[2]; } auto& pathList1 = row1.values[3].getList(); auto& pathList2 = row2.values[3].getList(); if (pathList1.size() != pathList2.size()) { return pathList1.size() < pathList2.size(); } for (size_t i = 0; i < pathList1.size(); i++) { if (pathList1.values[i] != pathList2.values[i]) { return pathList1.values[i] < pathList2.values[i]; } } return false; } void SetUp() override { qctx_ = std::make_unique<QueryContext>(); /* * 0->1->5->7; * 1->6->7 * 2->6->7 * 3->4->7 * startVids {0, 1, 2, 3} */ { DataSet ds1; ds1.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 0->1 Row row; row.values.emplace_back("0"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("1"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 2->6 Row row; row.values.emplace_back("2"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("6"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 3->4 Row row; row.values.emplace_back("3"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("4"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } firstStepResult_ = std::move(ds1); DataSet ds2; ds2.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } { // 4->7, 5->7, 6->7 for (auto i = 4; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } } secondStepResult_ = std::move(ds2); DataSet ds3; ds3.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 5->7, 6->7 for (auto i = 5; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds3.rows.emplace_back(std::move(row)); } } thridStepResult_ = std::move(ds3); { DataSet ds; ds.colNames = {kVid, "_stats", "_tag:tag1:prop1:prop2", "_edge:+edge1:prop1:prop2:_dst:_rank", "_expr"}; qctx_->symTable()->newVariable("empty_get_neighbors"); qctx_->ectx()->setResult("empty_get_neighbors", ResultBuilder() .value(Value(std::move(ds))) .iter(Iterator::Kind::kGetNeighbors) .build()); } } } protected: std::unique_ptr<QueryContext> qctx_; DataSet firstStepResult_; DataSet secondStepResult_; DataSet thridStepResult_; }; TEST_F(ProduceSemiShortestPathTest, ShortestPath) { qctx_->symTable()->newVariable("input"); auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("input"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); // Step 1 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(firstStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 1; { // 0->1 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("1"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->6 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("4"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step 2 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(secondStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 2; { // 0->1->5 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 0->1->6 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6->7 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4->7 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5->7, 1->6->7 List paths; { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step3 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(thridStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 3; { // 0->1->5->7, 0->1->6->7 List paths; { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } TEST_F(ProduceSemiShortestPathTest, EmptyInput) { auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("empty_get_neighbors"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; EXPECT_EQ(result.value().getDataSet(), expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } // namespace graph } // namespace nebula
31.988235
86
0.567243
heyanlong
92f81a3f201aae9487ca7105f8d1f813eead65b8
4,090
cpp
C++
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
3
2022-02-12T06:54:20.000Z
2022-02-26T21:54:59.000Z
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
null
null
null
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
null
null
null
#include <cage-core/logger.h> #include <cage-core/ini.h> #include <cage-core/config.h> #include <cage-core/files.h> #include <cage-core/image.h> #include <qasm/qasm.h> using namespace qasm; int main(int argc, const char *args[]) { try { Holder<Logger> logger = newLogger(); logger->format.bind<logFormatConsole>(); logger->output.bind<logOutputStdOut>(); ConfigString programPath("imgmod/path/program", "imgmod.qasm"); ConfigString limitsPath("imgmod/path/limits"); ConfigString inputPath("imgmod/path/input"); ConfigString outputPath("imgmod/path/output"); { Holder<Ini> ini = newIni(); ini->parseCmd(argc, args); programPath = ini->cmdString('p', "program", programPath); limitsPath = ini->cmdString('l', "limits", limitsPath); inputPath = ini->cmdString('i', "input", inputPath); outputPath = ini->cmdString('o', "output", outputPath); ini->checkUnusedWithHelp(); } if (string(inputPath).empty() || string(outputPath).empty()) CAGE_THROW_ERROR(Exception, "no input or output path"); Holder<Image> img = newImage(); ImageFormatEnum originalFormat = ImageFormatEnum::Default; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading image at path: '" + string(inputPath) + "'"); img->importFile(inputPath); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); originalFormat = img->format(); imageConvert(+img, ImageFormatEnum::Float); } Holder<Program> program; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading program at path: '" + string(programPath) + "'"); Holder<File> file = readFile(programPath); Holder<Compiler> compiler = newCompiler(); program = compiler->compile(file->readAll()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "program has: " + program->instructionsCount() + " instructions"); } Holder<Cpu> cpu; { CpuCreateConfig cfg; for (uint32 i = 0; i < 4; i++) cfg.limits.memoryCapacity[i] = img->width() * img->height() * img->channels(); if (!string(limitsPath).empty()) { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading limits at path: '" + string(limitsPath) + "'"); Holder<Ini> limits = newIni(); limits->importFile(limitsPath); cfg.limits = qasm::limitsFromIni(+limits, cfg.limits); } cpu = newCpu(cfg); cpu->program(+program); } { auto fv = img->rawViewFloat(); cpu->memory(0, { (const uint32 *)fv.begin(), (const uint32 *)fv.end() }); uint32 regs[26]; regs['W' - 'A'] = img->width(); regs['H' - 'A'] = img->height(); regs['C' - 'A'] = img->channels(); cpu->registers(regs); } try { cpu->run(); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "finished in " + cpu->stepIndex() + " steps"); } catch (...) { CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "function: " + program->functionName(cpu->functionIndex())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "source: " + program->sourceCodeLine(cpu->sourceLine())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "line: " + (cpu->sourceLine() + 1)); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "step: " + cpu->stepIndex()); throw; } { Holder<Image> img = newImage(); const auto mem = cpu->memory(0); const auto regs = cpu->registers(); img->importRaw({ (const char *)mem.begin(), (const char *)mem.end() }, regs['W' - 'A'], regs['H' - 'A'], regs['C' - 'A'], ImageFormatEnum::Float); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); imageConvert(+img, originalFormat); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "saving image at path: '" + string(outputPath) + "'"); img->exportFile(outputPath); } return 0; } catch (...) { detail::logCurrentCaughtException(); } return 1; }
34.369748
149
0.641565
ucpu
92f8e1f6514e85c5bf42a3993e7f18e326dabcdc
2,120
cpp
C++
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; // structure to denote node in list typedef struct node { // member to hold data of node int data; // pointer to next node struct node* next; }node; // a node to point to some element in the list node* start; /* Function: preety_print Desc: utility for printing elements in intuitive format Args: element -> element if list that is going to be printed Returns: preety_string -> prettified string version for element */ string preety_print(int element) { int dashes = to_string(element).size() + 6; string preety_string; for(int i = 0; i < dashes; ++i) preety_string += "_"; return preety_string; } /* Function: print_list Desc: prints the given circular linked list Args: start -> any pointer pointing to a node in the list Returns: None */ void print_list(node* start) { // node for traversing the list node* end = start; // if there is a single element in the list if(start->next == start) { cout << "\t" << start->data << "\n\n"; return; } cout << "\t"; string line_below(" |"); // keep traversing the list until we reach the start node do { // print the current node cout << end->data; if(end->next != start) { line_below += preety_print(end->data); cout << " ---> "; } // move end to next node end = end->next; }while(end != start); line_below[line_below.size()-1] = '|'; cout << "\n" << line_below <<"\n\n"; } /* Function: cleanup Desc: deallocates memory of all nodes in list Args: start -> pointer to any node in list Returns: None */ void cleanup(node* start) { // pointer for traversal node* end = start; // loop through all the nodes do { cout << "\tDelete " << end->data << "\n"; // temporarily hold location of end node node* temp = end; // increment the end node end = end->next; // deallocate the current node free(temp); }while(end != start); }
20.784314
63
0.586792
AshishS-1123
92fddcb009cb6a3a4adfe664713c50e01256f673
1,666
cc
C++
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
6
2019-01-11T04:11:33.000Z
2019-12-12T09:01:46.000Z
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
null
null
null
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
5
2019-01-11T03:38:00.000Z
2019-12-04T11:08:01.000Z
// Copyright (c) 2018-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "include/pika_cmd_table_manager.h" PikaCmdTableManager::PikaCmdTableManager() { pthread_rwlock_init(&map_protector_, NULL); } PikaCmdTableManager::~PikaCmdTableManager() { pthread_rwlock_destroy(&map_protector_); for (const auto& item : thread_table_map_) { CmdTable* cmd_table = item.second; CmdTable::const_iterator it = cmd_table->begin(); for (; it != cmd_table->end(); ++it) { delete it->second; } delete cmd_table; } } Cmd* PikaCmdTableManager::GetCmd(const std::string& opt) { pid_t tid = gettid(); CmdTable* cmd_table = nullptr; if (!CheckCurrentThreadCmdTableExist(tid)) { InsertCurrentThreadCmdTable(); } slash::RWLock l(&map_protector_, false); cmd_table = thread_table_map_[tid]; CmdTable::const_iterator iter = cmd_table->find(opt); if (iter != cmd_table->end()) { return iter->second; } return NULL; } bool PikaCmdTableManager::CheckCurrentThreadCmdTableExist(const pid_t& tid) { slash::RWLock l(&map_protector_, false); if (thread_table_map_.find(tid) == thread_table_map_.end()) { return false; } return true; } void PikaCmdTableManager::InsertCurrentThreadCmdTable() { pid_t tid = gettid(); CmdTable* cmds = new CmdTable(); cmds->reserve(300); InitCmdTable(cmds); slash::RWLock l(&map_protector_, true); thread_table_map_.insert(make_pair(tid, cmds)); }
29.75
78
0.719088
yihaoDeng
1302950cea1520981d3001bc8f8d5fcc6cf19c5e
110,231
cpp
C++
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
1
2015-05-08T22:47:13.000Z
2015-05-08T22:47:13.000Z
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
null
null
null
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
null
null
null
 /* Copyright (c) 2009-2015 Maximus5 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define DROP_SETCP_ON_WIN2K3R2 //#define SKIPHOOKLOG //#define USE_ONLY_INT_CHECK_PTR #undef USE_ONLY_INT_CHECK_PTR // Иначе не опередяется GetConsoleAliases (хотя он должен быть доступен в Win2k) #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #define DEFINE_HOOK_MACROS #ifdef _DEBUG #define HOOK_ERROR_PROC //#undef HOOK_ERROR_PROC #define HOOK_ERROR_NO ERROR_INVALID_DATA #else #undef HOOK_ERROR_PROC #endif #define USECHECKPROCESSMODULES //#define ASSERT_ON_PROCNOTFOUND #include <windows.h> #include <Tlhelp32.h> #ifndef __GNUC__ #include <intrin.h> #else #define _InterlockedIncrement InterlockedIncrement #endif #include "../common/common.hpp" #include "../common/ConEmuCheck.h" #include "../common/MSection.h" #include "../common/WObjects.h" //#include "../common/MArray.h" #include "ShellProcessor.h" #include "SetHook.h" #include "ConEmuHooks.h" #include "Ansi.h" #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #define DebugString(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugString(x) #define DebugStringA(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugStringA(x) #else #define DebugString(x) #define DebugStringA(x) #endif HMODULE ghOurModule = NULL; // Хэндл нашей dll'ки (здесь хуки не ставятся) DWORD gnHookMainThreadId = 0; MMap<DWORD,BOOL> gStartedThreads; extern HWND ghConWnd; // RealConsole extern BOOL gbDllStopCalled; extern BOOL gbHooksWasSet; extern bool gbPrepareDefaultTerminal; #ifdef _DEBUG bool gbSuppressShowCall = false; bool gbSkipSuppressShowCall = false; bool gbSkipCheckProcessModules = false; #endif bool gbHookExecutableOnly = false; //!!!All dll names MUST BE LOWER CASE!!! //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! const wchar_t *kernelbase = L"kernelbase.dll", *kernelbase_noext = L"kernelbase"; const wchar_t *kernel32 = L"kernel32.dll", *kernel32_noext = L"kernel32"; const wchar_t *user32 = L"user32.dll", *user32_noext = L"user32"; const wchar_t *gdi32 = L"gdi32.dll", *gdi32_noext = L"gdi32"; const wchar_t *shell32 = L"shell32.dll", *shell32_noext = L"shell32"; const wchar_t *advapi32 = L"advapi32.dll", *advapi32_noext = L"advapi32"; const wchar_t *comdlg32 = L"comdlg32.dll", *comdlg32_noext = L"comdlg32"; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! HMODULE ghKernelBase = NULL, ghKernel32 = NULL, ghUser32 = NULL, ghGdi32 = NULL, ghShell32 = NULL, ghAdvapi32 = NULL, ghComdlg32 = NULL; HMODULE* ghSysDll[] = {&ghKernelBase, &ghKernel32, &ghUser32, &ghGdi32, &ghShell32, &ghAdvapi32, &ghComdlg32}; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; }; enum LDR_DLL_NOTIFICATION_REASON { LDR_DLL_NOTIFICATION_REASON_LOADED = 1, LDR_DLL_NOTIFICATION_REASON_UNLOADED = 2, }; struct LDR_DLL_LOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; struct LDR_DLL_UNLOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; union LDR_DLL_NOTIFICATION_DATA { LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; }; typedef VOID (CALLBACK* PLDR_DLL_NOTIFICATION_FUNCTION)(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); typedef NTSTATUS (NTAPI* LdrRegisterDllNotification_t)(ULONG Flags, PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, PVOID Context, PVOID *Cookie); typedef NTSTATUS (NTAPI* LdrUnregisterDllNotification_t)(PVOID Cookie); static LdrRegisterDllNotification_t LdrRegisterDllNotification = NULL; static LdrUnregisterDllNotification_t LdrUnregisterDllNotification = NULL; static PVOID gpLdrDllNotificationCookie = NULL; static NTSTATUS gnLdrDllNotificationState = (NTSTATUS)-1; static bool gbLdrDllNotificationUsed = false; // Forwards bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot = FALSE, BOOL abForceHooks = FALSE); void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep); //typedef LONG (WINAPI* RegCloseKey_t)(HKEY hKey); RegCloseKey_t RegCloseKey_f = NULL; //typedef LONG (WINAPI* RegOpenKeyEx_t)(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); RegOpenKeyEx_t RegOpenKeyEx_f = NULL; //typedef LONG (WINAPI* RegCreateKeyEx_t(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); RegCreateKeyEx_t RegCreateKeyEx_f = NULL; //typedef BOOL (WINAPI* OnChooseColorA_t)(LPCHOOSECOLORA lpcc); OnChooseColorA_t ChooseColorA_f = NULL; //typedef BOOL (WINAPI* OnChooseColorW_t)(LPCHOOSECOLORW lpcc); OnChooseColorW_t ChooseColorW_f = NULL; struct PreloadFuncs { LPCSTR sFuncName; void** pFuncPtr; }; struct PreloadModules { LPCWSTR sModule, sModuleNoExt; HMODULE *pModulePtr; PreloadFuncs Funcs[5]; }; size_t GetPreloadModules(PreloadModules** ppModules) { static PreloadModules Checks[] = { {gdi32, gdi32_noext, &ghGdi32}, {shell32, shell32_noext, &ghShell32}, {advapi32, advapi32_noext, &ghAdvapi32, {{"RegOpenKeyExW", (void**)&RegOpenKeyEx_f}, {"RegCreateKeyExW", (void**)&RegCreateKeyEx_f}, {"RegCloseKey", (void**)&RegCloseKey_f}} }, {comdlg32, comdlg32_noext, &ghComdlg32, {{"ChooseColorA", (void**)&ChooseColorA_f}, {"ChooseColorW", (void**)&ChooseColorW_f}} }, }; *ppModules = Checks; return countof(Checks); } void CheckLoadedModule(LPCWSTR asModule) { if (!asModule || !*asModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != NULL) continue; if (!lstrcmpiW(asModule, Checks[m].sModule) || !lstrcmpiW(asModule, Checks[m].sModuleNoExt)) { *Checks[m].pModulePtr = LoadLibraryW(Checks[m].sModule); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик if ((*Checks[m].pModulePtr) != NULL) { _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = (void*)GetProcAddress(*Checks[m].pModulePtr, Checks[m].Funcs[f].sFuncName); } } } } } void FreeLoadedModule(HMODULE hModule) { if (!hModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != hModule) continue; if (GetModuleHandle(Checks[m].sModule) == NULL) { // По идее, такого быть не должно, т.к. счетчик мы накрутили, библиотека не должна была выгрузиться _ASSERTEX(*Checks[m].pModulePtr == NULL); *Checks[m].pModulePtr = NULL; _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = NULL; } } } } #define MAX_HOOKED_PROCS 255 // Использовать GetModuleFileName или CreateToolhelp32Snapshot во время загрузки библиотек нельзя // Однако, хранить список модулей нужно // 1. для того, чтобы знать, в каких модулях хуки уже ставились // 2. для информации, чтобы передать в ConEmu если пользователь включил "Shell and processes log" struct HkModuleInfo { BOOL bUsed; // ячейка занята int Hooked; // 1-модуль обрабатывался (хуки установлены), 2-хуки сняты HMODULE hModule; // хэндл wchar_t sModuleName[128]; // Только информационно, в обработке не участвует HkModuleInfo* pNext; HkModuleInfo* pPrev; size_t nAdrUsed; struct StrAddresses { DWORD_PTR* ppAdr; #ifdef _DEBUG DWORD_PTR ppAdrCopy1, ppAdrCopy2; DWORD_PTR pModulePtr, nModuleSize; #endif DWORD_PTR pOld; DWORD_PTR pOur; union { BOOL bHooked; LPVOID Dummy; }; #ifdef _DEBUG char sName[32]; #endif } Addresses[MAX_HOOKED_PROCS]; }; WARNING("Хорошо бы выделять память под gpHookedModules через VirtualProtect, чтобы защитить ее от изменений дурными программами"); HkModuleInfo *gpHookedModules = NULL, *gpHookedModulesLast = NULL; size_t gnHookedModules = 0; MSectionSimple *gpHookedModulesSection = NULL; void InitializeHookedModules() { _ASSERTE(gpHookedModules==NULL && gpHookedModulesSection==NULL); if (!gpHookedModulesSection) { //MessageBox(NULL, L"InitializeHookedModules", L"Hooks", MB_SYSTEMMODAL); gpHookedModulesSection = new MSectionSimple(true); //WARNING: "new" вызывать из DllStart нельзя! DllStart вызывается НЕ из главной нити, //WARNING: причем, когда главная нить еще не была запущена. В итоге, если это //WARNING: попытаться сделать мы получим: //WARNING: runtime error R6030 - CRT not initialized // -- gpHookedModules = new MArray<HkModuleInfo>; // -- поэтому тупо через массив //#ifdef _DEBUG //gnHookedModules = 16; //#else //gnHookedModules = 256; //#endif gpHookedModules = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); } gpHookedModulesLast = gpHookedModules; } } void FinalizeHookedModules() { HLOG1("FinalizeHookedModules",0); if (gpHookedModules) { MSectionLockSimple CS; if (gpHookedModulesSection) CS.Lock(gpHookedModulesSection); HkModuleInfo *p = gpHookedModules; gpHookedModules = NULL; while (p) { HkModuleInfo *pNext = p->pNext; free(p); p = pNext; } } SafeDelete(gpHookedModulesSection); HLOGEND1(); } HkModuleInfo* IsHookedModule(HMODULE hModule, LPWSTR pszName = NULL, size_t cchNameMax = 0) { if (!gpHookedModulesSection) InitializeHookedModules(); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return false; } //bool lbHooked = false; //_ASSERTE(gpHookedModules && gpHookedModulesSection); //if (bSection) // Enter Critical Section(gpHookedModulesSection); HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { _ASSERTE(p->Hooked == 1 || p->Hooked == 2); //lbHooked = true; // Если хотят узнать имя модуля (по hModule) if (pszName && (cchNameMax > 0)) lstrcpyn(pszName, p->sModuleName, (int)cchNameMax); break; } p = p->pNext; } //if (bSection) // Leave Critical Section(gpHookedModulesSection); return p; } HkModuleInfo* AddHookedModule(HMODULE hModule, LPCWSTR sModuleName) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return NULL; } HkModuleInfo* p = IsHookedModule(hModule); if (!p) { MSectionLockSimple CS; CS.Lock(gpHookedModulesSection); p = gpHookedModules; while (p) { if (!p->bUsed) { p->bUsed = TRUE; // сразу зарезервируем gnHookedModules++; memset(p->Addresses, 0, sizeof(p->Addresses)); p->nAdrUsed = 0; p->Hooked = 1; lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); // hModule - последним, чтобы не было проблем с другими потоками p->hModule = hModule; goto wrap; } p = p->pNext; } p = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!p) { _ASSERTE(p!=NULL); } else { gnHookedModules++; p->bUsed = TRUE; // ячейка занята. тут можно первой, т.к. в цепочку еще не добавили p->Hooked = 1; // модуль обрабатывался (хуки установлены) p->hModule = hModule; // хэндл lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); //_ASSERTEX(lstrcmpi(p->sModuleName,L"dsound.dll")); p->pNext = NULL; p->pPrev = gpHookedModulesLast; gpHookedModulesLast->pNext = p; gpHookedModulesLast = p; } } wrap: return p; } void RemoveHookedModule(HMODULE hModule) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return; } HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { gnHookedModules--; // Именно в такой последовательности, чтобы с другими потоками не драться p->Hooked = 0; p->bUsed = FALSE; break; } p = p->pNext; } } BOOL gbHooksTemporaryDisabled = FALSE; //BOOL gbInShellExecuteEx = FALSE; //typedef VOID (WINAPI* OnLibraryLoaded_t)(HMODULE ahModule); HMODULE ghOnLoadLibModule = NULL; OnLibraryLoaded_t gfOnLibraryLoaded = NULL; OnLibraryLoaded_t gfOnLibraryUnLoaded = NULL; // Forward declarations of the hooks FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName); FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName); HMODULE WINAPI OnLoadLibraryA(const char* lpFileName); HMODULE WINAPI OnLoadLibraryW(const WCHAR* lpFileName); HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags); HMODULE WINAPI OnLoadLibraryExW(const WCHAR* lpFileName, HANDLE hFile, DWORD dwFlags); BOOL WINAPI OnFreeLibrary(HMODULE hModule); #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError(); VOID WINAPI OnSetLastError(DWORD dwErrCode); #endif HookItem *gpHooks = NULL; size_t gnHookedFuncs = 0; //bool gbHooksSorted = false; #if 0 struct HookItemNode { const char* Name; HookItem *p; HookItemNode *pLeft; HookItemNode *pRight; #ifdef _DEBUG size_t nLeftCount; size_t nRightCount; #endif }; HookItemNode *gpHooksTree = NULL; // [MAX_HOOKED_PROCS] HookItemNode *gpHooksRoot = NULL; // Pointer to the "root" item in gpHooksTree #endif //struct HookItemNodePtr //{ // const void* Address; // HookItem *p; // HookItemNodePtr *pLeft; // HookItemNodePtr *pRight; //#ifdef _DEBUG // size_t nLeftCount; // size_t nRightCount; //#endif //}; //HookItemNodePtr *gpHooksTreePtr = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootPtr = NULL; // Pointer to the "root" item in gpHooksTreePtr //MSectionSimple* gpcsHooksRootPtr = NULL; //HookItemNodePtr *gpHooksTreeNew = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootNew = NULL; // Pointer to the "root" item in gpHooksTreePtr const char *szGetProcAddress = "GetProcAddress"; const char *szLoadLibraryA = "LoadLibraryA"; const char *szLoadLibraryW = "LoadLibraryW"; const char *szLoadLibraryExA = "LoadLibraryExA"; const char *szLoadLibraryExW = "LoadLibraryExW"; const char *szFreeLibrary = "FreeLibrary"; const char *szWriteConsoleW = "WriteConsoleW"; #ifdef HOOK_ERROR_PROC const char *szGetLastError = "GetLastError"; const char *szSetLastError = "SetLastError"; #endif #define HOOKEXPADDRESSONLY enum HookLibFuncs { hlfGetProcAddress = 0, hlfKernelLast, }; struct HookItemWork { HMODULE hLib; FARPROC OldAddress; FARPROC NewAddress; const char* Name; } gKernelFuncs[hlfKernelLast] = {};/* = { {NULL, OnGetProcAddressExp, szGetProcAddress}, };*/ void InitKernelFuncs() { #undef SETFUNC #define SETFUNC(m,i,f,n) \ gKernelFuncs[i].hLib = m; \ gKernelFuncs[i].OldAddress = NULL; \ gKernelFuncs[i].NewAddress = (FARPROC)f; \ gKernelFuncs[i].Name = n; WARNING("Захукать бы LdrGetProcAddressEx в ntdll.dll, но там нужно не просто экспорты менять, а ставить jmp на входе в функцию"); SETFUNC(ghKernel32/*(ghKernelBase?ghKernelBase:ghKernel32)*/, hlfGetProcAddress, OnGetProcAddressExp, szGetProcAddress); // Индексы первых функций должны совпадать, т.к. там инфа по callback-ам #ifdef _DEBUG if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); } else { for (int f = 0; f < hlfKernelLast; f++) { _ASSERTEX(gpHooks[f].Name==gKernelFuncs[f].Name); } } #endif #undef SETFUNC } bool InitHooksLibrary() { #ifndef HOOKS_SKIP_LIBRARY if (!gpHooks) { _ASSERTE(gpHooks!=NULL); return false; } if (gpHooks[0].NewAddress != NULL) { _ASSERTE(gpHooks[0].NewAddress==NULL); return false; } gnHookedFuncs = 0; #define ADDFUNC(pProc,szName,szDll) \ gpHooks[gnHookedFuncs].NewAddress = pProc; \ gpHooks[gnHookedFuncs].Name = szName; \ gpHooks[gnHookedFuncs].DllName = szDll; \ if (pProc/*need to be, ignore GCC warn*/) gnHookedFuncs++; /* ************************ */ ADDFUNC((void*)OnGetProcAddress, szGetProcAddress, kernel32); // eGetProcAddress, ... // No need to hook these functions in Vista+ if (!gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryA, szLoadLibraryA, kernel32); // ... ADDFUNC((void*)OnLoadLibraryExA, szLoadLibraryExA, kernel32); ADDFUNC((void*)OnLoadLibraryExW, szLoadLibraryExW, kernel32); ADDFUNC((void*)OnFreeLibrary, szFreeLibrary, kernel32); // OnFreeLibrary тоже нужен! } // With only exception of LoadLibraryW - it handles "ExtendedConsole.dll" loading in Far 64 if (gbIsFarProcess || !gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryW, szLoadLibraryW, kernel32); } #ifdef HOOK_ERROR_PROC // Для отладки появления системных ошибок ADDFUNC((void*)OnGetLastError, szGetLastError, kernel32); ADDFUNC((void*)OnSetLastError, szSetLastError, kernel32); // eSetLastError #endif ADDFUNC(NULL,NULL,NULL); #undef ADDFUNC /* ************************ */ #endif return true; } #define MAX_EXCLUDED_MODULES 40 // Skip/ignore/don't set hooks in modules... const wchar_t* ExcludedModules[MAX_EXCLUDED_MODULES] = { L"ntdll.dll", L"kernelbase.dll", L"kernel32.dll", L"user32.dll", L"advapi32.dll", // L"shell32.dll", -- shell нужно обрабатывать обязательно. по крайней мере в WinXP/Win2k3 (ShellExecute должен звать наш CreateProcess) L"wininet.dll", // какой-то криминал с этой библиотекой? //#ifndef _DEBUG L"mssign32.dll", L"crypt32.dll", L"setupapi.dll", // "ConEmu\Bugs\2012\z120711\" L"uxtheme.dll", // подозрение на exception на некоторых Win7 & Far3 (Bugs\2012\120124\Info.txt, пункт 3) WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), // Loaded in-process when AlternativeServer is started WIN3264TEST(L"ExtendedConsole.dll",L"ExtendedConsole64.dll"), // Our API for Far Manager TrueColor support /* // test L"twext.dll", L"propsys.dll", L"ntmarta.dll", L"Wldap32.dll", L"userenv.dll", L"zipfldr.dll", L"shdocvw.dll", L"linkinfo.dll", L"ntshrui.dll", L"cscapi.dll", */ //#endif // А также исключаются все "API-MS-Win-..." в функции IsModuleExcluded 0 }; BOOL gbLogLibraries = FALSE; DWORD gnLastLogSetChange = 0; // Используется в том случае, если требуется выполнить оригинальную функцию, без нашей обертки // пример в OnPeekConsoleInputW void* __cdecl GetOriginalAddress(void* OurFunction, void* DefaultFunction, BOOL abAllowModified, HookItem** ph) { if (gpHooks) { for (int i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].NewAddress == OurFunction) { *ph = &(gpHooks[i]); // По идее, ExeOldAddress должен совпадать с OldAddress, если включен "Inject ConEmuHk" return (abAllowModified && gpHooks[i].ExeOldAddress) ? gpHooks[i].ExeOldAddress : gpHooks[i].OldAddress; } } } _ASSERT(!gbHooksWasSet || gbLdrDllNotificationUsed && !gbIsFarProcess); // сюда мы попадать не должны return DefaultFunction; } FARPROC WINAPI GetLoadLibraryW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); } FARPROC WINAPI GetWriteConsoleW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)CEAnsi::OnWriteConsoleW, (void*)(FARPROC)WriteConsoleW, FALSE, &ph); } CInFuncCall::CInFuncCall() { mpn_Counter = NULL; } BOOL CInFuncCall::Inc(int* pnCounter) { BOOL lbFirstCall = FALSE; mpn_Counter = pnCounter; if (mpn_Counter) { lbFirstCall = (*mpn_Counter) == 0; (*mpn_Counter)++; } return lbFirstCall; } CInFuncCall::~CInFuncCall() { if (mpn_Counter && (*mpn_Counter)>0)(*mpn_Counter)--; } MSection* gpHookCS = NULL; bool SetExports(HMODULE Module); DWORD CalculateNameCRC32(const char *apszName) { #if 1 DWORD nCRC32 = 0xFFFFFFFF; static DWORD CRCtable[] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; DWORD dwRead = lstrlenA(apszName); for (LPBYTE p = (LPBYTE)apszName; (dwRead--);) { nCRC32 = ( nCRC32 >> 8 ) ^ CRCtable[(unsigned char) ((unsigned char) nCRC32 ^ *p++ )]; } // т.к. нас интересует только сравнение - последний XOR необязателен! //nCRC32 = ( nCRC32 ^ 0xFFFFFFFF ); #else // Этот "облегченный" алгоритм был расчитан на wchar_t DWORD nDwordCount = (anNameLen+1) >> 1; DWORD nCRC32 = 0x7A3B91F4; for (DWORD i = 0; i < nDwordCount; i++) nCRC32 ^= ((LPDWORD)apszName)[i]; #endif return nCRC32; } // Заполнить поле HookItem.OldAddress (реальные процедуры из внешних библиотек) // apHooks->Name && apHooks->DllName MUST be for a lifetime bool __stdcall InitHooks(HookItem* apHooks) { size_t i, j; bool skip; static bool bLdrWasChecked = false; if (!bLdrWasChecked) { #ifndef _WIN32_WINNT_WIN8 #define _WIN32_WINNT_WIN8 0x602 #endif _ASSERTE(_WIN32_WINNT_WIN8==0x602); OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isAllowed = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); // LdrDllNotification работает так как нам надо начиная с Windows 8 // В предыдущих версиях Windows нотификатор вызывается из LdrpFindOrMapDll // ДО того, как были обработаны импорты функцией LdrpProcessStaticImports (а точнее LdrpSnapThunk) if (isAllowed) { HMODULE hNtDll = GetModuleHandle(L"ntdll.dll"); if (hNtDll) { LdrRegisterDllNotification = (LdrRegisterDllNotification_t)GetProcAddress(hNtDll, "LdrRegisterDllNotification"); LdrUnregisterDllNotification = (LdrUnregisterDllNotification_t)GetProcAddress(hNtDll, "LdrUnregisterDllNotification"); if (LdrRegisterDllNotification && LdrUnregisterDllNotification) { gnLdrDllNotificationState = LdrRegisterDllNotification(0, LdrDllNotification, NULL, &gpLdrDllNotificationCookie); gbLdrDllNotificationUsed = (gnLdrDllNotificationState == 0/*STATUS_SUCCESS*/); } } } bLdrWasChecked = true; } #if 0 if (gbHooksSorted && apHooks) { _ASSERTEX(FALSE && "Hooks are already initialized and blocked"); return false; } #endif if (!gpHookCS) { gpHookCS = new MSection; } //if (!gpcsHooksRootPtr) //{ // gpcsHooksRootPtr = (LPCRITICAL_SECTION)calloc(1,sizeof(*gpcsHooksRootPtr)); // Initialize Critical Section(gpcsHooksRootPtr); //} if (gpHooks == NULL) { gpHooks = (HookItem*)calloc(sizeof(HookItem),MAX_HOOKED_PROCS); if (!gpHooks) return false; if (!InitHooksLibrary()) return false; } if (apHooks && gpHooks) { for (i = 0; apHooks[i].NewAddress; i++) { DWORD NameCRC = CalculateNameCRC32(apHooks[i].Name); if (apHooks[i].Name==NULL || apHooks[i].DllName==NULL) { _ASSERTE(apHooks[i].Name!=NULL && apHooks[i].DllName!=NULL); break; } skip = false; for (j = 0; gpHooks[j].NewAddress; j++) { if (gpHooks[j].NewAddress == apHooks[i].NewAddress) { skip = true; break; } } if (skip) continue; j = 0; // using while, because of j while (gpHooks[j].NewAddress) { if (gpHooks[j].NameCRC == NameCRC && strcmp(gpHooks[j].Name, apHooks[i].Name) == 0 && wcscmp(gpHooks[j].DllName, apHooks[i].DllName) == 0) { // Не должно быть такого - функции должны только добавляться _ASSERTEX(lstrcmpiA(gpHooks[j].Name, apHooks[i].Name) && lstrcmpiW(gpHooks[j].DllName, apHooks[i].DllName)); gpHooks[j].NewAddress = apHooks[i].NewAddress; if (j >= gnHookedFuncs) gnHookedFuncs = j+1; skip = true; break; } j++; } if (skip) continue; if ((j+1) >= MAX_HOOKED_PROCS) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_HOOKED_PROCS); continue; // может какие другие хуки удастся обновить, а не добавить } gpHooks[j].Name = apHooks[i].Name; gpHooks[j].NameOrdinal = apHooks[i].NameOrdinal; gpHooks[j].DllName = apHooks[i].DllName; gpHooks[j].NewAddress = apHooks[i].NewAddress; gpHooks[j].NameCRC = NameCRC; _ASSERTEX(j >= gnHookedFuncs); gnHookedFuncs = j+1; gpHooks[j+1].Name = NULL; // на всякий gpHooks[j+1].NewAddress = NULL; // на всякий } } // Для добавленных в gpHooks функций определить "оригинальный" адрес экспорта for (i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].DllNameA[0] == 0) { int nLen = WideCharToMultiByte(CP_ACP, 0, gpHooks[i].DllName, -1, gpHooks[i].DllNameA, (int)countof(gpHooks[i].DllNameA), 0,0); if (nLen > 0) CharLowerBuffA(gpHooks[i].DllNameA, nLen); } if (!gpHooks[i].OldAddress) { // Сейчас - не загружаем HMODULE mod = GetModuleHandle(gpHooks[i].DllName); if (mod == NULL) { _ASSERTE(mod != NULL // Библиотеки, которые могут быть НЕ подлинкованы на старте || (gpHooks[i].DllName == shell32 || gpHooks[i].DllName == user32 || gpHooks[i].DllName == gdi32 || gpHooks[i].DllName == advapi32 || gpHooks[i].DllName == comdlg32 )); } else { WARNING("Тут часто возвращается XXXStub вместо самой функции!"); const char* ExportName = gpHooks[i].NameOrdinal ? ((const char*)gpHooks[i].NameOrdinal) : gpHooks[i].Name; gpHooks[i].OldAddress = (void*)GetProcAddress(mod, ExportName); // WinXP does not have many hooked functions, will not show dozens of asserts #ifdef _DEBUG if (gpHooks[i].OldAddress == NULL) { static int isWin7 = 0; if (isWin7 == 0) { OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isGrEq = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); isWin7 = isGrEq ? 1 : -1; } _ASSERTE((isWin7 == -1) || (gpHooks[i].OldAddress != NULL)); } #endif gpHooks[i].hDll = mod; } } } // Обработать экспорты в Kernel32.dll static bool KernelHooked = false; if (!KernelHooked) { KernelHooked = true; _ASSERTEX(ghKernel32!=NULL); if (IsWin7()) { ghKernelBase = LoadLibrary(kernelbase); } InitKernelFuncs(); WARNING("Без перехвата экспорта в kernel не работает поддержка UPX-нутых модулей"); // Но при такой обработке валится EMenu на Win8 TODO("Нужно вставлять jmp в начало функции LdrGetProcAddressEx в ntdll.dll"); #if 0 // Необходимо для обработки UPX-нутых модулей SetExports(ghKernel32); #endif /* if (ghKernelBase) { WARNING("will fail on Win7 x64"); SetExports(ghKernelBase); } */ } return true; } #if 0 void AddHooksNode(HookItemNode* pRoot, HookItem* p, HookItemNode*& ppNext) { int iCmp = strcmp(p->Name, pRoot->Name); _ASSERTEX(iCmp!=0); // All function names must be unique! if (iCmp < 0) { pRoot->nLeftCount++; if (!pRoot->pLeft) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pLeft = ppNext++; return; } AddHooksNode(pRoot->pLeft, p, ppNext); } else { pRoot->nRightCount++; if (!pRoot->pRight) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pRight = ppNext++; return; } AddHooksNode(pRoot->pRight, p, ppNext); } } #endif #if 0 void BuildTree(HookItemNode*& pRoot, HookItem** pSorted, size_t nCount, HookItemNode*& ppNext) { size_t n = nCount>>1; // Init root pRoot = ppNext++; pRoot->p = pSorted[n]; pRoot->Name = pSorted[n]->Name; if (n > 0) { BuildTree(pRoot->pLeft, pSorted, n, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pLeft!=NULL); pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; #endif } if ((n + 1) < nCount) { BuildTree(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pRight!=NULL); pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; #endif } } #endif //void BuildTreePtr(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->OldAddress; // // if (n > 0) // { // BuildTreePtr(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreePtr(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} //void BuildTreeNew(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->NewAddress; // // if (n > 0) // { // BuildTreeNew(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreeNew(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} #if 0 HookItemNode* FindFunctionNode(HookItemNode* pRoot, const char* pszFuncName) { if (!pRoot) return NULL; int nCmp = strcmp(pszFuncName, pRoot->Name); if (!nCmp) return pRoot; // BinTree is sorted HookItemNode* pc; if (nCmp < 0) { pc = FindFunctionNode(pRoot->pLeft, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pRight, pszFuncName)==NULL); //#endif } else { pc = FindFunctionNode(pRoot->pRight, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pLeft, pszFuncName)==NULL); //#endif } return pc; } #endif //HookItemNodePtr* FindFunctionNodePtr(HookItemNodePtr* pRoot, const void* ptrFunc) //{ // if (!pRoot) // return NULL; // // if (ptrFunc == pRoot->Address) // return pRoot; // // // BinTree is sorted // // HookItemNodePtr* pc; // if (ptrFunc < pRoot->Address) // { // pc = FindFunctionNodePtr(pRoot->pLeft, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pRight, ptrFunc)==NULL); // #endif // } // else // { // pc = FindFunctionNodePtr(pRoot->pRight, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pLeft, ptrFunc)==NULL); // #endif // } // // return pc; //} HookItem* FindFunction(const char* pszFuncName) { DWORD NameCRC = CalculateNameCRC32(pszFuncName); for (HookItem* p = gpHooks; p->NewAddress; ++p) { if (p->NameCRC == NameCRC) { if (strcmp(p->Name, pszFuncName) == 0) return p; } } //HookItemNode* pc = FindFunctionNode(gpHooksRoot, pszFuncName); //if (pc) // return pc->p; return NULL; } //HookItem* FindFunctionPtr(HookItemNodePtr *pRoot, const void* ptrFunction) //{ // HookItemNodePtr* pc = FindFunctionNodePtr(pRoot, ptrFunction); // if (pc) // return pc->p; // return NULL; //} //// Unfortunately, tree must be rebuilded when new modules are loaded //// (e.g. "shell32.dll", when it is not statically linked to exe) //void InitHooksSortAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortAddress",gnHookedFuncs); // // // *** !!! *** // Enter Critical Section(gpcsHooksRootPtr); // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // Leave Critical Section(gpcsHooksRootPtr); // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // size_t iMax = 0; // for (size_t i = 0; i < gnHookedFuncs; i++) // { // if (gpHooks[i].OldAddress) // pSort[iMax++] = (gpHooks+i); // } // if (iMax) iMax--; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->OldAddress; // for (size_t j = i+1; j <= iMax; j++) // { // _ASSERTEX(pSort[j]->OldAddress != ptrM && pSort[j]->OldAddress); // if (pSort[j]->OldAddress < ptrM) // { // m = j; ptrM = pSort[j]->OldAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreePtr) // { // gpHooksTreePtr = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreePtr) // { // Leave Critical Section(gpcsHooksRootPtr); // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreePtr; // BuildTreePtr(gpHooksRootPtr, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); // // Leave Critical Section(gpcsHooksRootPtr); //} // //void InitHooksSortNewAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortNewAddress",gnHookedFuncs); // // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // // for (size_t i = 0; i < gnHookedFuncs; i++) // { // pSort[i] = (gpHooks+i); // } // size_t iMax = gnHookedFuncs - 1; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->NewAddress; // for (size_t j = i+1; j < gnHookedFuncs; j++) // { // _ASSERTEX(pSort[j]->NewAddress != ptrM && pSort[j]->NewAddress); // if (pSort[j]->NewAddress < ptrM) // { // m = j; ptrM = pSort[j]->NewAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreeNew) // { // gpHooksTreeNew = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreeNew) // { // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreeNew; // BuildTreeNew(gpHooksRootNew, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); //} #if 0 void __stdcall InitHooksSort() { if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); return; } if (gbHooksSorted) { _ASSERTEX(FALSE && "Hooks are already sorted"); return; } gbHooksSorted = true; _ASSERTEX(gpHooks && gpHooks->Name); HLOG0("InitHooksSort",gnHookedFuncs); #if 1 // Sorted by name vector HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); if (!pSort) { _ASSERTEX(pSort!=NULL && "Memory allocation failed"); return; } for (size_t i = 0; i < gnHookedFuncs; i++) { pSort[i] = (gpHooks+i); } // Go sorting size_t iMax = (gnHookedFuncs-1); for (size_t i = 0; i < iMax; i++) { size_t m = i; LPCSTR pszM = pSort[i]->Name; for (size_t j = i+1; j < gnHookedFuncs; j++) { int iCmp = strcmp(pSort[j]->Name, pszM); _ASSERTEX(iCmp!=0); if (iCmp < 0) { m = j; pszM = pSort[j]->Name; } } if (m != i) { HookItem* p = pSort[i]; pSort[i] = pSort[m]; pSort[m] = p; } } gpHooksTree = (HookItemNode*)calloc(gnHookedFuncs,sizeof(HookItemNode)); if (!gpHooksTree) return; // Go to building HookItemNode *ppNext = gpHooksTree; BuildTree(gpHooksRoot, pSort, gnHookedFuncs, ppNext); free(pSort); #else gpHooksTree = (HookItemNode*)calloc(MAX_HOOKED_PROCS,sizeof(HookItemNode)); // Init root gpHooksRoot = gpHooksTree; gpHooksRoot->p = gpHooks; gpHooksRoot->Name = gpHooks->Name; HookItemNode *ppNext = gpHooksTree+1; // Go to building for (size_t i = 1; i < MAX_HOOKED_PROCS; ++i) { if (!gpHooks[i].Name) break; AddHooksNode(gpHooksRoot, gpHooks+i, ppNext); } #endif #ifdef _DEBUG // Validate tree _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); _ASSERTEX(FindFunction("Not Existed")==NULL); for (size_t i = 0; i < gnHookedFuncs; i++) { HookItem* pFind = FindFunction(gpHooks[i].Name); _ASSERTEX(pFind == (gpHooks+i)); } #endif HLOGEND(); //// Tree with our NewAddress //InitHooksSortNewAddress(); //// First call to address tree. But it may be rebuilded... //InitHooksSortAddress(); } #endif void ShutdownHooks() { HLOG1("ShutdownHooks.UnsetAllHooks",0); UnsetAllHooks(); HLOGEND1(); //// Завершить работу с реестром //DoneHooksReg(); // Уменьшение счетчиков загрузок (а надо ли?) HLOG1_("ShutdownHooks.FreeLibrary",1); for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && *ghSysDll[s]) { FreeLibrary(*ghSysDll[s]); *ghSysDll[s] = NULL; } } HLOGEND1(); if (gpHookCS) { MSection *p = gpHookCS; gpHookCS = NULL; delete p; } //if (gpcsHooksRootPtr) //{ // Delete Critical Section(gpcsHooksRootPtr); // SafeFree(gpcsHooksRootPtr); //} FinalizeHookedModules(); } void __stdcall SetLoadLibraryCallback(HMODULE ahCallbackModule, OnLibraryLoaded_t afOnLibraryLoaded, OnLibraryLoaded_t afOnLibraryUnLoaded) { ghOnLoadLibModule = ahCallbackModule; gfOnLibraryLoaded = afOnLibraryLoaded; gfOnLibraryUnLoaded = afOnLibraryUnLoaded; } bool __stdcall SetHookCallbacks(const char* ProcName, const wchar_t* DllName, HMODULE hCallbackModule, HookItemPreCallback_t PreCallBack, HookItemPostCallback_t PostCallBack, HookItemExceptCallback_t ExceptCallBack) { if (!ProcName|| !DllName) { _ASSERTE(ProcName!=NULL && DllName!=NULL); return false; } _ASSERTE(ProcName[0]!=0 && DllName[0]!=0); bool bFound = false; if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (!strcmp(gpHooks[i].Name, ProcName) && !lstrcmpW(gpHooks[i].DllName,DllName)) { gpHooks[i].hCallbackModule = hCallbackModule; gpHooks[i].PreCallBack = PreCallBack; gpHooks[i].PostCallBack = PostCallBack; gpHooks[i].ExceptCallBack = ExceptCallBack; bFound = true; //break; // перехватов может быть более одного (деление хуков на exe/dll) } } } return bFound; } bool FindModuleFileName(HMODULE ahModule, LPWSTR pszName, size_t cchNameMax) { bool lbFound = false; if (pszName && cchNameMax) { //*pszName = 0; #ifdef _WIN64 msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X%08X> ", (DWORD)((((u64)ahModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)ahModule) & 0xFFFFFFFF)); //-V112 #else msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X> ", (DWORD)ahModule); #endif INT_PTR nLen = lstrlen(pszName); pszName += nLen; cchNameMax -= nLen; _ASSERTE(cchNameMax>0); } //TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. lbFound = (IsHookedModule(ahModule, pszName, cchNameMax) != NULL); return lbFound; } bool IsModuleExcluded(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW) { if (module == ghOurModule) return true; BOOL lbResource = LDR_IS_RESOURCE(module); if (lbResource) return true; // игнорировать системные библиотеки вида // API-MS-Win-Core-Util-L1-1-0.dll if (asModuleA) { char szTest[12]; lstrcpynA(szTest, asModuleA, 12); if (lstrcmpiA(szTest, "API-MS-Win-") == 0) return true; } else if (asModuleW) { wchar_t szTest[12]; lstrcpynW(szTest, asModuleW, 12); if (lstrcmpiW(szTest, L"API-MS-Win-") == 0) return true; } #if 1 for (int i = 0; ExcludedModules[i]; i++) if (module == GetModuleHandle(ExcludedModules[i])) return true; #else wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; DWORD nLen = GetModuleFileNameW(module, szModule, countof(szModule)); if ((nLen == 0) || (nLen >= countof(szModule))) { //_ASSERTE(nLen>0 && nLen<countof(szModule)); return true; // Что-то с модулем не то... } LPCWSTR pszName = wcsrchr(szModule, L'\\'); if (pszName) pszName++; else pszName = szModule; for (int i = 0; ExcludedModules[i]; i++) { if (lstrcmpi(ExcludedModules[i], pszName) == 0) return true; // указан в исключениях } #endif return false; } #define GetPtrFromRVA(rva,pNTHeader,imageBase) (PVOID)((imageBase)+(rva)) extern BOOL gbInCommonShutdown; bool LockHooks(HMODULE Module, LPCWSTR asAction, MSectionLock* apCS) { #ifdef _DEBUG DWORD nCurTID = GetCurrentThreadId(); #endif //while (nHookMutexWait != WAIT_OBJECT_0) BOOL lbLockHooksSection = FALSE; while (!(lbLockHooksSection = apCS->Lock(gpHookCS, TRUE, 10000))) { #ifdef _DEBUG if (!IsDebuggerPresent()) { _ASSERTE(lbLockHooksSection); } #endif if (gbInCommonShutdown) return false; wchar_t* szTrapMsg = (wchar_t*)calloc(1024,2); wchar_t* szName = (wchar_t*)calloc((MAX_PATH+1),2); if (!FindModuleFileName(Module, szName, MAX_PATH+1)) szName[0] = 0; DWORD nTID = GetCurrentThreadId(); DWORD nPID = GetCurrentProcessId(); msprintf(szTrapMsg, 1024, L"Can't %s hooks in module '%s'\nCurrent PID=%u, TID=%i\nCan't lock hook section\nPress 'Retry' to repeat locking", asAction, szName, nPID, nTID); int nBtn = #ifdef CONEMU_MINIMAL GuiMessageBox #else MessageBoxW #endif (GetConEmuHWND(TRUE), szTrapMsg, L"ConEmu", MB_RETRYCANCEL|MB_ICONSTOP|MB_SYSTEMMODAL); free(szTrapMsg); free(szName); if (nBtn != IDRETRY) return false; //nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); //continue; } #ifdef _DEBUG wchar_t szDbg[80]; msprintf(szDbg, countof(szDbg), L"ConEmuHk: LockHooks, TID=%u\n", nCurTID); if (nCurTID != gnHookMainThreadId) { int nDbg = 0; } DebugString(szDbg); #endif return true; } bool SetExportsSEH(HMODULE Module) { bool lbRc = false; DWORD ExportDir = 0; IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = 0; if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature == 0x004550) { ExportDir = (DWORD)(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); } } if (ExportDir != 0) { IMAGE_SECTION_HEADER* section = (IMAGE_SECTION_HEADER*)IMAGE_FIRST_SECTION(nt_header); for (WORD s = 0; s < nt_header->FileHeader.NumberOfSections; s++) { if (!((section[s].VirtualAddress == ExportDir) || ((section[s].VirtualAddress < ExportDir) && ((section[s].Misc.VirtualSize + section[s].VirtualAddress) > ExportDir)))) { // Эта секция не содержит ExportDir continue; } //int nDiff = 0;//section[s].VirtualAddress - section[s].PointerToRawData; IMAGE_EXPORT_DIRECTORY* Export = (IMAGE_EXPORT_DIRECTORY*)((char*)Module + (ExportDir/*-nDiff*/)); if (!Export->AddressOfNames || !Export->AddressOfNameOrdinals || !Export->AddressOfFunctions) { _ASSERTEX(Export->AddressOfNames && Export->AddressOfNameOrdinals && Export->AddressOfFunctions); continue; } DWORD* Name = (DWORD*)(((BYTE*)Module) + Export->AddressOfNames); WORD* Ordn = (WORD*)(((BYTE*)Module) + Export->AddressOfNameOrdinals); DWORD* Shift = (DWORD*)(((BYTE*)Module) + Export->AddressOfFunctions); DWORD nCount = Export->NumberOfNames; // Export->NumberOfFunctions; DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(Shift, nCount * sizeof( DWORD ), PAGE_READWRITE, &old_protect )) { for (DWORD i = 0; i < nCount; i++) { char* pszExpName = ((char*)Module) + Name[i]; DWORD nFnOrdn = Ordn[i]; if (nFnOrdn > Export->NumberOfFunctions) { _ASSERTEX(nFnOrdn <= Export->NumberOfFunctions); continue; } void* ptrOldAddr = ((BYTE*)Module) + Shift[nFnOrdn]; for (DWORD j = 0; j <= countof(gKernelFuncs); j++) { if ((Module == gKernelFuncs[j].hLib) && gKernelFuncs[j].NewAddress && !strcmp(gKernelFuncs[j].Name, pszExpName)) { gKernelFuncs[j].OldAddress = (FARPROC)ptrOldAddr; INT_PTR NewShift = ((BYTE*)gKernelFuncs[j].NewAddress) - ((BYTE*)Module); #ifdef _WIN64 if (NewShift <= 0 || NewShift > (DWORD)-1) { _ASSERTEX((NewShift > 0) && (NewShift < (DWORD)-1)); break; } #endif Shift[nFnOrdn] = (DWORD)NewShift; lbRc = true; break; } } } VirtualProtect( Shift, nCount * sizeof( DWORD ), old_protect, &old_protect ); } } } return lbRc; } bool SetExports(HMODULE Module) { _ASSERTEX((Module == ghKernel32 || Module == ghKernelBase) && Module); #ifdef _DEBUG if (Module == ghKernel32) { static bool KernelHooked = false; if (KernelHooked) { _ASSERTEX(KernelHooked==false); return false; } KernelHooked = true; } else if (Module == ghKernelBase) { static bool KernelBaseHooked = false; if (KernelBaseHooked) { _ASSERTEX(KernelBaseHooked==false); return false; } KernelBaseHooked = true; } #endif bool lbValid = IsModuleValid(Module); if ((Module == ghOurModule) || !lbValid) { _ASSERTEX(Module != ghOurModule); _ASSERTEX(IsModuleValid(Module)); return false; } //InitKernelFuncs(); -- уже должно быть выполнено! _ASSERTEX(gKernelFuncs[0].NewAddress!=NULL); // переопределяем только первые 6 экспортов, и через gKernelFuncs //_ASSERTEX(gpHooks[0].Name == szGetProcAddress && gpHooks[5].Name == szFreeLibrary); //_ASSERTEX(gpHooks[1].Name == szLoadLibraryA && gpHooks[2].Name == szLoadLibraryW); //_ASSERTEX(gpHooks[3].Name == szLoadLibraryExA && gpHooks[4].Name == szLoadLibraryExW); #ifdef _WIN64 if (((DWORD_PTR)Module) >= ((DWORD_PTR)ghOurModule)) { //_ASSERTEX(((DWORD_PTR)Module) < ((DWORD_PTR)ghOurModule)) wchar_t* pszMsg = (wchar_t*)malloc(MAX_PATH*3*sizeof(wchar_t)); if (pszMsg) { wchar_t szTitle[64]; OSVERSIONINFO osv = {sizeof(osv)}; GetOsVersionInformational(&osv); msprintf(szTitle, countof(szTitle), L"ConEmuHk64, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); msprintf(pszMsg, 250, L"ConEmuHk64.dll was loaded below Kernel32.dll\n" L"Some important features may be not available!\n" L"Please, report to developer!\n\n" L"OS version: %u.%u.%u (%s)\n" L"<ConEmuHk64.dll=0x%08X%08X>\n" L"<%s=0x%08X%08X>\n", osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber, osv.szCSDVersion, WIN3264WSPRINT(ghOurModule), (Module==ghKernelBase) ? kernelbase : kernel32, WIN3264WSPRINT(Module) ); GetModuleFileName(ghOurModule, pszMsg+lstrlen(pszMsg), MAX_PATH); lstrcat(pszMsg, L"\n"); GetModuleFileName(Module, pszMsg+lstrlen(pszMsg), MAX_PATH); GuiMessageBox(NULL, pszMsg, szTitle, MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL); free(pszMsg); } return false; } #endif bool lbRc = false; SAFETRY { // В отдельной функции, а то компилятор глюкавит (под отладчиком во всяком случае куда-то не туда прыгает) lbRc = SetExportsSEH(Module); } SAFECATCH { lbRc = false; } return lbRc; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); // Подменить Импортируемые функции в модуле (Module) // если (abForceHooks == FALSE) то хуки не ставятся, если // будет обнаружен импорт, не совпадающий с оригиналом // Это для того, чтобы не выполнять множественные хуки при множественных LoadLibrary bool SetHook(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks) { IMAGE_IMPORT_DESCRIPTOR* Import = NULL; DWORD Size = 0; HMODULE hExecutable = GetModuleHandle(0); if (!gpHooks) return false; if (!Module) Module = hExecutable; // Если он уже хукнут - не проверять больше ничего HkModuleInfo* p = IsHookedModule(Module); if (p) return true; if (!IsModuleValid(Module)) return false; bool bExecutable = (Module == hExecutable); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = NULL; HLOG0("SetHook.Init",(DWORD)Module); // Валидность адреса размером sizeof(IMAGE_DOS_HEADER) проверяется в IsModuleValid. if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (IsBadReadPtr(nt_header, sizeof(IMAGE_NT_HEADERS))) return false; if (nt_header->Signature != 0x004550) return false; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } HLOGEND(); } else return false; // if wrong module or no import table if (!Import) return false; #ifdef _DEBUG PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt_header); //-V220 #endif #ifdef _WIN64 _ASSERTE(sizeof(DWORD_PTR)==8); #else _ASSERTE(sizeof(DWORD_PTR)==4); #endif #ifdef _WIN64 #define TOP_SHIFT 60 #else #define TOP_SHIFT 28 #endif //DWORD nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); HLOG("SetHook.Lock",(DWORD)Module); MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"install", &CS)) return false; HLOGEND(); if (!p) { HLOG("SetHook.Add",(DWORD)Module); p = AddHookedModule(Module, asModule); HLOGEND(); if (!p) return false; } HLOG("SetHook.Prepare",(DWORD)Module); TODO("!!! Сохранять ORDINAL процедур !!!"); bool res = false, bHooked = false; //INT_PTR i; INT_PTR nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); bool bFnNeedHook[MAX_HOOKED_PROCS] = {}; // в отдельной функции, т.к. __try res = SetHookPrep(asModule, Module, nt_header, abForceHooks, bExecutable, Import, nCount, bFnNeedHook, p); HLOGEND(); HLOG("SetHook.Change",(DWORD)Module); // в отдельной функции, т.к. __try bHooked = SetHookChange(asModule, Module, abForceHooks, bFnNeedHook, p); HLOGEND(); #ifdef _DEBUG if (bHooked) { HLOG("SetHook.FindModuleFileName",(DWORD)Module); wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); wchar_t* szModPath = (wchar_t*)calloc(MAX_PATH*2, 2); FindModuleFileName(Module, szModPath, MAX_PATH*2); _wcscpy_c(szDbg, MAX_PATH*3, L" ## Hooks was set by conemu: "); _wcscat_c(szDbg, MAX_PATH*3, szModPath); _wcscat_c(szDbg, MAX_PATH*3, L"\n"); DebugString(szDbg); free(szDbg); free(szModPath); HLOGEND(); } #endif HLOG("SetHook.Unlock",(DWORD)Module); //ReleaseMutex(ghHookMutex); CS.Unlock(); HLOGEND(); // Плагин ConEmu может выполнить дополнительные действия if (gfOnLibraryLoaded) { HLOG("SetHook.gfOnLibraryLoaded",(DWORD)Module); gfOnLibraryLoaded(Module); HLOGEND(); } return res; } bool isBadModulePtr(const void *lp, UINT_PTR ucb, HMODULE Module, const IMAGE_NT_HEADERS* nt_header) { bool bTestValid = (((LPBYTE)lp) >= ((LPBYTE)Module)) && ((((LPBYTE)lp) + ucb) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiValid = bTestValid; #else bool bApiValid = !IsBadReadPtr(lp, ucb); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestValid != bApiValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestValid != bApiValid); } } #endif #endif return !bApiValid; } bool isBadModuleStringA(LPCSTR lpsz, UINT_PTR ucchMax, HMODULE Module, IMAGE_NT_HEADERS* nt_header) { bool bTestStrValid = (((LPBYTE)lpsz) >= ((LPBYTE)Module)) && ((((LPBYTE)lpsz) + ucchMax) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiStrValid = bTestStrValid; #else bool bApiStrValid = !IsBadStringPtrA(lpsz, ucchMax); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestStrValid != bApiStrValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestStrValid != bApiStrValid); } } #endif #endif return !bApiStrValid; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool res = false; size_t i; //api-ms-win-core-libraryloader-l1-1-1.dll //api-ms-win-core-console-l1-1-0.dll //... char szCore[18]; const char szCorePrefix[] = "api-ms-win-core-"; // MUST BE LOWER CASE! const int nCorePrefLen = lstrlenA(szCorePrefix); _ASSERTE((nCorePrefLen+1)<countof(szCore)); bool lbIsCoreModule = false; char mod_name[MAX_PATH]; //_ASSERTEX(lstrcmpi(asModule, L"dsound.dll")); SAFETRY { HLOG0("SetHookPrep.Begin",ImportCount); //if (!gpHooksRootPtr) //{ // InitHooksSortAddress(); //} //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (i = 0; i < ImportCount; i++) { if (Import[i].Name == 0) break; HLOG0("SetHookPrep.Import",i); HLOG1("SetHookPrep.CheckModuleName",i); //DebugString( ToTchar( (char*)Module + Import[i].Name ) ); char* mod_name_ptr = (char*)Module + Import[i].Name; DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 lstrcpynA(mod_name, mod_name_ptr, countof(mod_name)); CharLowerBuffA(mod_name, lstrlenA(mod_name)); // MUST BE LOWER CASE! lstrcpynA(szCore, mod_name, nCorePrefLen+1); lbIsCoreModule = (strcmp(szCore, szCorePrefix) == 0); bool bHookExists = false; for (size_t j = 0; gpHooks[j].Name; j++) { if ((strcmp(mod_name, gpHooks[j].DllNameA) != 0) && !(lbIsCoreModule && (gpHooks[j].DllName == kernel32))) // Имя модуля не соответствует continue; bHookExists = true; break; } // Этот модуль вообще не хукается if (!bHookExists) { HLOGEND1(); HLOGEND(); continue; } if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); HLOGEND1(); HLOGEND(); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); HLOGEND1(); HLOGEND(); continue; } HLOGEND1(); // ***** >>>>>> go HLOG1_("SetHookPrep.ImportThunksSteps",i); size_t f, s; for (s = 0; s <= 1; s++) { if (s) { thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); } for (f = 0;; thunk++, thunkO++, f++) { //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunk",f); bool lbBadThunk = isBadModulePtr(thunk, sizeof(*thunk), Module, nt_header); if (lbBadThunk) { _ASSERTEX(!lbBadThunk); break; } #endif if (!thunk->u1.Function) break; #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunkO",f); bool lbBadThunkO = isBadModulePtr(thunkO, sizeof(*thunkO), Module, nt_header); if (lbBadThunkO) { _ASSERTEX(!lbBadThunkO); break; } #endif const char* pszFuncName = NULL; //ULONGLONG ordinalO = -1; // Получили адрес функции, и (на втором шаге) имя функции // Теперь нужно подобрать (если есть) адрес перехвата HookItem* ph = gpHooks; INT_PTR jj = -1; if (!s) { HLOG1("SetHookPrep.ImportThunks0",s); //HLOG2("SetHookPrep.FuncTreeNew",f); //ph = FindFunctionPtr(gpHooksRootNew, (void*)thunk->u1.Function); //HLOGEND2(); //if (ph) //{ // // Already hooked, this is our function address // HLOGEND1(); // continue; //} //HLOG2_("SetHookPrep.FuncTreeOld",f); //ph = FindFunctionPtr(gpHooksRootPtr, (void*)thunk->u1.Function); //HLOGEND2(); //if (!ph) //{ // // This address (Old) does not exists in our tables // HLOGEND1(); // continue; //} //jj = (ph - gpHooks); for (size_t j = 0; ph->Name; ++j, ++ph) { _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); // Если не удалось определить оригинальный адрес процедуры (kernel32/WriteConsoleOutputW, и т.п.) if (ph->OldAddress == NULL) { continue; } // Если адрес импорта в модуле уже совпадает с адресом одной из наших функций if (ph->NewAddress == (void*)thunk->u1.Function) { res = true; // это уже захучено break; } #ifdef _DEBUG //const void* ptrNewAddress = ph->NewAddress; //const void* ptrOldAddress = (void*)thunk->u1.Function; #endif // Проверяем адрес перехватываемой функции if ((void*)thunk->u1.Function == ph->OldAddress) { jj = j; break; // OK, Hook it! } } // for (size_t j = 0; ph->Name; ++j, ++ph), (s==0) HLOGEND1(); } else { HLOG1("SetHookPrep.ImportThunks1",s); if (!abForceHooks) { //_ASSERTEX(abForceHooks); //HLOGEND1(); HLOG2("!!!Function skipped of (!abForceHooks)",f); continue; // запрещен перехват, если текущий адрес в модуле НЕ совпадает с оригинальным экспортом! } // искать имя функции if ((thunk->u1.Function != thunkO->u1.Function) && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else HLOG("SetHookPrep.pOrdinalNameO",f); //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) { lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } if (!pszFuncName || !*pszFuncName) { continue; // This import does not have "Function name" } HLOG2("SetHookPrep.FindFunction",f); ph = FindFunction(pszFuncName); HLOGEND2(); if (!ph) { HLOGEND1(); continue; } // Имя модуля HLOG2_("SetHookPrep.Module",f); if ((strcmp(mod_name, ph->DllNameA) != 0) && !(lbIsCoreModule && (ph->DllName == kernel32))) { HLOGEND2(); HLOGEND1(); // Имя модуля не соответствует continue; // И дубли имен функций не допускаются. Пропускаем } HLOGEND2(); jj = (ph - gpHooks); HLOGEND1(); } if (jj >= 0) { HLOG1("SetHookPrep.WorkExport",f); if (bExecutable && !ph->ExeOldAddress) { // OldAddress уже может отличаться от оригинального экспорта библиотеки //// Это происходит например с PeekConsoleIntputW при наличии плагина Anamorphosis // Про Anamorphosis несколько устарело. При включенном "Inject ConEmuHk" // хуки ставятся сразу при запуске процесса. // Но, теоретически, кто-то может успеть раньше, или флажок "Inject" выключен. // Также это может быть в новой архитектуре Win7 ("api-ms-win-core-..." и др.) ph->ExeOldAddress = (void*)thunk->u1.Function; } // When we get here - jj matches pszFuncName or FuncPtr if (p->Addresses[jj].ppAdr != NULL) { HLOGEND1(); continue; // уже обработали, следующий импорт } //#ifdef _DEBUG //// Это НЕ ORDINAL, это Hint!!! //if (ph->nOrdinal == 0 && ordinalO != (ULONGLONG)-1) // ph->nOrdinal = (DWORD)ordinalO; //#endif _ASSERTE(sizeof(thunk->u1.Function)==sizeof(DWORD_PTR)); if (thunk->u1.Function == (DWORD_PTR)ph->NewAddress) { // оказалось захучено в другой нити? такого быть не должно, блокируется секцией // Но может быть захучено в прошлый раз, если не все модули были загружены при старте _ASSERTE(thunk->u1.Function != (DWORD_PTR)ph->NewAddress); } else { bFnNeedHook[jj] = true; p->Addresses[jj].ppAdr = &thunk->u1.Function; #ifdef _DEBUG p->Addresses[jj].ppAdrCopy1 = (DWORD_PTR)p->Addresses[jj].ppAdr; p->Addresses[jj].ppAdrCopy2 = (DWORD_PTR)*p->Addresses[jj].ppAdr; p->Addresses[jj].pModulePtr = (DWORD_PTR)p->hModule; IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)((char*)p->hModule + ((IMAGE_DOS_HEADER*)p->hModule)->e_lfanew); p->Addresses[jj].nModuleSize = nt_header->OptionalHeader.SizeOfImage; #endif //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect _ASSERTEX(p->hModule==Module); HLOG2("SetHookPrep.CheckCallbackPtr.1",f); _ASSERTEX(CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[jj].ppAdr, TRUE)); HLOGEND2(); p->Addresses[jj].pOld = thunk->u1.Function; p->Addresses[jj].pOur = (DWORD_PTR)ph->NewAddress; #ifdef _DEBUG lstrcpynA(p->Addresses[jj].sName, ph->Name, countof(p->Addresses[jj].sName)); #endif _ASSERTEX(p->nAdrUsed < countof(p->Addresses)); p->nAdrUsed++; //информационно } #ifdef _DEBUG if (bExecutable) ph->ReplacedInExe = TRUE; #endif //DebugString( ToTchar( ph->Name ) ); res = true; HLOGEND1(); } // if (jj >= 0) HLOGEND1(); } // for (f = 0;; thunk++, thunkO++, f++) } // for (s = 0; s <= 1; s++) HLOGEND1(); HLOGEND(); } // for (i = 0; i < nCount; i++) HLOGEND(); } SAFECATCH { } return res; } bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool bHooked = false; size_t j = 0; DWORD dwErr = (DWORD)-1; _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); SAFETRY { while (j < gnHookedFuncs) { // Может быть NULL, если импортируются не все функции if (p->Addresses[j].ppAdr && bFnNeedHook[j]) { if (*p->Addresses[j].ppAdr == p->Addresses[j].pOur) { // оказалось захучено в другой нити или раньше _ASSERTEX(*p->Addresses[j].ppAdr != p->Addresses[j].pOur); } else { DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); _ASSERTEX(FALSE); } else { bHooked = true; *p->Addresses[j].ppAdr = p->Addresses[j].pOur; p->Addresses[j].bHooked = TRUE; VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), old_protect, &old_protect); } } } j++; } } SAFECATCH { // Ошибка назначения p->Addresses[j].pOur = 0; } return bHooked; } DWORD GetMainThreadId(bool bUseCurrentAsMain) { // Найти ID основной нити if (!gnHookMainThreadId) { if (bUseCurrentAsMain) { gnHookMainThreadId = GetCurrentThreadId(); } else { DWORD dwPID = GetCurrentProcessId(); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwPID); if (snapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 module = {sizeof(THREADENTRY32)}; if (Thread32First(snapshot, &module)) { while (!gnHookMainThreadId) { if (module.th32OwnerProcessID == dwPID) { gnHookMainThreadId = module.th32ThreadID; break; } if (!Thread32Next(snapshot, &module)) break; } } CloseHandle(snapshot); } } } #ifdef _DEBUG char szInfo[100]; msprintf(szInfo, countof(szInfo), "GetMainThreadId()=%u, TID=%u\n", gnHookMainThreadId, GetCurrentThreadId()); //OutputDebugStringA(szInfo); #endif _ASSERTE(gnHookMainThreadId!=0); return gnHookMainThreadId; } VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context) { DWORD dwSaveErrCode = GetLastError(); wchar_t szModule[MAX_PATH*2] = L""; HMODULE hModule; BOOL bMainThread = (GetCurrentThreadId() == gnHookMainThreadId); const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: FullDllName = NotificationData->Loaded.FullDllName; BaseDllName = NotificationData->Loaded.BaseDllName; hModule = (HMODULE)NotificationData->Loaded.DllBase; break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: FullDllName = NotificationData->Unloaded.FullDllName; BaseDllName = NotificationData->Unloaded.BaseDllName; hModule = (HMODULE)NotificationData->Unloaded.DllBase; break; default: return; } if (FullDllName && FullDllName->Buffer) memmove(szModule, FullDllName->Buffer, min(sizeof(szModule)-2,FullDllName->Length)); else if (BaseDllName && BaseDllName->Buffer) memmove(szModule, BaseDllName->Buffer, min(sizeof(szModule)-2,BaseDllName->Length)); #ifdef _DEBUG wchar_t szDbgInfo[MAX_PATH*3]; _wsprintf(szDbgInfo, SKIPLEN(countof(szDbgInfo)) L"ConEmuHk: Ldr(%s) " WIN3264TEST(L"0x%08X",L"0x%08X%08X") L" '%s'\n", (NotificationReason==LDR_DLL_NOTIFICATION_REASON_LOADED) ? L"Loaded" : L"Unload", WIN3264WSPRINT(hModule), szModule); DebugString(szDbgInfo); #endif switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: if (PrepareNewModule(hModule, NULL, szModule, TRUE, TRUE)) { HookItem* ph = NULL;; GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); if (ph && ph->PostCallBack) { SETARGS1(&hModule,szModule); ph->PostCallBack(&args); } } break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: UnprepareModule(hModule, szModule, 0); UnprepareModule(hModule, szModule, 2); break; } SetLastError(dwSaveErrCode); } // Подменить Импортируемые функции во всех модулях процесса, загруженных ДО conemuhk.dll // *aszExcludedModules - должны указывать на константные значения (program lifetime) bool __stdcall SetAllHooks(HMODULE ahOurDll, const wchar_t** aszExcludedModules /*= NULL*/, BOOL abForceHooks) { // т.к. SetAllHooks может быть вызван из разных dll - запоминаем однократно if (!ghOurModule) ghOurModule = ahOurDll; if (!gpHooks) { HLOG1("SetAllHooks.InitHooks",0); InitHooks(NULL); if (!gpHooks) return false; HLOGEND1(); } #if 0 if (!gbHooksSorted) { HLOG1("InitHooksSort",0); InitHooksSort(); HLOGEND1(); } #endif #ifdef _DEBUG wchar_t szHookProc[128]; for (int i = 0; gpHooks[i].NewAddress; i++) { msprintf(szHookProc, countof(szHookProc), L"## %S -> 0x%08X (exe: 0x%X)\n", gpHooks[i].Name, (DWORD)gpHooks[i].NewAddress, (DWORD)gpHooks[i].ExeOldAddress); DebugString(szHookProc); } #endif // Запомнить aszExcludedModules if (aszExcludedModules) { INT_PTR j; bool skip; for (INT_PTR i = 0; aszExcludedModules[i]; i++) { j = 0; skip = false; while (ExcludedModules[j]) { if (lstrcmpi(ExcludedModules[j], aszExcludedModules[i]) == 0) { skip = true; break; } j++; } if (skip) continue; if (j > 0) { if ((j+1) >= MAX_EXCLUDED_MODULES) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_EXCLUDED_MODULES); continue; } ExcludedModules[j] = aszExcludedModules[i]; ExcludedModules[j+1] = NULL; // на всякий } } } // Для исполняемого файла могут быть заданы дополнительные inject-ы (сравнение в FAR) HMODULE hExecutable = GetModuleHandle(0); HANDLE snapshot; HLOG0("SetAllHooks.GetMainThreadId",0); // Найти ID основной нити GetMainThreadId(false); _ASSERTE(gnHookMainThreadId!=0); HLOGEND(); wchar_t szInfo[MAX_PATH+2] = {}; // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG("SetAllHooks.SetHook(exe)",0); SetHook(szInfo, hExecutable, abForceHooks); HLOGEND(); } else { #ifdef _DEBUG msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, SetAllHooks, hOurModule=" WIN3264TEST(L"0x%08X\n",L"0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(ahOurDll)); DebugString(szInfo); #endif HLOG("SetAllHooks.CreateSnap",0); // Начались замены во всех загруженных (linked) модулях snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); HLOGEND(); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(MODULEENTRY32)}; HLOG("SetAllHooks.EnumStart",0); HLOG("SetAllHooks.Module32First/Module32Next",0); for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { HLOGEND(); if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG1("SetAllHooks.SetHook",(DWORD)module.hModule); SetHook(module.szModule, module.hModule/*, (module.hModule == hExecutable)*/, abForceHooks); HLOGEND1(); } HLOG("SetAllHooks.Module32First/Module32Next",0); } HLOGEND(); HLOG("SetAllHooks.CloseSnap",0); CloseHandle(snapshot); HLOGEND(); } } DebugString(L"SetAllHooks finished\n"); return true; } bool UnsetHookInt(HMODULE Module) { bool bUnhooked = false, res = false; IMAGE_IMPORT_DESCRIPTOR* Import = 0; size_t Size = 0; _ASSERTE(Module!=NULL); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header; SAFETRY { if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature != 0x004550) goto wrap; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } } else goto wrap; // if wrong module or no import table if (Module == INVALID_HANDLE_VALUE || !Import) goto wrap; size_t i, s, nCount; nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (s = 0; s <= 1; s++) { for (i = 0; i < nCount; i++) { if (Import[i].Name == 0) break; #ifdef _DEBUG char* mod_name = (char*)Module + Import[i].Name; #endif DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); continue; } int f = 0; for (f = 0 ;; thunk++, thunkO++, f++) { //110220 - something strange. валимся при выходе из некоторых программ (AddFont.exe) // смысл в том, что thunk указывает на НЕ валидную область памяти. // Разбор полетов показал, что программа сама порушила таблицу импортов. //Issue 466: We must check every thunk, not first (perl.exe fails?) //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH if (isBadModulePtr(thunk, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunk && FALSE); break; } #endif if (!thunk->u1.Function) { break; } #ifndef USE_SEH if (isBadModulePtr(thunkO, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunkO && FALSE); break; } #endif const char* pszFuncName = NULL; // Имя функции проверяем на втором шаге if (s && thunk->u1.Function != thunkO->u1.Function && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else #ifdef _DEBUG bool bTestValid = (((LPBYTE)pOrdinalNameO) >= ((LPBYTE)Module)) && (((LPBYTE)pOrdinalNameO) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #endif //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); #ifdef _DEBUG static bool bFirstAssert = false; if (!lbValidPtr && !bFirstAssert) { bFirstAssert = true; //_ASSERTE(lbValidPtr); } #endif if (lbValidPtr) { //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } int j; for (j = 0; gpHooks[j].Name; j++) { if (!gpHooks[j].OldAddress) continue; // Эту функцию не обрабатывали (хотя должны были?) // Нужно найти функцию (thunk) в gpHooks через NewAddress или имя if ((void*)thunk->u1.Function != gpHooks[j].NewAddress) { if (!pszFuncName) { continue; } else { if (strcmp(pszFuncName, gpHooks[j].Name)!=0) continue; } // OldAddress уже может отличаться от оригинального экспорта библиотеки // Это если функцию захукали уже после нас } #ifdef _DEBUG // Может ли такое быть? Модуль был "захукан" без нашего ведома? // Наблюдается в Win2k8R2 static bool bWarned = false; if (!bWarned) { bWarned = true; _ASSERTE(FALSE && "Unknown function replacement was found (external hook?)"); } #endif // Если мы дошли сюда - значит функция найдена (или по адресу или по имени) // BugBug: в принципе, эту функцию мог захукать и другой модуль (уже после нас), // но лучше вернуть оригинальную, чем потом свалиться DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), PAGE_READWRITE, &old_protect)) { // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена ДО нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else thunk->u1.Function = (DWORD_PTR)gpHooks[j].OldAddress; VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), old_protect, &old_protect); bUnhooked = true; } //DebugString( ToTchar( gpHooks[j].Name ) ); break; // перейти к следующему thunk-у } } } } wrap: res = bUnhooked; } SAFECATCH { } return res; } // Подменить Импортируемые функции в модуле bool UnsetHook(HMODULE Module) { if (!gpHooks) return false; if (!IsModuleValid(Module)) return false; MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"uninstall", &CS)) return false; HkModuleInfo* p = IsHookedModule(Module); bool bUnhooked = false; DWORD dwErr = (DWORD)-1; if (!p) { // Хотя модуль и не обрабатывался нами, но может получиться, что у него переопределенные импорты // Зовем в отдельной функции, т.к. __try HLOG1("UnsetHook.Int",0); bUnhooked = UnsetHookInt(Module); HLOGEND1(); } else { if (p->Hooked == 1) { HLOG1("UnsetHook.Var",0); for (size_t i = 0; i < MAX_HOOKED_PROCS; i++) { if (p->Addresses[i].pOur == 0) continue; // Этот адрес поменять не смогли #ifdef _DEBUG //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[i].ppAdr, TRUE); #endif DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); //Один раз выскочило ERROR_INVALID_PARAMETER // При этом, (p->Addresses[i].ppAdr==0x04cde0e0), (p->Addresses[i].ppAdr==0x912edebf) // что было полной пургой. Ни одного модуля в этих адресах не было _ASSERTEX(dwErr==ERROR_INVALID_ADDRESS); } else { bUnhooked = true; // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена без нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else *p->Addresses[i].ppAdr = p->Addresses[i].pOld; p->Addresses[i].bHooked = FALSE; VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), old_protect, &old_protect); } } // Хуки сняты p->Hooked = 2; HLOGEND1(); } } #ifdef _DEBUG if (bUnhooked && p) { wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); lstrcpy(szDbg, L" ## Hooks was UNset by conemu: "); lstrcat(szDbg, p->sModuleName); lstrcat(szDbg, L"\n"); DebugString(szDbg); free(szDbg); } #endif return bUnhooked; } void __stdcall UnsetAllHooks() { HMODULE hExecutable = GetModuleHandle(0); wchar_t szInfo[MAX_PATH+2] = {}; if (gbLdrDllNotificationUsed) { _ASSERTEX(LdrUnregisterDllNotification!=NULL); LdrUnregisterDllNotification(gpLdrDllNotificationCookie); } // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); #ifdef _DEBUG wcscat_c(szInfo, L"\n"); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 DebugString(szInfo); #endif // Go UnsetHook(hExecutable); } else { #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, UnsetAllHooks\n", GetCurrentThreadId()); DebugString(szInfo); #endif //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); WARNING("Убрать перехват экспортов из Kernel32.dll"); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(module)}; for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #ifdef _DEBUG wcscat_c(szInfo, L"\n"); DebugString(szInfo); #endif // Go UnsetHook(module.hModule/*, (module.hModule == hExecutable)*/); } } CloseHandle(snapshot); } } #ifdef _DEBUG DebugStringA("UnsetAllHooks finished\n"); #endif } /* **************************** * * * * Далее идут собственно хуки * * * * **************************** */ void LoadModuleFailed(LPCSTR asModuleA, LPCWSTR asModuleW) { DWORD dwErrCode = GetLastError(); if (!gnLastLogSetChange) { CShellProc* sp = new CShellProc(); if (sp) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping() && sp->GetLogLibraries(); delete sp; } SetLastError(dwErrCode); } if (!gbLogLibraries) return; CESERVER_REQ* pIn = NULL; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; wchar_t szErrCode[64]; szErrCode[0] = 0; msprintf(szErrCode, countof(szErrCode), L"ErrCode=0x%08X", dwErrCode); if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); asModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; asModuleW = szModule; } pIn = ExecuteNewCmdOnCreate(NULL, ghConWnd, eLoadLibrary, L"Fail", asModuleW, szErrCode, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } SetLastError(dwErrCode); } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule); #endif // Заменить в модуле Module ЭКСпортируемые функции на подменяемые плагином нихрена // НЕ получится, т.к. в Win32 библиотека shell32 может быть загружена ПОСЛЕ conemu.dll // что вызовет некорректные смещения функций, // а в Win64 смещения вообще должны быть 64битными, а структура модуля хранит только 32битные смещения bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot /*= FALSE*/, BOOL abForceHooks /*= FALSE*/) { bool lbAllSysLoaded = true; for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && (*ghSysDll[s] == NULL)) { lbAllSysLoaded = false; break; } } if (!lbAllSysLoaded) { // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); } if (!module) { LoadModuleFailed(asModuleA, asModuleW); #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); #endif return false; } // Проверить по gpHookedModules а не был ли модуль уже обработан? if (IsHookedModule(module)) { // Этот модуль уже обработан! return false; } bool lbModuleOk = false; BOOL lbResource = LDR_IS_RESOURCE(module); CShellProc* sp = new CShellProc(); if (sp != NULL) { if (!gnLastLogSetChange || ((GetTickCount() - gnLastLogSetChange) > 2000)) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping(TRUE) && sp->GetLogLibraries(); } if (gbLogLibraries) { CESERVER_REQ* pIn = NULL; LPCWSTR pszModuleW = asModuleW; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); pszModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; pszModuleW = szModule; } wchar_t szInfo[64]; szInfo[0] = 0; #ifdef _WIN64 if ((DWORD)((DWORD_PTR)module >> 32)) msprintf(szInfo, countof(szInfo), L"Module=0x%08X%08X", (DWORD)((DWORD_PTR)module >> 32), (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 #else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)module); #endif pIn = sp->NewCmdOnCreate(eLoadLibrary, NULL, pszModuleW, szInfo, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; sp = NULL; } #ifdef USECHECKPROCESSMODULES if (!lbResource) { if (!abNoSnapshoot /*&& !lbResource*/) { #if 0 // -- уже выполнено выше // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); #endif // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); } if (!gbHookExecutableOnly && !IsModuleExcluded(module, asModuleA, asModuleW)) { wchar_t szModule[128] = {}; if (asModuleA) { LPCSTR pszNameA = strrchr(asModuleA, '\\'); if (!pszNameA) pszNameA = asModuleA; else pszNameA++; MultiByteToWideChar(CP_ACP, 0, pszNameA, -1, szModule, countof(szModule)-1); } else if (asModuleW) { LPCWSTR pszNameW = wcsrchr(asModuleW, L'\\'); if (!pszNameW) pszNameW = asModuleW; else pszNameW++; lstrcpyn(szModule, pszNameW, countof(szModule)); } lbModuleOk = true; // Подмена импортируемых функций в module SetHook(szModule, module, FALSE); } } #else lbModuleOk = true; #endif return lbModuleOk; } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule) { // Если просили хукать только exe-шник if (gbHookExecutableOnly) { return; } #ifdef _DEBUG if (gbSkipCheckProcessModules) { return; } #endif #ifdef _DEBUG char szDbgInfo[100]; msprintf(szDbgInfo, countof(szDbgInfo), "!!! TH32CS_SNAPMODULE, TID=%u, CheckProcessModules, hFromModule=" WIN3264TEST("0x%08X\n","0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(hFromModule)); DebugStringA(szDbgInfo); #endif WARNING("TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary!!!"); // Может, имеет смысл запустить фоновую нить, в которой проверить все загруженные модули? //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); MODULEENTRY32 mi = {sizeof(mi)}; if (h && h != INVALID_HANDLE_VALUE && Module32First(h, &mi)) { BOOL lbAddMod = FALSE; do { //CheckLoadedModule(mi.szModule); //if (!ghUser32) //{ // // Если на старте exe-шника user32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"user32.dll") || !lstrcmpiW(mi.szModule, L"user32"))) // { // ghUser32 = LoadLibraryW(user32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghShell32) //{ // // Если на старте exe-шника shell32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"shell32.dll") || !lstrcmpiW(mi.szModule, L"shell32"))) // { // ghShell32 = LoadLibraryW(shell32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghAdvapi32) //{ // // Если на старте exe-шника advapi32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"advapi32.dll") || !lstrcmpiW(mi.szModule, L"advapi32"))) // { // ghAdvapi32 = LoadLibraryW(advapi32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // if (ghAdvapi32) // { // RegOpenKeyEx_f = (RegOpenKeyEx_t)GetProcAddress(ghAdvapi32, "RegOpenKeyExW"); // RegCreateKeyEx_f = (RegCreateKeyEx_t)GetProcAddress(ghAdvapi32, "RegCreateKeyExW"); // RegCloseKey_f = (RegCloseKey_t)GetProcAddress(ghAdvapi32, "RegCloseKey"); // } // //InitHooks(NULL); -- ниже и так будет выполнено // } //} if (lbAddMod) { if (PrepareNewModule(mi.hModule, NULL, mi.szModule, TRUE/*не звать CheckProcessModules*/)) CheckLoadedModule(mi.szModule); } else if (mi.hModule == hFromModule) { lbAddMod = TRUE; } } while (Module32Next(h, &mi)); CloseHandle(h); } } #endif #ifdef _DEBUG void OnLoadLibraryLog(LPCSTR lpLibraryA, LPCWSTR lpLibraryW) { #if 0 if ((lpLibraryA && strncmp(lpLibraryA, "advapi32", 8)==0) || (lpLibraryW && wcsncmp(lpLibraryW, L"advapi32", 8)==0)) { extern HANDLE ghDebugSshLibs, ghDebugSshLibsRc; if (ghDebugSshLibs) { SetEvent(ghDebugSshLibs); WaitForSingleObject(ghDebugSshLibsRc, 1000); } } #endif } #else #define OnLoadLibraryLog(lpLibraryA,lpLibraryW) #endif /* ************** */ HMODULE WINAPI OnLoadLibraryAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryA_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpiA(lpFileName, "kernel32.dll") == 0) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryA(const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); ORIGINAL(LoadLibraryA); return OnLoadLibraryAWork((FARPROC)F(LoadLibraryA), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); HMODULE module = NULL; OnLoadLibraryLog(NULL,lpFileName); // Спрятать ExtendedConsole.dll с глаз долой, в сервисную папку "ConEmu" if (lpFileName && ((lstrcmpiW(lpFileName, L"ExtendedConsole.dll") == 0) || lstrcmpiW(lpFileName, L"ExtendedConsole64.dll") == 0)) { CESERVER_CONSOLE_MAPPING_HDR *Info = (CESERVER_CONSOLE_MAPPING_HDR*)calloc(1,sizeof(*Info)); if (Info && ::LoadSrvMapping(ghConWnd, *Info)) { size_t cchMax = countof(Info->ComSpec.ConEmuBaseDir)+64; wchar_t* pszFullPath = (wchar_t*)calloc(cchMax,sizeof(*pszFullPath)); if (pszFullPath) { _wcscpy_c(pszFullPath, cchMax, Info->ComSpec.ConEmuBaseDir); _wcscat_c(pszFullPath, cchMax, WIN3264TEST(L"\\ExtendedConsole.dll",L"\\ExtendedConsole64.dll")); module = ((OnLoadLibraryW_t)lpfn)(pszFullPath); SafeFree(pszFullPath); } } SafeFree(Info); } if (!module) module = ((OnLoadLibraryW_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled || gbLdrDllNotificationUsed) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpi(lpFileName, L"kernel32.dll") == 0) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryW(const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); ORIGINAL(LoadLibraryW); return OnLoadLibraryWWork((FARPROC)F(LoadLibraryW), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryExAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryExA_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExA); return OnLoadLibraryExAWork((FARPROC)F(LoadLibraryExA), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ HMODULE WINAPI OnLoadLibraryExWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(NULL,lpFileName); HMODULE module = ((OnLoadLibraryExW_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExW(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExW); return OnLoadLibraryExWWork((FARPROC)F(LoadLibraryExW), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ FARPROC WINAPI OnGetProcAddressWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); FARPROC lpfnRc = NULL; #ifdef LOG_ORIGINAL_CALL char gszLastGetProcAddress[255], lsProcNameCut[64]; if (((DWORD_PTR)lpProcName) <= 0xFFFF) msprintf(lsProcNameCut, countof(lsProcNameCut), "%u", LOWORD(lpProcName)); else lstrcpynA(lsProcNameCut, lpProcName, countof(lsProcNameCut)); #endif WARNING("Убрать gbHooksTemporaryDisabled?"); if (gbHooksTemporaryDisabled) { TODO("!!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s,%u)", (DWORD)hModule, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? "" : lsProcNameCut, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? (UINT)(DWORD_PTR)lsProcNameCut : 0); #endif } else if (gbDllStopCalled) { //-- assert нельзя, т.к. все уже деинициализировано! //_ASSERTE(ghHeap!=NULL); //-- lpfnRc = NULL; -- уже } else if (((DWORD_PTR)lpProcName) <= 0xFFFF) { TODO("!!! Обрабатывать и ORDINAL values !!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%u)", (DWORD)hModule, (UINT)(DWORD_PTR)lsProcNameCut); #endif // Ordinal - пока используется только для "ShellExecCmdLine" if (gpHooks && gbPrepareDefaultTerminal) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && gpHooks[i].NameOrdinal && (gpHooks[i].NameOrdinal == (DWORD)(DWORD_PTR)lpProcName)) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } else { #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s)", (DWORD)hModule, lsProcNameCut); #endif if (gpHooks) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && strcmp(gpHooks[i].Name, lpProcName) == 0) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } #ifdef LOG_ORIGINAL_CALL if (lpfnRc) lstrcatA(gszLastGetProcAddress, " - hooked"); #endif if (!lpfnRc) { lpfnRc = ((OnGetProcAddress_t)lpfn)(hModule, lpProcName); #ifdef _DEBUG #ifdef ASSERT_ON_PROCNOTFOUND DWORD dwErr = GetLastError(); _ASSERTEX(lpfnRc != NULL); SetLastError(dwErr); #endif #endif } #ifdef LOG_ORIGINAL_CALL int nLeft = lstrlenA(gszLastGetProcAddress); msprintf(gszLastGetProcAddress+nLeft, countof(gszLastGetProcAddress)-nLeft, WIN3264TEST(" - 0x%08X\n"," - 0x%08X%08X\n"), WIN3264WSPRINT(lpfnRc)); DebugStringA(gszLastGetProcAddress); #endif return lpfnRc; } FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); ORIGINALFAST(GetProcAddress); return OnGetProcAddressWork((FARPROC)F(GetProcAddress), ph, FALSE, hModule, lpProcName); } FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName) { return OnGetProcAddressWork(gKernelFuncs[hlfGetProcAddress].OldAddress, gpHooks+hlfGetProcAddress, FALSE, hModule, lpProcName); } /* ************** */ void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep) { BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; if ((iStep == 0) && gbLogLibraries && !gbDllStopCalled) { CShellProc* sp = new CShellProc(); if (sp->LoadSrvMapping()) { CESERVER_REQ* pIn = NULL; if (pszModule && *pszModule) { lstrcpyn(szModule, pszModule, countof(szModule)); } else { wchar_t szHandle[32] = {}; #ifdef _WIN64 msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X%08X>", (DWORD)((((u64)hModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)hModule) & 0xFFFFFFFF)); //-V112 #else msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X>", (DWORD)hModule); #endif // GetModuleFileName в некоторых случаях зависает O_O. Поэтому, запоминаем в локальном массиве имя загруженного ранее модуля if (FindModuleFileName(hModule, szModule, countof(szModule)-lstrlen(szModule)-1)) wcscat_c(szModule, szHandle); else wcscpy_c(szModule, szHandle+2); } pIn = sp->NewCmdOnCreate(eFreeLibrary, NULL, szModule, NULL, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; } // Далее только если !LDR_IS_RESOURCE if ((iStep > 0) && !lbResource && !gbDllStopCalled) { // Попробуем определить, действительно ли модуль выгружен, или только счетчик уменьшился // iStep == 2 comes from LdrDllNotification(Unload) // Похоже, что если библиотека была реально выгружена, то FreeLibrary выставляет SetLastError(ERROR_GEN_FAILURE) // Актуально только для Win2k/XP так что не будем на это полагаться BOOL lbModulePost = (iStep == 2) ? FALSE : IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #ifdef _DEBUG DWORD dwErr = lbModulePost ? 0 : GetLastError(); #endif if (!lbModulePost) { RemoveHookedModule(hModule); if (ghOnLoadLibModule == hModule) { ghOnLoadLibModule = NULL; gfOnLibraryLoaded = NULL; gfOnLibraryUnLoaded = NULL; } if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (gpHooks[i].hCallbackModule == hModule) { gpHooks[i].hCallbackModule = NULL; gpHooks[i].PreCallBack = NULL; gpHooks[i].PostCallBack = NULL; gpHooks[i].ExceptCallBack = NULL; } } } TODO("Тоже на цикл переделать, как в CheckLoadedModule"); if (gfOnLibraryUnLoaded) { gfOnLibraryUnLoaded(hModule); } // Если выгружена библиотека ghUser32/ghAdvapi32/ghComdlg32... // проверить, может какие наши импорты стали невалидными FreeLoadedModule(hModule); } } } BOOL WINAPI OnFreeLibraryWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); BOOL lbRc = FALSE; BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll UnprepareModule(hModule, NULL, 0); #ifdef _DEBUG BOOL lbModulePre = IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #endif // Section locking is inadmissible. One FreeLibrary may cause another FreeLibrary in _different_ thread. lbRc = ((OnFreeLibrary_t)lpfn)(hModule); DWORD dwFreeErrCode = GetLastError(); // Далее только если !LDR_IS_RESOURCE if (lbRc && !lbResource) UnprepareModule(hModule, NULL, 1); SetLastError(dwFreeErrCode); return lbRc; } BOOL WINAPI OnFreeLibrary(HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); ORIGINALFAST(FreeLibrary); return OnFreeLibraryWork((FARPROC)F(FreeLibrary), ph, FALSE, hModule); } #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError() { typedef DWORD (WINAPI* OnGetLastError_t)(); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(GetLastError); DWORD nErr = 0; if (F(GetLastError)) nErr = F(GetLastError)(); if (nErr == HOOK_ERROR_NO) { nErr = HOOK_ERROR_NO; } return nErr; } VOID WINAPI OnSetLastError(DWORD dwErrCode) { typedef DWORD (WINAPI* OnSetLastError_t)(DWORD dwErrCode); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(SetLastError); if (dwErrCode == HOOK_ERROR_NO) { dwErrCode = HOOK_ERROR_NO; } if (F(SetLastError)) F(SetLastError)(dwErrCode); } #endif /* ***************** Logging ****************** */ #ifdef LOG_ORIGINAL_CALL void LogFunctionCall(LPCSTR asFunc, LPCSTR asFile, int anLine) { if (!gbSuppressShowCall || gbSkipSuppressShowCall) { DWORD nErr = GetLastError(); char sFunc[128]; _wsprintfA(sFunc, SKIPLEN(countof(sFunc)) "Hook[%u]: %s\n", GetCurrentThreadId(), asFunc); DebugStringA(sFunc); SetLastError(nErr); } else { gbSuppressShowCall = false; } } #endif
27.984514
226
0.684435
Maximus5
13049abd6de0ff146e5cb53fc3e3ef511415faa8
7,923
cpp
C++
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
/* // // DEKAF(tm): Lighter, Faster, Smarter(tm) // // Copyright (c) 2017, Ridgeware, Inc. // // +-------------------------------------------------------------------------+ // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\| // |/+---------------------------------------------------------------------+/| // |/| |/| // |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\| // |/| |/| // |\| OPEN SOURCE LICENSE |\| // |/| |/| // |\| 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 "kquotedprintable.h" #include "kstringutils.h" #include "klog.h" #include <cctype> namespace dekaf2 { constexpr char sxDigit[] = "0123456789ABCDEF"; enum ETYPE : uint8_t { NO, // no, do not encode YY, // yes, encode LF, // linefeed SL, // encode if at start of line MH // encode if used in mail headers }; constexpr ETYPE sEncodeCodepoints[256] = { // 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB 0xC 0xD 0xE 0xF YY, YY, YY, YY, YY, YY, YY, YY, YY, MH, LF, YY, YY, LF, YY, YY, // 0x00 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x10 MH, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, SL, NO, // 0x20 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, NO, MH, // 0x30 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x40 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, MH, // 0x50 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x60 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, YY, // 0x70 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x80 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x90 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xA0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xB0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xC0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xD0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xE0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xF0 }; //----------------------------------------------------------------------------- KString KQuotedPrintable::Encode(KStringView sInput, bool bForMailHeaders) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); uint16_t iLineLen { 0 }; uint16_t iMaxLineLen { 75 }; if (bForMailHeaders) { out += "=?UTF-8?Q?"; // we already add the 2 chars we need to close the encoding, and reserve 15 // chars for the 'Header: ' iMaxLineLen = 75 - (10 + 2 + 15); } for (auto byte : sInput) { if (iLineLen >= iMaxLineLen) { if (bForMailHeaders) { out += "?=\r\n "; out += "=?UTF-8?Q?"; iMaxLineLen = 75 - (1 + 10 + 2); } else { out += "=\r\n"; iMaxLineLen = 75 - 1; } iLineLen = 0; } switch (sEncodeCodepoints[static_cast<uint8_t>(byte)]) { case NO: // do not encode out += byte; ++iLineLen; continue; case SL: // encode if at start of line if (iLineLen > 0) { out += byte; ++iLineLen; continue; } // yes, encode break; case LF: // copy, reset line counter out += byte; iLineLen = 0; continue; case MH: // encode if in mail headers if (!bForMailHeaders) { out += byte; ++iLineLen; continue; } // yes, encode break; case YY: // yes, encode break; } out += '='; out += sxDigit[(byte >> 4) & 0x0f]; out += sxDigit[(byte ) & 0x0f]; iLineLen += 3; } if (bForMailHeaders) { out += "?="; } return out; } // Encode //----------------------------------------------------------------------------- void FlushRaw(KString& out, uint16_t iDecode, KString::value_type LeadChar, KString::value_type ch = 'f') //----------------------------------------------------------------------------- { out += '='; if (iDecode == 1) { out += LeadChar; } // 'f' signals that the input starved, as 'f' is a valid xdigit if (ch != 'f') { out += ch; } } // FlushRaw //----------------------------------------------------------------------------- KString KQuotedPrintable::Decode(KStringView sInput, bool bDotStuffing) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); KString::value_type LeadChar { 0 }; uint16_t iDecode { 0 }; bool bStartOfLine { true }; for (auto ch : sInput) { if (iDecode) { if (iDecode == 2 && (ch == '\r' || ch == '\n')) { bStartOfLine = true; if (ch == '\n') { iDecode = 0; } } else if (!KASCII::kIsXDigit(ch)) { if (ch == '\r' || ch == '\n') { bStartOfLine = true; } else { kDebug(2, "illegal encoding, flushing raw"); FlushRaw(out, iDecode, LeadChar, ch); } iDecode = 0; } else if (--iDecode == 1) { LeadChar = ch; } else { uint16_t iValue = kFromBase36(LeadChar) << 4; iValue += kFromBase36(ch); out += static_cast<KString::value_type>(iValue); } } else { switch (ch) { case '\r': case '\n': bStartOfLine = true; out += ch; break; case '=': bStartOfLine = false; iDecode = 2; break; default: if (bStartOfLine) { bStartOfLine = false; if (bDotStuffing && ch == '.') { break; } } out += ch; break; } } } if (iDecode) { kDebug(2, "QuotedPrintable decoding ended prematurely, flushing raw"); FlushRaw(out, iDecode, LeadChar); } return out; } // Decode } // end of namespace dekaf2
28.296429
105
0.441247
ridgeware
131225564493d521c005ae83f0b3a9a1ebd1edb1
96,834
cpp
C++
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
1
2020-07-16T04:49:29.000Z
2020-07-16T04:49:29.000Z
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * bridge API * bridge API generated from bridge.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git */ /* Do not edit this file manually */ #include "BridgeApi.h" namespace io { namespace swagger { namespace server { namespace api { using namespace io::swagger::server::model; BridgeApi::BridgeApi() { setupRoutes(); }; void BridgeApi::control_handler(const HttpHandleRequest &request, HttpHandleResponse &response) { try { auto s = router.route(request, response); if (s == Rest::Router::Status::NotFound) { response.send(Http::Code::Not_Found); } } catch (std::runtime_error &e) { response.send(polycube::service::Http::Code::Bad_Request, e.what()); } } void BridgeApi::setupRoutes() { using namespace polycube::service::Rest; Routes::Post(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::create_bridge_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::create_bridge_ports_access_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::create_bridge_ports_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::create_bridge_ports_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_ports_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::create_bridge_ports_stp_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::create_bridge_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::delete_bridge_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::delete_bridge_ports_access_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::delete_bridge_ports_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::delete_bridge_ports_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::delete_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::read_bridge_agingtime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::read_bridge_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/age/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_age_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Get(router, base + "/bridge/", Routes::bind(&BridgeApi::read_bridge_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::read_bridge_ports_access_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::read_bridge_ports_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::read_bridge_ports_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::read_bridge_ports_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::read_bridge_ports_mode_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::read_bridge_ports_peer_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::read_bridge_ports_status_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_ports_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::read_bridge_ports_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/state/", Routes::bind(&BridgeApi::read_bridge_ports_stp_state_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/uuid/", Routes::bind(&BridgeApi::read_bridge_ports_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::read_bridge_stp_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::read_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::read_bridge_stp_hellotime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::read_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::read_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::read_bridge_stp_priority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::read_bridge_stpenabled_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/uuid/", Routes::bind(&BridgeApi::read_bridge_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::read_bridge_type_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::update_bridge_agingtime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::update_bridge_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::update_bridge_ports_access_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::update_bridge_ports_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::update_bridge_ports_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::update_bridge_ports_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::update_bridge_ports_mode_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::update_bridge_ports_peer_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::update_bridge_ports_status_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_ports_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::update_bridge_ports_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::update_bridge_stp_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::update_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::update_bridge_stp_hellotime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::update_bridge_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::update_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::update_bridge_stp_priority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::update_bridge_stpenabled_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::update_bridge_type_by_id_handler, this)); } void BridgeApi::create_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); auto x = create_bridge_by_id(name, bridge); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); auto x = create_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } auto x = create_bridge_filteringdatabase_list_by_id(name, filteringdatabase); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); auto x = create_bridge_ports_access_by_id(name, portsName, access); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); auto x = create_bridge_ports_by_id(name, portsName, ports); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } auto x = create_bridge_ports_list_by_id(name, ports); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_ports_stp_by_id(name, portsName, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_ports_stp_list_by_id(name, portsName, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); auto x = create_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } auto x = create_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); auto x = create_bridge_ports_trunk_by_id(name, portsName, trunk); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_stp_by_id(name, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_stp_list_by_id(name, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::delete_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); delete_bridge_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); delete_bridge_filteringdatabase_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_filteringdatabase_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_access_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_ports_stp_by_id(name, portsName, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_stp_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); delete_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_trunk_allowed_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_trunk_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_stp_by_id(name, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_stp_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::read_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_agingtime_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_age_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_age_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_filteringdatabase_by_id(name, vlan, address); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_entrytype_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_filteringdatabase_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_port_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_list_by_id(); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // element is complex val["params"] = PortsAccessSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_access_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_access_vlanid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_address_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_mode_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_peer_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_status_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_stp_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_stp_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_pathcost_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_portpriority_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_state_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_state_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_trunk_allowed_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_trunk_nativevlan_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_uuid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_address_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_stp_by_id(name, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_forwarddelay_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_hellotime_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_stp_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_maxmessageage_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_priority_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_stpenabled_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_type_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_uuid_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::update_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param int32_t agingtime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library agingtime = request_body; update_bridge_agingtime_by_id(name, agingtime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); update_bridge_by_id(name, bridge); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); update_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string entrytype; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library entrytype = request_body; update_bridge_filteringdatabase_entrytype_by_id(name, vlan, address, entrytype); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } update_bridge_filteringdatabase_list_by_id(name, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string port; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library port = request_body; update_bridge_filteringdatabase_port_by_id(name, vlan, address, port); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); update_bridge_ports_access_by_id(name, portsName, access); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t vlanid; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library vlanid = request_body; update_bridge_ports_access_vlanid_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_ports_address_by_id(name, portsName, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); update_bridge_ports_by_id(name, portsName, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } update_bridge_ports_list_by_id(name, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string mode; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library mode = request_body; update_bridge_ports_mode_by_id(name, portsName, mode); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string peer; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library peer = request_body; update_bridge_ports_peer_by_id(name, portsName, peer); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string status; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library status = request_body; update_bridge_ports_status_by_id(name, portsName, status); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_ports_stp_by_id(name, portsName, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_ports_stp_list_by_id(name, portsName, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t pathcost; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library pathcost = request_body; update_bridge_ports_stp_pathcost_by_id(name, portsName, vlan, pathcost); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t portpriority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library portpriority = request_body; update_bridge_ports_stp_portpriority_by_id(name, portsName, vlan, portpriority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); update_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } update_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); update_bridge_ports_trunk_by_id(name, portsName, trunk); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t nativevlan; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library nativevlan = request_body; update_bridge_ports_trunk_nativevlan_by_id(name, portsName, nativevlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_stp_address_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_stp_by_id(name, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t forwarddelay; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library forwarddelay = request_body; update_bridge_stp_forwarddelay_by_id(name, vlan, forwarddelay); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t hellotime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library hellotime = request_body; update_bridge_stp_hellotime_by_id(name, vlan, hellotime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_stp_list_by_id(name, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t maxmessageage; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library maxmessageage = request_body; update_bridge_stp_maxmessageage_by_id(name, vlan, maxmessageage); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t priority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library priority = request_body; update_bridge_stp_priority_by_id(name, vlan, priority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param bool stpenabled; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library stpenabled = request_body; update_bridge_stpenabled_by_id(name, stpenabled); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::string type; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library type = request_body; update_bridge_type_by_id(name, type); response.send(polycube::service::Http::Code::Ok); } } } } }
41.101019
181
0.679988
mbertrone
13160379f3ae6bae62e83f610ee3f43beb4cdab3
1,158
cpp
C++
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
74
2019-07-29T11:45:33.000Z
2021-08-20T00:08:48.000Z
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
null
null
null
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
14
2019-09-04T09:04:02.000Z
2021-08-02T17:08:39.000Z
/********************************************************** * Author : Apriluestc * Email : 13669186256@163.com * Last modified : 2019-07-28 13:24 * Filename : Channel.cpp * Description : 事件和描述符的封装 * 包括文件描述符的获取、设置 * 事件的设置、获取 * 以及读、写、异常、错误事件的分发处理 * *******************************************************/ #include <unistd.h> #include <queue> #include <cstdlib> #include <iostream> #include "Channel.h" #include "Util.h" #include "Epoll.h" #include "EventLoop.h" Channel::Channel(EventLoop *loop) :loop_(loop), events_(0), lastEvents_(0) {} Channel::Channel(EventLoop *loop, int fd) :loop_(loop), fd_(fd), events_(0), lastEvents_(0) {} Channel::~Channel() {} int Channel::getFd() { return fd_; } void Channel::setFd(int fd) { fd_ = fd; } void Channel::handleRead() { if (readHandler_) { readHandler_(); } } void Channel::handleWrite() { if (writeHandler_) { writeHandler_(); } } void Channel::handleConn() { if (connHandler_) { connHandler_(); } }
18.983607
60
0.497409
Apriluestc
1317e280190edb91978fe893cfc6b86a8d4920be
7,300
hpp
C++
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
#ifndef FF_DRECEIVER_H #define FF_DRECEIVER_H #include <iostream> #include <sstream> #include <ff/ff.hpp> #include <ff/distributed/ff_network.hpp> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/uio.h> #include <arpa/inet.h> #include <cereal/cereal.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/polymorphic.hpp> using namespace ff; class ff_dreceiver: public ff_monode_t<message_t> { private: int sendRoutingTable(int sck){ dataBuffer buff; std::ostream oss(&buff); cereal::PortableBinaryOutputArchive oarchive(oss); std::vector<int> reachableDestinations; for(auto const& p : this->routingTable) reachableDestinations.push_back(p.first); oarchive << reachableDestinations; size_t sz = htobe64(buff.getLen()); struct iovec iov[1]; iov[0].iov_base = &sz; iov[0].iov_len = sizeof(sz); if (writevn(sck, iov, 1) < 0 || writen(sck, buff.getPtr(), buff.getLen()) < 0){ error("Error writing on socket the routing Table\n"); return -1; } return 0; } int handleRequest(int sck){ int sender; int chid; size_t sz; struct iovec iov[3]; iov[0].iov_base = &sender; iov[0].iov_len = sizeof(sender); iov[1].iov_base = &chid; iov[1].iov_len = sizeof(chid); iov[2].iov_base = &sz; iov[2].iov_len = sizeof(sz); switch (readvn(sck, iov, 3)) { case -1: error("Error reading from socket\n"); // fatal error case 0: return -1; // connection close } // convert values to host byte order sender = ntohl(sender); chid = ntohl(chid); sz = be64toh(sz); if (sz > 0){ char* buff = new char [sz]; assert(buff); if(readn(sck, buff, sz) < 0){ error("Error reading from socket\n"); delete [] buff; return -1; } message_t* out = new message_t(buff, sz, true); assert(out); out->sender = sender; out->chid = chid; //std::cout << "received something from " << sender << " directed to " << chid << std::endl; ff_send_out_to(out, this->routingTable[chid]); // assume the routing table is consistent WARNING!!! return 0; } neos++; // increment the eos received return -1; } public: ff_dreceiver(const int dGroup_id, ff_endpoint acceptAddr, size_t input_channels, std::map<int, int> routingTable = {std::make_pair(0,0)}, int coreid=-1) : input_channels(input_channels), acceptAddr(acceptAddr), routingTable(routingTable), distributedGroupId(dGroup_id), coreid(coreid) {} int svc_init() { if (coreid!=-1) ff_mapThreadToCpu(coreid); #ifdef LOCAL if ((listen_sck=socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } struct sockaddr_un serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sun_family = AF_LOCAL; strncpy(serv_addr.sun_path, acceptAddr.address.c_str(), acceptAddr.address.size()+1); #endif #ifdef REMOTE if ((listen_sck=socket(AF_INET, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } int enable = 1; // enable the reuse of the address if (setsockopt(listen_sck, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) error("setsockopt(SO_REUSEADDR) failed\n"); struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; // still listening from any interface serv_addr.sin_port = htons( acceptAddr.port ); #endif if (bind(listen_sck, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){ error("Error binding\n"); return -1; } if (listen(listen_sck, MAXBACKLOG) < 0){ error("Error listening\n"); return -1; } /*for (const auto& e : routingTable) std::cout << "Entry: " << e.first << " -> " << e.second << std::endl; */ return 0; } void svc_end() { close(this->listen_sck); #ifdef LOCAL unlink(this->acceptAddr.address.c_str()); #endif } /* Here i should not care of input type nor input data since they come from a socket listener. Everything will be handled inside a while true in the body of this node where data is pulled from network */ message_t *svc(message_t* task) { /* here i should receive the task via socket */ fd_set set, tmpset; // intialize both sets (master, temp) FD_ZERO(&set); FD_ZERO(&tmpset); // add the listen socket to the master set FD_SET(this->listen_sck, &set); // hold the greater descriptor int fdmax = this->listen_sck; while(neos < input_channels){ // copy the master set to the temporary tmpset = set; switch(select(fdmax+1, &tmpset, NULL, NULL, NULL)){ case -1: error("Error on selecting socket\n"); return EOS; case 0: continue; } // iterate over the file descriptor to see which one is active for(int i=0; i <= fdmax; i++) if (FD_ISSET(i, &tmpset)){ if (i == this->listen_sck) { int connfd = accept(this->listen_sck, (struct sockaddr*)NULL ,NULL); if (connfd == -1){ error("Error accepting client\n"); } else { FD_SET(connfd, &set); if(connfd > fdmax) fdmax = connfd; this->sendRoutingTable(connfd); // here i should check the result of the call! and handle possible errors! } continue; } // it is not a new connection, call receive and handle possible errors if (this->handleRequest(i) < 0){ close(i); FD_CLR(i, &set); // update the maximum file descriptor if (i == fdmax) for(int i=(fdmax-1);i>=0;--i) if (FD_ISSET(i, &set)){ fdmax = i; break; } } } } /* In theory i should never return because of the while true. In our first example this is necessary */ return this->EOS; } private: size_t neos = 0; size_t input_channels; int listen_sck; ff_endpoint acceptAddr; std::map<int, int> routingTable; int distributedGroupId; int coreid; }; #endif
31.877729
156
0.528904
gerzin
131c7c8119834813aeca5fa393e4aa9b9e9352fb
350
cpp
C++
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
1
2022-01-26T01:11:10.000Z
2022-01-26T01:11:10.000Z
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
null
null
null
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int n ,point , input = 0; cin >> n; while (n > 0){ for(int i = 0 ; i <3 ;i++){ cin>>input; point = point + input; } n--; } if(point == 0){ cout<<"YES"; }else{ cout<<"NO"; } }
15.217391
39
0.402857
geeknarendra
131eafafe73796cd97b62318f880e8e98da80e17
235
cpp
C++
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
16
2018-02-05T15:01:35.000Z
2022-01-21T10:21:43.000Z
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
2
2016-11-15T03:32:43.000Z
2019-04-21T23:11:10.000Z
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
3
2018-03-06T01:32:42.000Z
2021-01-27T07:25:37.000Z
// expression_test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <chrono> #pragma warning(disable:4996) #pragma warning(disable:4146) #include "../../Program.cpp" #include "../main.cpp"
18.076923
77
0.714894
ddf
13207fec8453cb578236e50af99ae43cf26e59cc
5,176
cpp
C++
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/SlicedSprite.hpp> #include <Nazara/Graphics/BasicMaterial.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderSpriteChain.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { SlicedSprite::SlicedSprite(std::shared_ptr<Material> material) : m_material(std::move(material)), m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { UpdateVertices(); } void SlicedSprite::BuildElement(std::size_t passIndex, const WorldInstance& worldInstance, std::vector<std::unique_ptr<RenderElement>>& elements, const Recti& scissorBox) const { const auto& materialPass = m_material->GetPass(passIndex); if (!materialPass) return; const std::shared_ptr<VertexDeclaration>& vertexDeclaration = VertexDeclaration::Get(VertexLayout::XYZ_Color_UV); std::vector<RenderPipelineInfo::VertexBufferData> vertexBufferData = { { { 0, vertexDeclaration } } }; const auto& renderPipeline = materialPass->GetPipeline()->GetRenderPipeline(vertexBufferData); const auto& whiteTexture = Graphics::Instance()->GetDefaultTextures().whiteTextures[UnderlyingCast(ImageType::E2D)]; elements.emplace_back(std::make_unique<RenderSpriteChain>(GetRenderLayer(), materialPass, renderPipeline, worldInstance, vertexDeclaration, whiteTexture, m_spriteCount, m_vertices.data(), scissorBox)); } const std::shared_ptr<Material>& SlicedSprite::GetMaterial(std::size_t i) const { assert(i == 0); NazaraUnused(i); return m_material; } std::size_t SlicedSprite::GetMaterialCount() const { return 1; } inline auto SlicedSprite::GetTopLeftCorner() const -> const Corner& { return m_topLeftCorner; } Vector3ui SlicedSprite::GetTextureSize() const { assert(m_material); //TODO: Cache index in registry? if (const auto& material = m_material->FindPass("ForwardPass")) { BasicMaterial mat(*material); if (mat.HasDiffuseMap()) { // Material should always have textures but we're better safe than sorry if (const auto& texture = mat.GetDiffuseMap()) return texture->GetSize(); } } // Couldn't get material pass or texture return Vector3ui::Unit(); //< prevents division by zero } void SlicedSprite::UpdateVertices() { VertexStruct_XYZ_Color_UV* vertices = m_vertices.data(); std::array<float, 3> heights = { m_topLeftCorner.size.y, m_size.y - m_topLeftCorner.size.y - m_bottomRightCorner.size.y, m_bottomRightCorner.size.y }; std::array<float, 3> widths = { m_topLeftCorner.size.x, m_size.x - m_topLeftCorner.size.x - m_bottomRightCorner.size.x, m_bottomRightCorner.size.x }; std::array<float, 3> texCoordsX = { m_topLeftCorner.textureCoords.x * m_textureCoords.width, m_textureCoords.width - m_topLeftCorner.textureCoords.x * m_textureCoords.width - m_bottomRightCorner.textureCoords.x * m_textureCoords.width, m_bottomRightCorner.textureCoords.x * m_textureCoords.width }; std::array<float, 3> texCoordsY = { m_topLeftCorner.textureCoords.y * m_textureCoords.height, m_textureCoords.height - m_topLeftCorner.textureCoords.y * m_textureCoords.height - m_bottomRightCorner.textureCoords.y * m_textureCoords.height, m_bottomRightCorner.textureCoords.y * m_textureCoords.height }; Vector3f origin = Vector3f::Zero(); Vector2f topLeftUV = m_textureCoords.GetCorner(RectCorner::LeftTop); m_spriteCount = 0; for (std::size_t y = 0; y < 3; ++y) { float height = heights[y]; if (height > 0.f) { for (std::size_t x = 0; x < 3; ++x) { float width = widths[x]; if (width > 0.f) { vertices->color = m_color; vertices->position = origin; vertices->uv = topLeftUV; vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], 0.f); vertices++; vertices->color = m_color; vertices->position = origin + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(0.f, texCoordsY[y]); vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right() + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], texCoordsY[y]); vertices++; origin.x += width; m_spriteCount++; } topLeftUV.x += texCoordsX[x]; } origin.y += height; } origin.x = 0; topLeftUV.x = m_textureCoords.x; topLeftUV.y += texCoordsY[y]; } Boxf aabb = Boxf::Zero(); std::size_t vertexCount = 4 * m_spriteCount; if (vertexCount > 0) { // Reverse texcoords Y for (std::size_t i = 0; i < vertexCount; ++i) m_vertices[i].uv.y = m_textureCoords.height - m_vertices[i].uv.y; aabb.Set(m_vertices[0].position); for (std::size_t i = 1; i < vertexCount; ++i) aabb.ExtendTo(m_vertices[i].position); } UpdateAABB(aabb); OnElementInvalidated(this); } }
28.916201
203
0.695131
jayrulez
1328669babfe2cc45cf20890d326188aa9410400
1,990
hpp
C++
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #define CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #include "GuiArea.hpp" #include <VistaAspects/VistaObserver.h> #include <VistaKernel/GraphicsManager/VistaOpenGLDraw.h> #include <vector> class VistaTransformNode; class VistaTransformMatrix; class VistaVector3D; class VistaQuaternion; class VistaProjection; class VistaViewport; class VistaGLSLShader; class VistaVertexArrayObject; class VistaBufferObject; namespace cs::gui { /// This class is used to render static UI elements, which are always at the same position of the /// screen. class CS_GUI_EXPORT ScreenSpaceGuiArea : public GuiArea, public IVistaOpenGLDraw, public IVistaObserver { public: explicit ScreenSpaceGuiArea(VistaViewport* pViewport); ~ScreenSpaceGuiArea() override; int getWidth() const override; int getHeight() const override; /// Draws the UI to screen. bool Do() override; bool GetBoundingBox(VistaBoundingBox& bb) override; /// Handles changes to the screen size. void ObserverUpdate(IVistaObserveable* pObserveable, int nMsg, int nTicket) override; private: virtual void onViewportChange(); VistaViewport* mViewport; VistaGLSLShader* mShader = nullptr; bool mShaderDirty = true; int mWidth = 0; int mHeight = 0; }; } // namespace cs::gui #endif // CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP
32.622951
100
0.598995
bernstein
132a036afe04926a94eb42c1bdf7e3d766df16c1
594
hpp
C++
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
#pragma once #include "Core/Core.hpp" #include "Core/Image.hpp" #include "Primus/Map.hpp" struct Colormap { Image image; }; // Holds data related to map to be used in the editor. struct EditorMap : public Map { int16 heightmapTileXMin = 66; int16 heightmapTileXMax = 70; int16 heightmapTileYMin = 45; int16 heightmapTileYMax = 50; int16 heightmapTileZoom = 7; int16 heightmapTileSize = 512; Colormap colormap; bool tryLoad(const wchar_t* mapDirectoryPath, float verticalFieldOfViewRadians, float aspectRatio); bool tryFixLandElevation(); };
21.214286
102
0.712121
DarebacK
132a3d777bcb9e34e5aa3ad46643ab4ba9ab9655
407
cc
C++
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://cses.fi/problemset/task/1090/ #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n, w; cin >> n >> w; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int i = 0; int j = n - 1; int c = 0; while (i <= j) { if (a[j] + a[i] > w) j--; else { i++; j--; } c++; } cout << c << endl; }
16.958333
42
0.479115
Ashindustry007
132b753443e1d4475bc08a149c635bec49733ecc
9,588
hpp
C++
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
24
2017-11-29T12:44:44.000Z
2022-03-06T12:45:52.000Z
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
3
2018-11-02T09:21:27.000Z
2020-03-16T20:03:17.000Z
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
12
2017-10-26T08:42:06.000Z
2022-03-06T12:45:52.000Z
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright (c) 2018, FZI Forschungszentrum Informatik // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions // and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials provided // with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to // endorse or promote products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY // WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Philipp Bender <philipp.bender@fzi.de> * \date 2014-01-01 * */ //---------------------------------------------------------------------- #pragma once #include <boost/math/special_functions.hpp> #include <cmath> #include <boost/tuple/tuple.hpp> #include <boost/variant/get.hpp> #include "LocalGeographicCS.hpp" #include "normalize_angle.hpp" #include "Attribute.hpp" namespace LLet { enum LATLON_COORDS { LAT = 0, LON = 1, ID = 2 }; enum XY_COORDS { X = 0, Y = 1 }; class point_with_id_t : public boost::tuple<double, double, int64_t>, public HasAttributes { public: point_with_id_t(const boost::tuple<double, double, int64_t> &tuple = boost::tuple<double, double, int64_t>(0.0, 0.0, -1)) : boost::tuple<double, double, int64_t>(tuple) { // nothing to do } #ifdef _WIN32 // The tuple implementation of MSVC10 fails on the auto-generated copy ctor point_with_id_t(const point_with_id_t &other) : HasAttributes(other) { boost::get<LLet::LAT>(*this) = boost::get<LLet::LAT>(other); boost::get<LLet::LON>(*this) = boost::get<LLet::LON>(other); boost::get<LLet::ID>(*this) = boost::get<LLet::ID>(other); } #endif }; inline bool operator==(const point_with_id_t& lhs, const point_with_id_t& rhs) { return boost::get<0>(lhs) == boost::get<0>(rhs) && boost::get<1>(lhs) == boost::get<1>(rhs) && boost::get<2>(lhs) == boost::get<2>(rhs); } inline bool operator!=(const point_with_id_t& lhs, const point_with_id_t& rhs){return !(lhs == rhs);} typedef boost::tuple< double, double > point_xy_t; typedef std::vector<point_xy_t> vertex_container_t; inline boost::tuple< double, double > vec( const point_with_id_t& a, const point_with_id_t& b ) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); double ax, ay, bx, by; boost::tie(ax, ay) = cs.ll2xy(get<LAT>(a), get<LON>(a)); boost::tie(bx, by) = cs.ll2xy(get<LAT>(b), get<LON>(b)); double dx = bx - ax; double dy = by - ay; return boost::make_tuple(dx, dy); } //! Calculate the absolute point from absolute point \a a with relative offset \a vec and the given id \a id inline point_with_id_t from_vec(const point_with_id_t& a, const point_xy_t& vec, const int64_t id = -1) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); const boost::tuple<double, double>& ll = cs.xy2ll(get<X>(vec), get<Y>(vec)); return boost::make_tuple(get<LAT>(ll), get<LON>(ll), id); } inline double abs( const boost::tuple< double, double > &v ) { using boost::get; using boost::math::hypot; return hypot( get<X>(v), get<Y>(v) ); } //! Calculate the distance between (metric) a and b inline double dist(const point_xy_t& a, const point_xy_t& b) { using boost::get; return abs(boost::make_tuple(get<X>(b) - get<X>(a), get<Y>(b) - get<Y>(a))); } //! Normalize the vector \a vec inline void normalize(boost::tuple<double, double>& vec) { using boost::get; const double length = abs(vec); assert(length != 0 && "The given vector's length is 0."); vec = boost::make_tuple(get<X>(vec) / length, get<Y>(vec) / length); } //! Calculate the distance between (gnss) a and b inline double dist( const point_with_id_t& a, const point_with_id_t& b ) { return abs(vec(a, b)); } inline double scalar_product( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; return get<X>(a) * get<X>(b) + get<Y>(a) * get<Y>(b); } //! Project p on line inline point_xy_t projected(const point_xy_t& p, const vertex_container_t &line, double* angle=0, std::size_t* index=0, std::size_t* previous_index=0, std::size_t* subsequent_index=0) { double min_distance = -1.0; double const px = boost::get<LLet::X>(p); double const py = boost::get<LLet::Y>(p); point_xy_t min_point = p; size_t const size = line.size(); for (std::size_t i=1; i<size; ++i) { const double& ax = boost::get<LLet::X>(line[i-1]); const double& ay = boost::get<LLet::Y>(line[i-1]); const double& bx = boost::get<LLet::X>(line[i]); const double& by = boost::get<LLet::Y>(line[i]); point_xy_t const AP = point_xy_t(px-ax, py-ay); point_xy_t const AB = point_xy_t(bx-ax, by-ay); double const scalar_product_ab = scalar_product(AB, AB); double const lambda = scalar_product(AP, AB) / ( scalar_product_ab == 0.0 ? 1.0 : scalar_product_ab ); double distance = 0.0; point_xy_t c; if (lambda <= 0.0) { c = line[i-1]; } else if (lambda < 1.0) { c = point_xy_t(ax + lambda*(bx-ax), ay + lambda*(by-ay)); } else { c = line[i]; } distance = dist(p, c); if (min_distance < 0.0 || distance < min_distance) { min_distance = distance; min_point = c; if (angle) { *angle = atan2(boost::get<Y>(line[i])-boost::get<Y>(line[i-1]), boost::get<X>(line[i])-boost::get<X>(line[i-1])); } if (index) { *index = lambda < 0.5? i-1 : i; } if (subsequent_index) { *subsequent_index = i; } if (previous_index) { *previous_index = i-1; } } } return min_point; } inline double angle( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; double sp = scalar_product(a, b); double cos_phi = sp / (abs(a) * abs(b)); // sign for angle: test cross product double crossp_z = get<X>(a) * get<Y>(b) - get<Y>(a) * get<X>(b); double signum = boost::math::sign(crossp_z); double phi = normalize_angle(signum * std::acos(cos_phi)); return phi; } template< typename T1, typename T2 > inline bool inrange(const T1& val, const T2& lo, const T2& hi) { return val >= lo && val <= hi; } /*! Interpolate the given points using a Catmull-Rom polygon. * Any \a ratio between 0 and 1 will interpolate in between \a p1 and \a p2. */ inline point_xy_t interpolate_spline(const point_xy_t& p0, const point_xy_t& p1, const point_xy_t& p2, const point_xy_t& p3, double ratio) { /* Catmull-Rom coefficients: * * a0 = -0.5*p0 + 1.5*p1 - 1.5*p2 + 0.5*p3 * a1 = p0 - 2.5*p1 + 2*p2 - 0.5*p3 * a2 = -0.5*p0 + 0.5*p2 */ const point_xy_t a0 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 1.5 * boost::get<X>(p1) - 1.5 * boost::get<X>(p2) + 0.5 * boost::get<X>(p3), -0.5 * boost::get<Y>(p0) + 1.5 * boost::get<Y>(p1) - 1.5 * boost::get<Y>(p2) + 0.5 * boost::get<Y>(p3)); const point_xy_t a1 = boost::make_tuple(boost::get<X>(p0) - 2.5 * boost::get<X>(p1) + 2. * boost::get<X>(p2) - 0.5 * boost::get<X>(p3), boost::get<Y>(p0) - 2.5 * boost::get<Y>(p1) + 2. * boost::get<Y>(p2) - 0.5 * boost::get<Y>(p3)); const point_xy_t a2 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 0.5 * boost::get<X>(p2), -0.5 * boost::get<Y>(p0) + 0.5 * boost::get<Y>(p2)); const double ratio_square = ratio * ratio; // Catmull-Rom polynom: result = a0 * ratio³ + a1 * ratio² + a2 * ratio + p1 return boost::make_tuple(boost::get<X>(a0) * ratio * ratio_square + boost::get<X>(a1) * ratio_square + boost::get<X>(a2) * ratio + boost::get<X>(p1), boost::get<Y>(a0) * ratio * ratio_square + boost::get<Y>(a1) * ratio_square + boost::get<Y>(a2) * ratio + boost::get<Y>(p1)); } //! Calculate the dot product for vector \a and vector \b inline double dot(const point_xy_t& a, const point_xy_t& b) { return boost::get<LLet::X>(a) * boost::get<LLet::X>(b) + boost::get<LLet::Y>(a) * boost::get<LLet::Y>(b); } }
34
176
0.618481
brand666
132c0abf222827a78c779e15a77a5978f342774e
29,723
cpp
C++
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
27
2021-09-28T00:33:11.000Z
2021-11-18T19:38:40.000Z
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F0 */ void _Print(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80152794 * Size: 0009C8 */ SpiderProp::SpiderProp() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x370(r1) stw r31, 0x36C(r1) mr r31, r3 stw r30, 0x368(r1) stw r29, 0x364(r1) stw r28, 0x360(r1) bl -0x4EE8 lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x1EC(r31) addi r0, r3, 0x737C stw r0, 0x1EC(r31) li r7, 0 lis r3, 0x802D stw r7, 0x1FC(r31) subi r6, r3, 0xBA0 lis r4, 0x802D stw r7, 0x1F8(r31) subi r3, r4, 0xE84 addi r0, r6, 0xC stw r7, 0x1F4(r31) addi r5, r1, 0x1B0 addi r4, r31, 0x200 stw r3, 0x1F0(r31) addi r3, r31, 0x204 stw r6, 0x54(r31) stw r0, 0x1EC(r31) stw r7, 0x200(r31) lwz r0, -0x398(r13) stw r0, 0x1B8(r1) lwz r0, 0x1B8(r1) stw r0, 0x1B0(r1) bl -0xF3DA0 lis r3, 0x802A addi r30, r3, 0x6098 stw r30, 0x20C(r31) addi r5, r1, 0x1AC addi r3, r31, 0x214 lfs f0, -0x5780(r2) addi r4, r31, 0x200 stfs f0, 0x210(r31) lwz r0, -0x394(r13) stw r0, 0x1C0(r1) lwz r0, 0x1C0(r1) stw r0, 0x1AC(r1) bl -0xF3DD4 stw r30, 0x21C(r31) addi r5, r1, 0x1A8 addi r3, r31, 0x224 lfs f0, -0x577C(r2) addi r4, r31, 0x200 stfs f0, 0x220(r31) lwz r0, -0x390(r13) stw r0, 0x1C8(r1) lwz r0, 0x1C8(r1) stw r0, 0x1A8(r1) bl -0xF3E00 stw r30, 0x22C(r31) addi r5, r1, 0x1A4 addi r3, r31, 0x234 lfs f0, -0x5778(r2) addi r4, r31, 0x200 stfs f0, 0x230(r31) lwz r0, -0x38C(r13) stw r0, 0x1D0(r1) lwz r0, 0x1D0(r1) stw r0, 0x1A4(r1) bl -0xF3E2C stw r30, 0x23C(r31) addi r5, r1, 0x1A0 addi r3, r31, 0x244 lfs f0, -0x5774(r2) addi r4, r31, 0x200 stfs f0, 0x240(r31) lwz r0, -0x388(r13) stw r0, 0x1D8(r1) lwz r0, 0x1D8(r1) stw r0, 0x1A0(r1) bl -0xF3E58 stw r30, 0x24C(r31) addi r5, r1, 0x19C addi r3, r31, 0x254 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x250(r31) lwz r0, -0x384(r13) stw r0, 0x1E0(r1) lwz r0, 0x1E0(r1) stw r0, 0x19C(r1) bl -0xF3E84 stw r30, 0x25C(r31) addi r5, r1, 0x198 addi r3, r31, 0x264 lfs f0, -0x576C(r2) addi r4, r31, 0x200 stfs f0, 0x260(r31) lwz r0, -0x380(r13) stw r0, 0x1E8(r1) lwz r0, 0x1E8(r1) stw r0, 0x198(r1) bl -0xF3EB0 stw r30, 0x26C(r31) addi r5, r1, 0x194 addi r3, r31, 0x274 lfs f0, -0x5768(r2) addi r4, r31, 0x200 stfs f0, 0x270(r31) lwz r0, -0x37C(r13) stw r0, 0x1F0(r1) lwz r0, 0x1F0(r1) stw r0, 0x194(r1) bl -0xF3EDC stw r30, 0x27C(r31) addi r5, r1, 0x190 addi r3, r31, 0x284 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x280(r31) lwz r0, -0x378(r13) stw r0, 0x1F8(r1) lwz r0, 0x1F8(r1) stw r0, 0x190(r1) bl -0xF3F08 stw r30, 0x28C(r31) addi r5, r1, 0x18C addi r3, r31, 0x294 lfs f0, -0x5760(r2) addi r4, r31, 0x200 stfs f0, 0x290(r31) lwz r0, -0x374(r13) stw r0, 0x200(r1) lwz r0, 0x200(r1) stw r0, 0x18C(r1) bl -0xF3F34 stw r30, 0x29C(r31) addi r5, r1, 0x188 addi r3, r31, 0x2A4 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x2A0(r31) lwz r0, -0x370(r13) stw r0, 0x208(r1) lwz r0, 0x208(r1) stw r0, 0x188(r1) bl -0xF3F60 stw r30, 0x2AC(r31) addi r5, r1, 0x184 addi r3, r31, 0x2B4 lfs f0, -0x575C(r2) addi r4, r31, 0x200 stfs f0, 0x2B0(r31) lwz r0, -0x36C(r13) stw r0, 0x210(r1) lwz r0, 0x210(r1) stw r0, 0x184(r1) bl -0xF3F8C stw r30, 0x2BC(r31) addi r5, r1, 0x180 addi r3, r31, 0x2C4 lfs f0, -0x5758(r2) addi r4, r31, 0x200 stfs f0, 0x2C0(r31) lwz r0, -0x368(r13) stw r0, 0x218(r1) lwz r0, 0x218(r1) stw r0, 0x180(r1) bl -0xF3FB8 stw r30, 0x2CC(r31) addi r5, r1, 0x17C addi r3, r31, 0x2D4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2D0(r31) lwz r0, -0x364(r13) stw r0, 0x220(r1) lwz r0, 0x220(r1) stw r0, 0x17C(r1) bl -0xF3FE4 stw r30, 0x2DC(r31) addi r5, r1, 0x178 addi r3, r31, 0x2E4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2E0(r31) lwz r0, -0x360(r13) stw r0, 0x228(r1) lwz r0, 0x228(r1) stw r0, 0x178(r1) bl -0xF4010 stw r30, 0x2EC(r31) addi r5, r1, 0x174 addi r3, r31, 0x2F4 lfs f0, -0x5750(r2) addi r4, r31, 0x200 stfs f0, 0x2F0(r31) lwz r0, -0x35C(r13) stw r0, 0x230(r1) lwz r0, 0x230(r1) stw r0, 0x174(r1) bl -0xF403C stw r30, 0x2FC(r31) addi r5, r1, 0x170 addi r3, r31, 0x304 lfs f0, -0x574C(r2) addi r4, r31, 0x200 stfs f0, 0x300(r31) lwz r0, -0x358(r13) stw r0, 0x238(r1) lwz r0, 0x238(r1) stw r0, 0x170(r1) bl -0xF4068 stw r30, 0x30C(r31) addi r5, r1, 0x16C addi r3, r31, 0x314 lfs f0, -0x5748(r2) addi r4, r31, 0x200 stfs f0, 0x310(r31) lwz r0, -0x354(r13) stw r0, 0x240(r1) lwz r0, 0x240(r1) stw r0, 0x16C(r1) bl -0xF4094 stw r30, 0x31C(r31) addi r5, r1, 0x168 addi r3, r31, 0x324 lfs f0, -0x5744(r2) addi r4, r31, 0x200 stfs f0, 0x320(r31) lwz r0, -0x350(r13) stw r0, 0x248(r1) lwz r0, 0x248(r1) stw r0, 0x168(r1) bl -0xF40C0 stw r30, 0x32C(r31) addi r5, r1, 0x164 addi r3, r31, 0x334 lfs f0, -0x5740(r2) addi r4, r31, 0x200 stfs f0, 0x330(r31) lwz r0, -0x34C(r13) stw r0, 0x250(r1) lwz r0, 0x250(r1) stw r0, 0x164(r1) bl -0xF40EC stw r30, 0x33C(r31) addi r5, r1, 0x160 addi r3, r31, 0x344 lfs f0, -0x573C(r2) addi r4, r31, 0x200 stfs f0, 0x340(r31) lwz r0, -0x348(r13) stw r0, 0x258(r1) lwz r0, 0x258(r1) stw r0, 0x160(r1) bl -0xF4118 stw r30, 0x34C(r31) addi r5, r1, 0x15C addi r3, r31, 0x354 lfs f0, -0x5738(r2) addi r4, r31, 0x200 stfs f0, 0x350(r31) lwz r0, -0x344(r13) stw r0, 0x260(r1) lwz r0, 0x260(r1) stw r0, 0x15C(r1) bl -0xF4144 stw r30, 0x35C(r31) addi r5, r1, 0x158 addi r3, r31, 0x364 lfs f0, -0x5734(r2) addi r4, r31, 0x200 stfs f0, 0x360(r31) lwz r0, -0x340(r13) stw r0, 0x268(r1) lwz r0, 0x268(r1) stw r0, 0x158(r1) bl -0xF4170 stw r30, 0x36C(r31) addi r5, r1, 0x154 addi r3, r31, 0x374 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x370(r31) lwz r0, -0x33C(r13) stw r0, 0x270(r1) lwz r0, 0x270(r1) stw r0, 0x154(r1) bl -0xF419C stw r30, 0x37C(r31) addi r5, r1, 0x150 addi r3, r31, 0x384 lfs f0, -0x5730(r2) addi r4, r31, 0x200 stfs f0, 0x380(r31) lwz r0, -0x338(r13) stw r0, 0x278(r1) lwz r0, 0x278(r1) stw r0, 0x150(r1) bl -0xF41C8 stw r30, 0x38C(r31) addi r5, r1, 0x14C addi r3, r31, 0x394 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x390(r31) lwz r0, -0x334(r13) stw r0, 0x280(r1) lwz r0, 0x280(r1) stw r0, 0x14C(r1) bl -0xF41F4 stw r30, 0x39C(r31) addi r5, r1, 0x148 addi r3, r31, 0x3A4 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x3A0(r31) lwz r0, -0x330(r13) stw r0, 0x288(r1) lwz r0, 0x288(r1) stw r0, 0x148(r1) bl -0xF4220 stw r30, 0x3AC(r31) addi r5, r1, 0x144 addi r3, r31, 0x3B4 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x3B0(r31) lwz r0, -0x32C(r13) stw r0, 0x290(r1) lwz r0, 0x290(r1) stw r0, 0x144(r1) bl -0xF424C stw r30, 0x3BC(r31) addi r5, r1, 0x140 addi r3, r31, 0x3C4 lfs f0, -0x5724(r2) addi r4, r31, 0x200 stfs f0, 0x3C0(r31) lwz r0, -0x328(r13) stw r0, 0x298(r1) lwz r0, 0x298(r1) stw r0, 0x140(r1) bl -0xF4278 stw r30, 0x3CC(r31) addi r5, r1, 0x13C addi r3, r31, 0x3D4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3D0(r31) lwz r0, -0x324(r13) stw r0, 0x2A0(r1) lwz r0, 0x2A0(r1) stw r0, 0x13C(r1) bl -0xF42A4 stw r30, 0x3DC(r31) addi r5, r1, 0x138 addi r3, r31, 0x3E4 lfs f0, -0x571C(r2) addi r4, r31, 0x200 stfs f0, 0x3E0(r31) lwz r0, -0x320(r13) stw r0, 0x2A8(r1) lwz r0, 0x2A8(r1) stw r0, 0x138(r1) bl -0xF42D0 stw r30, 0x3EC(r31) addi r5, r1, 0x134 addi r3, r31, 0x3F4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3F0(r31) lwz r0, -0x31C(r13) stw r0, 0x2B0(r1) lwz r0, 0x2B0(r1) stw r0, 0x134(r1) bl -0xF42FC stw r30, 0x3FC(r31) addi r5, r1, 0x130 addi r3, r31, 0x404 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x400(r31) lwz r0, -0x318(r13) stw r0, 0x2B8(r1) lwz r0, 0x2B8(r1) stw r0, 0x130(r1) bl -0xF4328 stw r30, 0x40C(r31) addi r5, r1, 0x12C addi r3, r31, 0x414 lfs f0, -0x5718(r2) addi r4, r31, 0x200 stfs f0, 0x410(r31) lwz r0, -0x314(r13) stw r0, 0x2C0(r1) lwz r0, 0x2C0(r1) stw r0, 0x12C(r1) bl -0xF4354 stw r30, 0x41C(r31) addi r5, r1, 0x128 addi r3, r31, 0x424 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x420(r31) lwz r0, -0x310(r13) stw r0, 0x2C8(r1) lwz r0, 0x2C8(r1) stw r0, 0x128(r1) bl -0xF4380 stw r30, 0x42C(r31) addi r5, r1, 0x124 addi r3, r31, 0x434 lfs f0, -0x5710(r2) addi r4, r31, 0x200 stfs f0, 0x430(r31) lwz r0, -0x30C(r13) stw r0, 0x2D0(r1) lwz r0, 0x2D0(r1) stw r0, 0x124(r1) bl -0xF43AC stw r30, 0x43C(r31) addi r5, r1, 0x120 addi r3, r31, 0x444 lfs f0, -0x570C(r2) addi r4, r31, 0x200 stfs f0, 0x440(r31) lwz r0, -0x308(r13) stw r0, 0x2D8(r1) lwz r0, 0x2D8(r1) stw r0, 0x120(r1) bl -0xF43D8 stw r30, 0x44C(r31) addi r5, r1, 0x11C addi r3, r31, 0x454 lfs f0, -0x5708(r2) addi r4, r31, 0x200 stfs f0, 0x450(r31) lwz r0, -0x304(r13) stw r0, 0x2E0(r1) lwz r0, 0x2E0(r1) stw r0, 0x11C(r1) bl -0xF4404 stw r30, 0x45C(r31) addi r5, r1, 0x118 addi r3, r31, 0x464 lfs f0, -0x5704(r2) addi r4, r31, 0x200 stfs f0, 0x460(r31) lwz r0, -0x300(r13) stw r0, 0x2E8(r1) lwz r0, 0x2E8(r1) stw r0, 0x118(r1) bl -0xF4430 stw r30, 0x46C(r31) addi r5, r1, 0x114 addi r3, r31, 0x474 lfs f0, -0x5700(r2) addi r4, r31, 0x200 stfs f0, 0x470(r31) lwz r0, -0x2FC(r13) stw r0, 0x2F0(r1) lwz r0, 0x2F0(r1) stw r0, 0x114(r1) bl -0xF445C stw r30, 0x47C(r31) addi r5, r1, 0x110 addi r3, r31, 0x484 lfs f0, -0x56FC(r2) addi r4, r31, 0x200 stfs f0, 0x480(r31) lwz r0, -0x2F8(r13) stw r0, 0x2F8(r1) lwz r0, 0x2F8(r1) stw r0, 0x110(r1) bl -0xF4488 stw r30, 0x48C(r31) addi r5, r1, 0x10C addi r3, r31, 0x494 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x490(r31) lwz r0, -0x2F4(r13) stw r0, 0x300(r1) lwz r0, 0x300(r1) stw r0, 0x10C(r1) bl -0xF44B4 stw r30, 0x49C(r31) addi r5, r1, 0x108 addi r3, r31, 0x4A4 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x4A0(r31) lwz r0, -0x2F0(r13) stw r0, 0x308(r1) lwz r0, 0x308(r1) stw r0, 0x108(r1) bl -0xF44E0 stw r30, 0x4AC(r31) addi r5, r1, 0x104 addi r3, r31, 0x4B4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4B0(r31) lwz r0, -0x2EC(r13) stw r0, 0x310(r1) lwz r0, 0x310(r1) stw r0, 0x104(r1) bl -0xF450C stw r30, 0x4BC(r31) addi r5, r1, 0x100 addi r3, r31, 0x4C4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4C0(r31) lwz r0, -0x2E8(r13) stw r0, 0x318(r1) lwz r0, 0x318(r1) stw r0, 0x100(r1) bl -0xF4538 stw r30, 0x4CC(r31) addi r5, r1, 0xFC addi r3, r31, 0x4D4 lfs f0, -0x56F8(r2) addi r4, r31, 0x200 stfs f0, 0x4D0(r31) lwz r0, -0x2E4(r13) stw r0, 0x320(r1) lwz r0, 0x320(r1) stw r0, 0xFC(r1) bl -0xF4564 stw r30, 0x4DC(r31) addi r5, r1, 0xF8 addi r3, r31, 0x4E4 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x4E0(r31) lwz r0, -0x2E0(r13) stw r0, 0x328(r1) lwz r0, 0x328(r1) stw r0, 0xF8(r1) bl -0xF4590 stw r30, 0x4EC(r31) addi r5, r1, 0xF4 addi r3, r31, 0x4F4 lfs f0, -0x56F4(r2) addi r4, r31, 0x200 stfs f0, 0x4F0(r31) lwz r0, -0x2DC(r13) stw r0, 0x330(r1) lwz r0, 0x330(r1) stw r0, 0xF4(r1) bl -0xF45BC lis r3, 0x802A addi r29, r3, 0x60C4 stw r29, 0x4FC(r31) li r30, 0x1 addi r5, r1, 0xF0 stw r30, 0x500(r31) addi r3, r31, 0x504 addi r4, r31, 0x200 lwz r0, -0x2D8(r13) stw r0, 0x338(r1) lwz r0, 0x338(r1) stw r0, 0xF0(r1) bl -0xF45F0 stw r29, 0x50C(r31) li r28, 0x2 addi r5, r1, 0xEC stw r28, 0x510(r31) addi r3, r31, 0x514 addi r4, r31, 0x200 lwz r0, -0x2D4(r13) stw r0, 0x340(r1) lwz r0, 0x340(r1) stw r0, 0xEC(r1) bl -0xF461C stw r29, 0x51C(r31) addi r5, r1, 0xE8 addi r3, r31, 0x524 stw r28, 0x520(r31) addi r4, r31, 0x200 lwz r0, -0x2D0(r13) stw r0, 0x348(r1) lwz r0, 0x348(r1) stw r0, 0xE8(r1) bl -0xF4644 stw r29, 0x52C(r31) li r0, 0x4 addi r5, r1, 0xE4 stw r0, 0x530(r31) addi r3, r31, 0x534 addi r4, r31, 0x200 lwz r0, -0x2CC(r13) stw r0, 0x350(r1) lwz r0, 0x350(r1) stw r0, 0xE4(r1) bl -0xF4670 stw r29, 0x53C(r31) addi r5, r1, 0xE0 addi r3, r31, 0x544 stw r30, 0x540(r31) addi r4, r31, 0x200 lwz r0, -0x2C8(r13) stw r0, 0x358(r1) lwz r0, 0x358(r1) stw r0, 0xE0(r1) bl -0xF4698 stw r29, 0x54C(r31) mr r3, r31 stw r30, 0x550(r31) lfs f1, -0x5718(r2) stfs f1, 0x10(r31) lfs f0, -0x5730(r2) stfs f0, 0x30(r31) stfs f1, 0x40(r31) lwz r0, 0x374(r1) lwz r31, 0x36C(r1) lwz r30, 0x368(r1) lwz r29, 0x364(r1) lwz r28, 0x360(r1) addi r1, r1, 0x370 mtlr r0 blr */ } /* * --INFO-- * Address: 8015315C * Size: 000140 */ Spider::Spider(CreatureProp*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 stw r30, 0x18(r1) stw r29, 0x14(r1) bl -0x5300 lis r3, 0x802D subi r0, r3, 0xD80 stw r0, 0x0(r31) addi r3, r31, 0x3CC bl -0xE9C5C li r3, 0x14 bl -0x10C190 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x50 li r4, 0x18 bl -0xCA578 .loc_0x50: stw r30, 0x220(r31) li r3, 0xC bl -0x10C1B0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x70 mr r4, r31 bl 0x678 .loc_0x70: stw r30, 0x3C0(r31) li r3, 0x68C bl -0x10C1D0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x90 mr r4, r31 bl 0x3908 .loc_0x90: stw r30, 0x3C4(r31) li r30, 0 subi r0, r13, 0x2C4 stw r30, 0x3DC(r31) addi r3, r31, 0x3CC stw r30, 0x3D8(r31) stw r30, 0x3D4(r31) stw r0, 0x3D0(r31) bl -0xE9BA8 li r3, 0x24 bl -0x10C210 mr. r29, r3 beq- .loc_0x11C lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x0(r29) addi r0, r3, 0x737C stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 stw r30, 0x10(r29) stw r30, 0xC(r29) stw r30, 0x8(r29) bl -0x12E378 lis r3, 0x8023 subi r0, r3, 0x71E0 stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 bl -0x112B28 lis r3, 0x802D subi r0, r3, 0xE2C stw r0, 0x0(r29) stw r31, 0x20(r29) .loc_0x11C: stw r29, 0x760(r31) mr r3, r31 lwz r0, 0x24(r1) lwz r31, 0x1C(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: 8015329C * Size: 000008 */ void Spider::getiMass() { /* .loc_0x0: lfs f1, -0x5770(r2) blr */ } /* * --INFO-- * Address: 801532A4 * Size: 0000C4 */ void Spider::init(Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0x1 stwu r1, -0x18(r1) stw r31, 0x14(r1) li r31, 0 stw r30, 0x10(r1) addi r30, r3, 0 addi r4, r30, 0 lfs f0, -0x56F0(r2) stfs f0, 0x270(r3) stb r0, 0x2BC(r3) stb r31, 0x2BB(r3) stb r31, 0x3B8(r3) stb r0, 0x3B9(r3) stb r31, 0x3BA(r3) stb r0, 0x3BB(r3) stw r31, 0x3BC(r3) lwz r3, 0x3C0(r3) bl 0x570 lwz r3, 0x3C4(r30) mr r4, r30 bl 0x399C stb r31, 0x3C9(r30) lis r31, 0x6C65 addi r4, r31, 0x6731 lfs f0, -0x56EC(r2) li r5, 0x3 stfs f0, 0x5AC(r30) lwz r3, 0x220(r30) bl -0xC9714 lwz r3, 0x220(r30) addi r4, r31, 0x6732 li r5, 0x3 bl -0xC9724 lwz r3, 0x220(r30) addi r4, r31, 0x6733 li r5, 0x3 bl -0xC9734 lwz r3, 0x220(r30) addi r4, r31, 0x6734 li r5, 0x3 bl -0xC9744 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153368 * Size: 000058 */ void Spider::doKill() { /* .loc_0x0: mflr r0 li r4, 0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r3, 0 stb r0, 0x3B8(r3) stb r0, 0x2B8(r3) stb r0, 0x2B9(r3) lwz r3, 0x3C4(r3) bl 0x3444 addi r3, r31, 0x3CC bl -0x112D8C lwz r3, 0x3168(r13) mr r4, r31 bl -0x1210 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 801533C0 * Size: 000028 */ void Spider::exitCourse() { /* .loc_0x0: mflr r0 li r4, 0x1 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C4(r3) bl 0x3404 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 801533E8 * Size: 00006C */ void Spider::update() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 lwz r12, 0x0(r31) lwz r12, 0x104(r12) mtlr r12 blrl lwz r3, 0x3C4(r31) bl 0x635C mr r3, r31 bl -0xC641C lwz r4, 0x2DEC(r13) mr r3, r31 lfs f1, 0x28C(r4) bl -0xC4E4C mr r3, r31 lwz r12, 0x0(r31) lwz r12, 0x108(r12) mtlr r12 blrl lwz r0, 0x24(r1) lwz r31, 0x1C(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000100 */ void Spider::draw(Graphics&) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80153454 * Size: 00014C */ void Spider::refresh(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x60(r1) stfd f31, 0x58(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x50(r1) stw r31, 0x4C(r1) addi r31, r4, 0 mr r4, r0 stw r30, 0x48(r1) addi r30, r3, 0 lwz r5, 0x2F00(r13) lfs f0, 0x9C(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r30) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r30) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C3AC lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x1458AC lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB0 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB0: lfs f1, -0x56E8(r2) mr r5, r31 lwz r3, 0x3C4(r30) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r30) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r30) stfs f2, 0x74C(r30) stfs f1, 0x750(r30) lwz r4, 0x3C4(r30) lfs f2, -0x575C(r2) lfs f1, 0x98(r30) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r30) stfs f1, 0x758(r30) lfs f0, 0x26C(r4) stfs f0, 0x75C(r30) lwz r3, 0x3C4(r30) lwz r4, 0x390(r30) bl 0x64EC lwz r3, 0x220(r30) addi r4, r31, 0 li r5, 0 bl -0xC9A90 lwz r0, 0x64(r1) lfd f31, 0x58(r1) lfd f30, 0x50(r1) lwz r31, 0x4C(r1) lwz r30, 0x48(r1) addi r1, r1, 0x60 mtlr r0 blr */ } /* * --INFO-- * Address: 801535A0 * Size: 000078 */ void Spider::drawShape(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) mr r31, r4 stw r30, 0x10(r1) mr r30, r3 lwz r3, 0x390(r3) lwz r3, 0x0(r3) bl -0x11DFD0 lwz r12, 0x3B4(r31) lis r4, 0x803A mr r3, r31 lwz r12, 0x74(r12) subi r4, r4, 0x77C0 li r5, 0 mtlr r12 blrl lwz r3, 0x390(r30) mr r4, r31 lwz r5, 0x2E4(r31) li r6, 0 lwz r3, 0x0(r3) bl -0x123190 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153618 * Size: 000024 */ void Spider::doAI() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C0(r3) bl 0x9E8 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8015363C * Size: 000044 */ void Spider::doAnimation() { /* .loc_0x0: mflr r0 mr r4, r3 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r0, 0x390(r3) cmplwi r0, 0 beq- .loc_0x34 lwz r12, 0x36C(r4) addi r3, r4, 0x33C lfs f1, 0x2D8(r4) lwz r12, 0xC(r12) mtlr r12 blrl .loc_0x34: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80153680 * Size: 000160 */ void SpiderDrawer::draw(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x68(r1) stfd f31, 0x60(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x58(r1) stw r31, 0x54(r1) stw r30, 0x50(r1) addi r30, r4, 0 mr r4, r0 stw r29, 0x4C(r1) mr r29, r3 lwz r5, 0x2F00(r13) lwz r31, 0x20(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f0, 0x9C(r31) lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r31) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r31) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C5E0 lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x145AE0 lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB8 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB8: lfs f1, -0x56E8(r2) mr r5, r30 lwz r3, 0x3C4(r31) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r31) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r31) stfs f2, 0x74C(r31) stfs f1, 0x750(r31) lwz r4, 0x3C4(r31) lfs f2, -0x575C(r2) lfs f1, 0x98(r31) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r31) stfs f1, 0x758(r31) lfs f0, 0x26C(r4) stfs f0, 0x75C(r31) lwz r3, 0x3C4(r31) lwz r4, 0x390(r31) bl 0x62B8 lwz r3, 0x20(r29) mr r4, r30 lwz r12, 0x0(r3) lwz r12, 0x120(r12) mtlr r12 blrl lwz r0, 0x6C(r1) lfd f31, 0x60(r1) lfd f30, 0x58(r1) lwz r31, 0x54(r1) lwz r30, 0x50(r1) lwz r29, 0x4C(r1) addi r1, r1, 0x68 mtlr r0 blr */ } /* * --INFO-- * Address: 801537E0 * Size: 000008 */ void Spider::isBossBgm() { /* .loc_0x0: lbz r3, 0x3B8(r3) blr */ } /* * --INFO-- * Address: 801537E8 * Size: 000050 */ void SpiderProp::read(RandomAccessStream&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r4, 0 stw r30, 0x10(r1) addi r30, r3, 0 bl -0xF4C6C addi r3, r30, 0x58 addi r4, r31, 0 bl -0xF4C78 addi r3, r30, 0x200 addi r4, r31, 0 bl -0xF4C84 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153838 * Size: 000008 */ void SpiderProp::@492 @read(RandomAccessStream&) { /* .loc_0x0: subi r3, r3, 0x1EC b -0x54 */ }
22.987626
48
0.459409
doldecomp
132ca133b0ff4c2658fd9fe83df277add8dd6e64
643
hpp
C++
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
meraz/doremi
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:05.000Z
2020-03-23T15:42:05.000Z
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
#pragma once #include <string> #include <DirectXMath.h> namespace DoremiEngine { namespace Graphic { class Camera; /** Builds new cameras and pushes cameras to the GPU */ class CameraManager { public: /** Creates a new Camera from the given projection matrix. */ virtual Camera* BuildNewCamera(DirectX::XMFLOAT4X4& p_projectionMatrix) = 0; /** Sends the matrices in the given camera class to the GPU */ virtual void PushCameraToDevice(const Camera& p_camera) = 0; }; } }
24.730769
88
0.553655
meraz
133148d1843538d811af1bca551d3c5e8334af9a
37
cpp
C++
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "jln/mp/list/take_back.hpp"
18.5
36
0.756757
jonathanpoelen
1333f5dbe3611b240f862f1623adfd9346383c98
11,112
cpp
C++
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
18
2017-04-26T13:53:43.000Z
2021-05-29T03:55:27.000Z
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
null
null
null
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
2
2017-10-17T10:32:01.000Z
2019-11-11T07:23:54.000Z
/* * SpaceShipGrammar.cpp * * Created on: Nov 2, 2015 * Author: Karl Haubenwallner */ #include <iostream> #include "operators/Generator.impl" #include "operators/ScopeOperators.impl" #include "operators/Resize.impl" #include "operators/Repeat.impl" #include "operators/Subdivide.impl" #include "operators/ComponentSplit.impl" #include "operators/Extrude.impl" #include "operators/RandomPath.impl" #include "operators/Duplicate.impl" #include "parameters/StaticParameter.h" #include "parameters/StaticRandom.h" #include "parameters/ParameterConversion.h" #include "parameters/Random.h" #include "parameters/ShapeParameter.h" #include "parameters/ScopeParameter.h" #include "parameters/ParameterOperations.h" #include "modifiers/DirectCall.h" #include "modifiers/RandomReseed.h" #include "modifiers/Discard.h" #include "modifiers/ScopeModifier.h" #include "CPU/StaticCall.h" #include "GeometryGeneratorInstanced.h" #include "SpaceShipGrammar.h" using namespace PGG; using namespace Shapes; using namespace Parameters; using namespace Scope; using namespace Operators; using namespace Modifiers; using namespace CPU; namespace PGA { namespace SpaceShip { void SpaceShipGrammar::initSymbols(SymbolManager& sm) { // start symbol, has no shape S = sm.createStart("S"); // Body element B = sm.createTerminal("B"); sm.addParameter<math::float3>(B, "size", math::float3(0.6f, 0.6f, 0.6f), math::float3(1.5f, 1.5f, 1.5f)); // Top (pyramid) element on top of body T_start = sm.createTerminal("T"); sm.addParameter<math::float3>(T_start, "size", math::float3(0.3f, 0.1f, 0.3f), math::float3(0.8f, 0.2f, 0.8f)); // Top (pyramid) element on top of body T_recursion = sm.createTerminal("t"); sm.addParameter<math::float3>(T_recursion, "size", math::float3(0.6f, 0.8f, 0.6f), math::float3(1.1f, 1.1f, 1.1f)); // Wing element W_start = sm.createTerminal("W"); sm.addParameter<math::float3>(W_start, "size", math::float3(0.3f, 0.2f, 0.2f), math::float3(1.2f, 0.5f, 1.0f)); sm.addParameter<float>(W_start, "forward/backward movement", -0.5f, 0.5f); W_recursion = sm.createTerminal("w"); sm.addParameter<math::float3>(W_recursion, "size", math::float3(0.6f, 0.9f, 0.7f), math::float3(1.2f, 1.0f, 1.2f)); sm.addParameter<float>(W_recursion, "forward/backward movement", -0.5f, 0.5f); sm.addPossibleChild(S, B, 1, 1.0f); sm.addPossibleChild(B, B, 1, 1.0f/3.0f); sm.addPossibleChild(B, W_start, 1, 1.0f/3.0f); sm.addPossibleChild(B, T_start, 1, 1.0f/3.0f); sm.addPossibleChild(W_start, W_recursion, 1, 1.0f); sm.addPossibleChild(W_recursion, W_recursion, 1, 0.9f); sm.addPossibleChild(T_start, T_recursion, 1, 1.0f); sm.addPossibleChild(T_recursion, T_recursion, 1, 1.0f); if (getNumPreparedShapes() != 1) { throw std::invalid_argument("Wrong number of shapes for the Grammar"); } } int SpaceShipGrammar::storeParameter(Symbol* symbol, PGG::Parameters::ParameterTable& pt) { if (symbol->id() == S) return -1; if (symbol->id() == B) { return storeBodyParameter(symbol, pt); } if (symbol->id() == T_start || symbol->id() == T_recursion) { return storeTopParameter(symbol, pt); } if (symbol->id() == W_start || symbol->id() == W_recursion) { return storeWingParameter(symbol, pt); } //std::cout << "no Parameters for Symbol id " << symbol->id() << std::endl; return -1; } int SpaceShipGrammar::storeBodyParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int body_child = 0; int body_child_offset = 0; int top_child = 0; int top_child_offset = 0; int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == B) { body_child = 1; body_child_offset = c->getParamTableOffset(); continue; } if (c->id() == T_start) { top_child = 1; top_child_offset = c->getParamTableOffset(); continue; } if (c->id() == W_start) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); continue; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of body part body_child, // attach another body part body_child_offset, // Param Layer of new body part top_child, // attach a top part top_child_offset, // Param Layer of top part wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeTopParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int top_child = 0; int top_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == T_recursion) { top_child = 1; top_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of top part top_child, // attach a top part top_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeWingParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == W_recursion) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); float movement = s->getParameter()[1]->getValue<float>(); int pt_offset = pt.storeParameters( size, // size of wing part movement, // movement of wing wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } void SpaceShipGrammar::createAxiom(PGG::CPU::GrammarSystem& system, const int axiomId) { //forward declaratons for recursion class BodyRuleRecusion; class TopRule; class TopRuleRecursion; class WingRule; class WingRuleRecursion; class BodyRule; typedef CoordinateframeScope<int> SpaceShipscope; typedef PGA::InstancedShapeGenerator<SpaceShipscope, 0, true> SpaceShipGenerator; typedef Operators::Generator<SpaceShipGenerator> MyGenerate; static const int ParamLayer = 0; // offset 0: float3 size class SpaceShip : public Resize<DynamicFloat3<0, ParamLayer>, DirectCall<BodyRule> > { }; // offset 3: int 1/0 to enable next body part // offset 4: int to change paramtable for next body part // offset 5: int 1/0 to enable top part // offset 6: int to change paramtable for top part // offset 7: int 1/0 to build wings // offset 8: int to change paramtable for wings (equal for both) class BodyRule : public Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, //0 is starting point, so move the box half the size to the front StaticCall < Duplicate < DirectCall<MyGenerate>, // body part is being generated DirectCall < ChoosePath < DynamicInt<3, ParamLayer>, // extend body part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, StaticCall<BodyRuleRecusion> > > > > // next body part >, DirectCall< ChoosePath < DynamicInt<5, ParamLayer>, // build top part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p>>, SetScopeAttachment<ParamLayer, DynamicInt<6, ParamLayer>, StaticCall<TopRule> > > > > // start top >, DirectCall< ChoosePath < DynamicInt<7, ParamLayer>, //generate wings SetScopeAttachment<ParamLayer, DynamicInt<8, ParamLayer>, DirectCall< Duplicate < // mirror DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > >, // wing right DirectCall<Rotate<StaticAxes<Axes::ZAxis>, StaticFloat<3.14159265359_p>, DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > > > > >// wing left > > > > > > > { }; // offset 0: float3 size class BodyRuleRecusion : public Resize<DynamicFloat3<0, ParamLayer>, //adjust body part size DirectCall<BodyRule> // execute the recursion > { }; // offset 0: float3 size class TopRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial top scale DirectCall<TopRuleRecursion > > {}; // offset 3: int 1/0 to enable next top part // offset 4: int to change paramtable for next top part class TopRuleRecursion : public Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // top part is being generated DirectCall<ChoosePath< DynamicInt<3, ParamLayer>, DirectCall< Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<TopRuleRecursion> > > > > > > > > > {}; // offset 0: float3 size // offset 3: float forward backward move class WingRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial wing scale DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, DirectCall<WingRuleRecursion > > > > {}; // offset 4: int 1/0 to enable next wing part // offset 5: int to change paramtable for next top part class WingRuleRecursion : public Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // wing part is being generated DirectCall<ChoosePath< DynamicInt<4, ParamLayer>, DirectCall< Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<5, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, // backward and forward move DirectCall<WingRuleRecursion> > > > > > > > > > > > {}; ScopedShape<Box, SpaceShipscope > spaceShipAxiom(Box(math::float3(1.0f)), SpaceShipscope(math::identity<math::float3x4>(), axiomId)); system.addAxiom<SpaceShip>(spaceShipAxiom); } }; // namespace SpaceShip }; // namespace PGA
32.491228
255
0.687635
crest01
1334b74368c4ff41bcb7911601ff771fd6f913bc
1,030
cpp
C++
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> #include <unordered_map> using namespace std; // https://leetcode.com/problems/repeated-dna-sequences/discuss/420527/Easy-Hashmap-bit-manipulation-solution-C%2B%2B class Solution { public: int char_to_bit(char c){ if(c=='A') return 0; if(c=='C') return 1; if(c=='G') return 2; if(c=='T') return 3; return 0; } vector<string> findRepeatedDnaSequences(string s) { int n= s.size(), mask=0, bitmask=(1<<20)-1; if(n==0) return {}; unordered_map<int, int> ht; vector<string> result; for(int i=0; i<10; i++){ mask= (mask<<2) | char_to_bit(s[i]); } ht[mask]++; for(int i=10; i<n; i++){ mask= ((mask<<2) & bitmask) | char_to_bit(s[i]); if(ht.find(mask)!=ht.end() && ht[mask]==1) result.push_back(s.substr(i-9, 10)); ht[mask]++; } return result; } };
25.75
117
0.500971
sky-bro
1336f604e5d0695b03d02286099e03b4501adf02
4,924
cpp
C++
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. // This cpp contains implemenations of to_string and from_string for intrinsic // types as well as ouro types. #include <oHLSL/oHLSLMath.h> #include <oString/stringize.h> namespace ouro { bool from_string(float2* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 2, src); } bool from_string(float3* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 3, src); } bool from_string(float4* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 4, src); } bool from_string(float4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_float_array((float*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } bool from_string(double4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_double_array((double*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } #define CHK_MV() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_SIGNED); \ if (!*src) return false; \ } while (false) #define CHK_MV_U() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_UNSIGNED); \ if (!*src) return false; \ } while (false) bool from_string(int2* _pValue, const char* src) { CHK_MV(); return 2 == sscanf_s(src, "%d %d", &_pValue->x, &_pValue->y); } bool from_string(int3* _pValue, const char* src) { CHK_MV(); return 3 == sscanf_s(src, "%d %d %d", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(int4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%d %d %d %d", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } bool from_string(uint2* _pValue, const char* src) { CHK_MV_U(); return 2 == sscanf_s(src, "%u %u", &_pValue->x, &_pValue->y); } bool from_string(uint3* _pValue, const char* src) { CHK_MV_U(); return 3 == sscanf_s(src, "%u %u %u", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(uint4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%u %u %u %u", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } char* to_string(char* dst, size_t dst_size, const float2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int2& value) { return -1 != snprintf(dst, dst_size, "%d %d", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int3& value) { return -1 != snprintf(dst, dst_size, "%d %d %d", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int4& value) { return -1 != snprintf(dst, dst_size, "%d %d %d %d", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint2& value) { return -1 != snprintf(dst, dst_size, "%u %u", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint3& value) { return -1 != snprintf(dst, dst_size, "%u %u %u", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint4& value) { return -1 != snprintf(dst, dst_size, "%u %u %u %u", value.x, value.y, value.z, value.w) ? dst : nullptr; } template<typename T> char* to_stringT(char* dst, size_t dst_size, const TMAT4<T>& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f" , value.Column0.x, value.Column1.x, value.Column2.x, value.Column3.x , value.Column0.y, value.Column1.y, value.Column2.y, value.Column3.y , value.Column0.z, value.Column1.z, value.Column2.z, value.Column3.z , value.Column0.w, value.Column1.w, value.Column2.w, value.Column3.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4x4& value) { return to_stringT(dst, dst_size, value); } char* to_string(char* dst, size_t dst_size, const double4x4& value) { return to_stringT(dst, dst_size, value); } }
55.325843
175
0.662063
jiangzhu1212
133cc7ead15c4c65ed0d5419ab92574e9557397e
380
hpp
C++
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
#ifndef QUICKSORT_HPP #define QUICKSORT_HPP #include "partition.hpp" template <typename T> void quicksort(T a[], int l, int r, int (*piv)(T a[], int l, int r, bool (*cmp)(T& a, T& b)), bool (*cmp)(T& a, T& b)) { if (r > l) { int pivot = piv(a, l, r, cmp); quicksort(a, l, pivot - 1, piv, cmp); quicksort(a, pivot + 1, r, piv, cmp); } } #endif
23.75
118
0.544737
bottomupmergesort
133eecface7ed1e8e7019196ef11e127d73645d8
1,375
cpp
C++
test/optional/from.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
test/optional/from.cpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
test/optional/from.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/make_ref.hpp> #include <fcppt/catch/begin.hpp> #include <fcppt/catch/end.hpp> #include <fcppt/catch/movable.hpp> #include <fcppt/optional/from.hpp> #include <fcppt/optional/make.hpp> #include <fcppt/optional/object_impl.hpp> #include <fcppt/optional/reference.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> FCPPT_CATCH_BEGIN TEST_CASE("optional::from", "[optiona]") { using optional_int = fcppt::optional::object<int>; using optional_int_ref = fcppt::optional::reference<int>; CHECK(fcppt::optional::from(optional_int(), [] { return 42; }) == 42); CHECK(fcppt::optional::from(optional_int(100), [] { return 42; }) == 100); int x{42}; int y{0}; fcppt::optional::from(optional_int_ref{fcppt::make_ref(x)}, [&y]() { return fcppt::make_ref(y); }).get() = 100; CHECK(x == 100); } TEST_CASE("optional::from move", "[optiona;]") { using int_movable = fcppt::catch_::movable<int>; CHECK(fcppt::optional::from(fcppt::optional::make(int_movable{42}), [] { return int_movable{10}; }) == int_movable{42}); } FCPPT_CATCH_END
26.960784
76
0.683636
freundlich
133fb8e1dc755a01fec4f49a740f8b825244e846
454
cpp
C++
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
null
null
null
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
null
null
null
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
1
2019-11-29T09:38:17.000Z
2019-11-29T09:38:17.000Z
#include "CipherFactory.hpp" std::unique_ptr<Cipher> cipherFactory( const CipherType type, const std::string key){ switch(type){ case CipherType::Caesar: return std::make_unique<CaesarCipher>(key); case CipherType::Playfair: return std::make_unique<PlayfairCipher>(key); case CipherType::Vigenere: return std::make_unique<VigenereCipher>(key); default: throw; } }
28.375
85
0.629956
MPAGS-CPP-2019
134119285d8744b3f9fc8ee9ccb4b6c5de2b641f
2,525
cpp
C++
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
// Includes #include <math.h> #include <ctime> // #include "Primitives.h" #include "CompositeModels.h" //// // Forward declarations void Update(void); void Render(void); void InitializeModels(void); void CalculateDeltaSeconds(void); //// // Global variables time_t g_lastFrameTime; float g_deltaSeconds = 0.01f; const float SWITCH_TIME = 4.0f; float g_switchTimer = 0.0f; float g_rotationAngle = 0.0f; int g_modelToShow = 0; std::vector<SceneNode*> g_models; //// int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(700, 700); glutInitWindowPosition(100, 100); glutCreateWindow("My First Application"); glClearColor(0.0, 0.0, 0.0, 0.0); InitializeModels(); time(&g_lastFrameTime); glutDisplayFunc(Render); glutIdleFunc(Update); glutMainLoop(); return 0; } void Update(void) { // DeltaSeconds CalculateDeltaSeconds(); // Functionality if (g_modelToShow == 2) { g_rotationAngle += 0.001f; } else { g_rotationAngle += 0.0001f; } g_switchTimer += g_deltaSeconds; if (g_switchTimer > SWITCH_TIME) { g_switchTimer = 0.0f; g_modelToShow++; if (g_modelToShow >= g_models.size()) { g_modelToShow = 0; } } // Render glutPostRedisplay(); } void Render(void) { glClear(GL_COLOR_BUFFER_BIT); //Ready to Draw glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (g_models.size() > 0) { // Rotate glm::mat4 rot = glm::rotate(glm::mat4(1.0), g_rotationAngle, glm::vec3(1, 1, 1)); g_models[g_modelToShow]->SetTransform(rot); g_models[g_modelToShow]->Render(); } glFlush(); } void InitializeModels(void) { Cube* cube = new Cube(glm::mat4(1.0f), 1.0f); cube->SetColor(1.0f, 0.0f, 0.0f); cube->SetScale(1, 1, 1); g_models.push_back(cube); Cone* cone = new Cone(glm::mat4(1.0f), 1.0f); cone->SetColor(1.0f, 0.0f, 0.0f); cone->SetScale(1, 1, 1); g_models.push_back(cone); Sphere* sphere = new Sphere(glm::mat4(1.0f), 1.0f); sphere->SetColor(1.0f, 0.0f, 0.0f); sphere->SetScale(1, 1, 1); g_models.push_back(sphere); Cylinder* cylinder = new Cylinder(glm::mat4(1.0f), 1.0f); cylinder->SetColor(1.0f, 0.0f, 0.0f); cylinder->SetScale(1, 1, 1); g_models.push_back(cylinder); StairCase* staircase = new StairCase(glm::mat4(1.0f), 1.0f); staircase->SetColor(1.0f, 0.0f, 0.0f); staircase->SetScale(1, 1, 1); g_models.push_back(staircase); } void CalculateDeltaSeconds(void) { time_t timer; time(&timer); g_deltaSeconds = difftime(timer, g_lastFrameTime); g_lastFrameTime = timer; }
19.128788
83
0.690693
CarloAlbino
134d2b9693ec58d51aa48cc110876430e7cda0f0
446
cpp
C++
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
2
2018-04-30T06:25:37.000Z
2018-05-12T20:29:10.000Z
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
null
null
null
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "GridRow.h" #include "NativeGridRow.h" namespace Ntreev { namespace Windows { namespace Forms { namespace Grid { GridRow::GridRow(Native::GrGridRow* pGridRow) : m_pGridRow(pGridRow), RowBase(pGridRow) { } _GridControl^ GridRow::ChildGrid::get() { return m_pGridRow->GetChildGrid(); } } /*namespace Grid*/ } /*namespace Forms*/ } /*namespace Windows*/ } /*namespace Ntreev*/
24.777778
89
0.661435
NtreevSoft
134f667091dd80fc625fcf4521b880bb8c4cd13b
9,169
cpp
C++
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
#include <eeros/hal/HAL.hpp> #include <eeros/core/Fault.hpp> #include <dlfcn.h> #include <getopt.h> using namespace eeros; using namespace eeros::hal; HAL::HAL() : log('H') { } HAL::HAL(const HAL&) : log('H') { } HAL& HAL::operator=(const HAL&) { } HAL& HAL::instance() { static HAL halInstance; return halInstance; } bool HAL::readConfigFromFile(std::string file) { parser = JsonParser(file); parser.createHalObjects(hwLibraries); return true; } bool HAL::readConfigFromFile(int* argc, char** argv) { // available long_options static struct option long_options_hal[] = { {"config", required_argument, NULL, 'c'}, {"configFile", required_argument, NULL, 'f'}, {NULL, 0, NULL, 0 } }; // Error message if long dashes (en dash) are used int i; for (i=0; i < *argc; i++) { if ((argv[i][0] == 226) && (argv[i][1] == 128) && (argv[i][2] == 147)) { fprintf(stderr, "Error: Invalid arguments. En dashes are used.\n"); return -1; } } /* Compute command line arguments */ int c; std::string configPath; while ((c = getopt_long(*argc, argv, "c:f:", long_options_hal, NULL)) != -1) { switch(c) { case 'c': // config found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case 'f': // configFile found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case '?': if(optopt == 'c') log.trace() << "Option -" << optopt << " requires an argument."; else if(isprint(optopt)) log.trace() << "Unknown option `-" << optopt <<"'."; else log.trace() << "Unknown option character `\\x" << optopt << "'."; break; default: // ignore all other args break; } } parser = JsonParser(configPath); parser.createHalObjects(hwLibraries); return true; } bool HAL::loadModule(std::string moduleName) { // TODO return false; } bool HAL::addInput(InputInterface* systemInput) { if(systemInput != nullptr) { if( inputs.find(systemInput->getId()) != inputs.end() ){ throw Fault("Could not add Input to HAL, signal id '" + systemInput->getId() + "' already exists!"); } inputs.insert(std::pair<std::string, InputInterface*>(systemInput->getId(), systemInput)); return true; } throw Fault("System input is null"); } bool HAL::addOutput(OutputInterface* systemOutput) { if(systemOutput != nullptr) { if( outputs.find(systemOutput->getId()) != outputs.end() ){ throw Fault("Could not add Output to HAL, signal id '" + systemOutput->getId() + "' already exists!"); } outputs.insert(std::pair<std::string, OutputInterface*>(systemOutput->getId(), systemOutput)); return true; } throw Fault("System output is null"); } void HAL::releaseInput(std::string name) { bool found = false; auto inIt = nonExclusiveInputs.find(inputs[name]); if(inIt != nonExclusiveInputs.end()){ nonExclusiveInputs.erase(inIt); found = true; } inIt = exclusiveReservedInputs.find(inputs[name]); if(inIt != exclusiveReservedInputs.end()){ exclusiveReservedInputs.erase(inIt); found = true; } if(!found){ throw Fault("Could not release system input '" + name + "', id not found."); } } void HAL::releaseOutput(std::string name) { bool found = false; auto outIt = nonExclusiveOutputs.find(outputs[name]); if(outIt != nonExclusiveOutputs.end()){ nonExclusiveOutputs.erase(outIt); found = true; } outIt = exclusiveReservedOutputs.find(outputs[name]); if(outIt != exclusiveReservedOutputs.end()){ exclusiveReservedOutputs.erase(outIt); found = true; } if(!found){ throw Fault("Could not release system output '" + name + "', id not found."); } } OutputInterface* HAL::getOutput(std::string name, bool exclusive) { if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("System output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("System output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("System output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return outputs[name]; } Output<bool>* HAL::getLogicOutput(std::string name, bool exclusive) { Output<bool>* out = dynamic_cast<Output<bool>*>(outputs[name]); if(out == nullptr) throw Fault("Logic system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Logic system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } ScalableOutput<double>* HAL::getScalableOutput(std::string name, bool exclusive) { ScalableOutput<double>* out = dynamic_cast<ScalableOutput<double>*>(outputs[name]); if(out == nullptr) throw Fault("Scalable system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Scalable system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } InputInterface* HAL::getInput(std::string name, bool exclusive) { if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("System input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("System input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("System input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return inputs[name]; } Input<bool>* HAL::getLogicInput(std::string name, bool exclusive) { Input<bool>* in = dynamic_cast<Input<bool>*>(inputs[name]); if(in == nullptr) throw Fault("Logic system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Logic system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } ScalableInput<double>* HAL::getScalableInput(std::string name, bool exclusive) { ScalableInput<double>* in = dynamic_cast<ScalableInput<double>*>(inputs[name]); if(in == nullptr) throw Fault("Scalable system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Scalable system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } void * HAL::getOutputFeature(std::string name, std::string featureName){ auto outObj = outputs[name]; return getOutputFeature(outObj, featureName); } void* HAL::getOutputFeature(OutputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); } void * HAL::getInputFeature(std::string name, std::string featureName){ auto inObj = inputs[name]; return getInputFeature(inObj, featureName); } void* HAL::getInputFeature(InputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); }
34.996183
202
0.688625
RicoPauli
1353697eb8a748bba9b039f92cf47a941ea7aedd
354
hpp
C++
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/BoundaryCondition.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/DirichletAnalytic.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Outflow.hpp"
39.333333
92
0.841808
macedo22
1357b814f8585a2bea089cef99b2afcb72ad9ed4
16,143
cpp
C++
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Peloton // // optimizer.cpp // // Identification: src/optimizer/optimizer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/manager.h" #include "optimizer/binding.h" #include "optimizer/child_property_generator.h" #include "optimizer/cost_and_stats_calculator.h" #include "optimizer/operator_to_plan_transformer.h" #include "optimizer/operator_visitor.h" #include "optimizer/optimizer.h" #include "optimizer/property_enforcer.h" #include "optimizer/query_property_extractor.h" #include "optimizer/query_to_operator_transformer.h" #include "optimizer/rule_impls.h" #include "parser/sql_statement.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" namespace peloton { namespace optimizer { //===--------------------------------------------------------------------===// // Optimizer //===--------------------------------------------------------------------===// Optimizer::Optimizer() { logical_transformation_rules_.emplace_back(new InnerJoinCommutativity()); physical_implementation_rules_.emplace_back(new GetToScan()); physical_implementation_rules_.emplace_back(new LogicalFilterToPhysical()); physical_implementation_rules_.emplace_back(new InnerJoinToInnerNLJoin()); physical_implementation_rules_.emplace_back(new LeftJoinToLeftNLJoin()); physical_implementation_rules_.emplace_back(new RightJoinToRightNLJoin()); physical_implementation_rules_.emplace_back(new OuterJoinToOuterNLJoin()); // rules.emplace_back(new InnerJoinToInnerHashJoin()); } std::shared_ptr<planner::AbstractPlan> Optimizer::BuildPelotonPlanTree( const std::unique_ptr<parser::SQLStatementList> &parse_tree_list) { // Base Case if (parse_tree_list->GetStatements().size() == 0) return nullptr; std::unique_ptr<planner::AbstractPlan> child_plan = nullptr; auto parse_tree = parse_tree_list->GetStatements().at(0); // Generate initial operator tree from query tree std::shared_ptr<GroupExpression> gexpr = InsertQueryTree(parse_tree); GroupID root_id = gexpr->GetGroupID(); // Get the physical properties the final plan must output PropertySet properties = GetQueryRequiredProperties(parse_tree); // Explore the logically equivalent plans from the root group ExploreGroup(root_id); // Implement all the physical operators ImplementGroup(root_id); // Find least cost plan for root group OptimizeGroup(root_id, properties); auto best_plan = ChooseBestPlan(root_id, properties); if (best_plan == nullptr) return nullptr; // return std::shared_ptr<planner::AbstractPlan>(best_plan.release()); return std::move(best_plan); } void Optimizer::Reset() { memo_ = std::move(Memo()); column_manager_ = std::move(ColumnManager()); } std::shared_ptr<GroupExpression> Optimizer::InsertQueryTree( parser::SQLStatement *tree) { QueryToOperatorTransformer converter(column_manager_); std::shared_ptr<OperatorExpression> initial = converter.ConvertToOpExpression(tree); std::shared_ptr<GroupExpression> gexpr; RecordTransformedExpression(initial, gexpr); return gexpr; } PropertySet Optimizer::GetQueryRequiredProperties(parser::SQLStatement *tree) { QueryPropertyExtractor converter(column_manager_); return std::move(converter.GetProperties(tree)); } std::unique_ptr<planner::AbstractPlan> Optimizer::OptimizerPlanToPlannerPlan( std::shared_ptr<OperatorExpression> plan, PropertySet &requirements, std::vector<PropertySet> &required_input_props) { OperatorToPlanTransformer transformer; return transformer.ConvertOpExpression(plan, &requirements, &required_input_props); } std::unique_ptr<planner::AbstractPlan> Optimizer::ChooseBestPlan( GroupID id, PropertySet requirements) { LOG_TRACE("Choosing best plan for group %d", id); Group *group = memo_.GetGroupByID(id); std::shared_ptr<GroupExpression> gexpr = group->GetBestExpression(requirements); LOG_TRACE("Choosing best plan for group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); std::vector<GroupID> child_groups = gexpr->GetChildGroupIDs(); std::vector<PropertySet> required_input_props = std::move(gexpr->GetInputProperties(requirements)); PL_ASSERT(required_input_props.size() == child_groups.size()); std::shared_ptr<OperatorExpression> op = std::make_shared<OperatorExpression>(gexpr->Op()); auto plan = OptimizerPlanToPlannerPlan(op, requirements, required_input_props); for (size_t i = 0; i < child_groups.size(); ++i) { auto child_plan = ChooseBestPlan(child_groups[i], required_input_props[i]); plan->AddChild(std::move(child_plan)); } return plan; } void Optimizer::OptimizeGroup(GroupID id, PropertySet requirements) { LOG_TRACE("Optimizing group %d", id); Group *group = memo_.GetGroupByID(id); // Whether required properties have already been optimized for the group if (group->GetBestExpression(requirements) != nullptr) return; const std::vector<std::shared_ptr<GroupExpression>> exprs = group->GetExpressions(); for (size_t i = 0; i < exprs.size(); ++i) { if (exprs[i]->Op().IsPhysical()) OptimizeExpression(exprs[i], requirements); } } void Optimizer::OptimizeExpression(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { LOG_TRACE("Optimizing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Only optimize and cost physical expression PL_ASSERT(gexpr->Op().IsPhysical()); std::vector<std::pair<PropertySet, std::vector<PropertySet>>> output_input_property_pairs = std::move(DeriveChildProperties(gexpr, requirements)); size_t num_property_pairs = output_input_property_pairs.size(); auto child_group_ids = gexpr->GetChildGroupIDs(); for (size_t pair_offset = 0; pair_offset < num_property_pairs; ++pair_offset) { auto output_properties = output_input_property_pairs[pair_offset].first; const auto &input_properties_list = output_input_property_pairs[pair_offset].second; std::vector<std::shared_ptr<Stats>> best_child_stats; std::vector<double> best_child_costs; for (size_t i = 0; i < child_group_ids.size(); ++i) { GroupID child_group_id = child_group_ids[i]; const PropertySet &input_properties = input_properties_list[i]; // Optimize child OptimizeGroup(child_group_id, input_properties); // Find best child expression std::shared_ptr<GroupExpression> best_expression = memo_.GetGroupByID(child_group_id) ->GetBestExpression(input_properties); // TODO(abpoms): we should allow for failure in the case where no // expression // can provide the required properties PL_ASSERT(best_expression != nullptr); best_child_stats.push_back(best_expression->GetStats(input_properties)); best_child_costs.push_back(best_expression->GetCost(input_properties)); } // Perform costing DeriveCostAndStats(gexpr, output_properties, input_properties_list, best_child_stats, best_child_costs); Group *group = this->memo_.GetGroupByID(gexpr->GetGroupID()); // Add to group as potential best cost group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); // enforce missing properties for (auto property : requirements.Properties()) { if (output_properties.HasProperty(*property) == false) { gexpr = EnforceProperty(gexpr, output_properties, property); group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); } } // After the enforcement it must have met the property requirements, so // notice here we set the best cost plan for 'requirements' instead of // 'output_properties' group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), requirements); } } std::shared_ptr<GroupExpression> Optimizer::EnforceProperty( std::shared_ptr<GroupExpression> gexpr, PropertySet &output_properties, const std::shared_ptr<Property> property) { // new child input is the old output auto child_input_properties = std::vector<PropertySet>(); child_input_properties.push_back(output_properties); auto child_stats = std::vector<std::shared_ptr<Stats>>(); child_stats.push_back(gexpr->GetStats(output_properties)); auto child_costs = std::vector<double>(); child_costs.push_back(gexpr->GetCost(output_properties)); PropertyEnforcer enforcer(column_manager_); auto enforced_expr = enforcer.EnforceProperty(gexpr, &output_properties, property); std::shared_ptr<GroupExpression> enforced_gexpr; RecordTransformedExpression(enforced_expr, enforced_gexpr, gexpr->GetGroupID()); // new output property would have the enforced Property output_properties.AddProperty(std::shared_ptr<Property>(property)); DeriveCostAndStats(enforced_gexpr, output_properties, child_input_properties, child_stats, child_costs); return enforced_gexpr; } std::vector<std::pair<PropertySet, std::vector<PropertySet>>> Optimizer::DeriveChildProperties(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { ChildPropertyGenerator converter(column_manager_); return std::move(converter.GetProperties(gexpr, requirements)); } void Optimizer::DeriveCostAndStats( std::shared_ptr<GroupExpression> gexpr, const PropertySet &output_properties, const std::vector<PropertySet> &input_properties_list, std::vector<std::shared_ptr<Stats>> child_stats, std::vector<double> child_costs) { CostAndStatsCalculator calculator(column_manager_); calculator.CalculateCostAndStats(gexpr, &output_properties, &input_properties_list, child_stats, child_costs); gexpr->SetLocalHashTable(output_properties, input_properties_list, calculator.GetOutputCost(), calculator.GetOutputStats()); } void Optimizer::ExploreGroup(GroupID id) { LOG_TRACE("Exploring group %d", id); if (memo_.GetGroupByID(id)->HasExplored()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { ExploreExpression(gexpr); } memo_.GetGroupByID(id)->SetExplorationFlag(); } void Optimizer::ExploreExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Exploring expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); PL_ASSERT(gexpr->Op().IsLogical()); // Explore logically equivalent plans by applying transformation rules for (const std::unique_ptr<Rule> &rule : logical_transformation_rules_) { // Apply all rules to operator which match. We apply all rules to one // operator before moving on to the next operator in the group because // then we avoid missing the application of a rule e.g. an application // of some rule creates a match for a previously applied rule, but it is // missed because the prev rule was already checked std::vector<std::shared_ptr<GroupExpression>> candidates = TransformExpression(gexpr, *(rule.get())); for (std::shared_ptr<GroupExpression> candidate : candidates) { // Explore the expression ExploreExpression(candidate); } } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasExplored()) ExploreGroup(child_id); } } void Optimizer::ImplementGroup(GroupID id) { LOG_TRACE("Implementing group %d", id); if (memo_.GetGroupByID(id)->HasImplemented()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { if (gexpr->Op().IsLogical()) ImplementExpression(gexpr); } memo_.GetGroupByID(id)->SetImplementationFlag(); } void Optimizer::ImplementExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Implementing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Explore implement physical expressions for (const std::unique_ptr<Rule> &rule : physical_implementation_rules_) { TransformExpression(gexpr, *(rule.get())); } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasImplemented()) ImplementGroup(child_id); } } ////////////////////////////////////////////////////////////////////////////// /// Rule application std::vector<std::shared_ptr<GroupExpression>> Optimizer::TransformExpression( std::shared_ptr<GroupExpression> gexpr, const Rule &rule) { std::shared_ptr<Pattern> pattern = rule.GetMatchPattern(); std::vector<std::shared_ptr<GroupExpression>> output_plans; ItemBindingIterator iterator(*this, gexpr, pattern); while (iterator.HasNext()) { std::shared_ptr<OperatorExpression> plan = iterator.Next(); // Check rule condition function if (rule.Check(plan)) { LOG_TRACE("Rule matched expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Apply rule transformations // We need to be able to analyze the transformations performed by this // rule in order to perform deduplication and launch an exploration of // the newly applied rule std::vector<std::shared_ptr<OperatorExpression>> transformed_plans; rule.Transform(plan, transformed_plans); // Integrate transformed plans back into groups and explore/cost if new for (std::shared_ptr<OperatorExpression> plan : transformed_plans) { LOG_TRACE("Trying to integrate expression with op %s", plan->Op().name().c_str()); std::shared_ptr<GroupExpression> new_gexpr; bool new_expression = RecordTransformedExpression(plan, new_gexpr, gexpr->GetGroupID()); if (new_expression) { LOG_TRACE("Expression with op %s was inserted into group %d", plan->Op().name().c_str(), new_gexpr->GetGroupID()); output_plans.push_back(new_gexpr); } } } } return output_plans; } ////////////////////////////////////////////////////////////////////////////// /// Memo insertion std::shared_ptr<GroupExpression> Optimizer::MakeGroupExpression( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups = MemoTransformedChildren(expr); return std::make_shared<GroupExpression>(expr->Op(), child_groups); } std::vector<GroupID> Optimizer::MemoTransformedChildren( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups; for (std::shared_ptr<OperatorExpression> child : expr->Children()) { child_groups.push_back(MemoTransformedExpression(child)); } return child_groups; } GroupID Optimizer::MemoTransformedExpression( std::shared_ptr<OperatorExpression> expr) { std::shared_ptr<GroupExpression> gexpr = MakeGroupExpression(expr); // Ignore whether this expression is new or not as we only care about that // at the top level (void)memo_.InsertExpression(gexpr); return gexpr->GetGroupID(); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr) { return RecordTransformedExpression(expr, gexpr, UNDEFINED_GROUP); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr, GroupID target_group) { gexpr = MakeGroupExpression(expr); return memo_.InsertExpression(gexpr, target_group); } } // namespace optimizer } // namespace peloton
38.253555
80
0.70018
rntlqvnf
1357d44339ada7f10cf9335bf6f5a498e47c6944
8,830
cpp
C++
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
#include "iobuffer.h" #include "symbols.h" #include "abstract-syntax-tree.h" using namespace std ; using namespace CS_IO_Buffers ; using namespace CS_Symbol_Tables ; using namespace Workshop_Compiler ; // ignore unused-function warnings in this source file #pragma clang diagnostic ignored "-Wunused-function" // keep global counters so we can create unique labels in while and if statements static int while_counter = 0 ; static int if_counter = 0 ; // we have a legal infix operator, translate into VM command equivalent static string translate_op(string op) { int oplen = op.length() ; if ( oplen == 1 ) { switch(op[0]) { case '+': return "add" ; case '-': return "sub" ; case '*': return "call Math.multiply 2" ; case '/': return "call Math.divide 2" ; case '<': return "lt" ; case '>': return "gt" ; default:; } } else if ( oplen == 2 && op[1] == '=' ) { switch(op[0]) { case '<': return "gt\nnot" ; case '>': return "lt\nnot" ; case '=': return "eq" ; case '!': return "eq\nnot" ; default:; } } fatal_error(-1,"translate_op passed unknown op: " + op + "\n") ; return op ; } // the grammar we are recognising // rules containing text literals are written using the matching tk_* or tg_* names // // TERM: DEFINITION // program: declarations statement tk_eoi // declarations: declaration* // declaration: tk_var tg_type tk_identifier tk_semi // statement: while | if | let | sequence // while: tk_while tk_lrb condition tk_rrb statement // if: tk_if tk_lrb condition tk_rrb statement (tk_else statement)? // let: tk_let tk_identifier tk_assign expression tk_semi // sequence: tk_lcb statement* tk_rcb // expression: term (tg_infix_op term)? // condition: term tg_relop term // term: tk_identifier | tk_integer // // Token groups for use with have()/have_next()/mustbe()/did_not_find(): // tg_statement - matches any token that can start a statement // tg_term - matches any token that can start a term // tg_infix_op - matches any token that can be used as an infix_op // tg_relop - matches any token that can be used as a relop // tg_type - matches any token that can be used as a type // since parsing is recursive, forward declare one function to walk each non-terminal: // note: conditions are represented by expressions static void walk_program(ast) ; static int walk_declarations(ast) ; static void walk_statement(ast) ; static void walk_while(ast) ; static void walk_if(ast) ; static void walk_if_else(ast) ; static void walk_let(ast) ; static void walk_sequence(ast) ; static void walk_expression(ast) ; static void walk_term(ast) ; // now implement the parsing functions // ast create_program(ast declarations,ast statement) static void walk_program(ast n) { push_error_context("walk_program()") ; int nlocals = walk_declarations(get_program_declarations(n)) ; // if the programs starts with x variable declarations, we must start with: // function Main.main x // nextlocal is effectively a variable count so ... write_to_output("function Main.main " + to_string(nlocals) + "\n") ; walk_statement(get_program_statement(n)) ; // always finish with return so the VM code is a complete void function write_to_output("push constant 0\n") ; write_to_output("return\n") ; pop_error_context() ; } // ast create_declarations(vector<ast> variables) static int walk_declarations(ast n) { push_error_context("walk_declarations()") ; int ndecls = size_of_declarations(n) ; pop_error_context() ; return ndecls ; } // statement nodes can contain one of ast_while, ast_if, ast_if_else, ast_let or ast_statements static void walk_statement(ast n) { push_error_context("walk_statement()") ; ast stat = get_statement_statement(n) ; switch(ast_node_kind(stat)) { case ast_while: walk_while(stat) ; break ; case ast_if: walk_if(stat) ; break ; case ast_if_else: walk_if_else(stat) ; break ; case ast_let: walk_let(stat) ; break ; case ast_statements: walk_sequence(stat) ; break ; default: fatal_error(0,"Unknown kind of statement node found") ; break ; } pop_error_context() ; } // ast create_while(ast condition,ast body) static void walk_while(ast n) { push_error_context("walk_while()") ; string label = to_string(while_counter++) ; // label write_to_output("label WHILE_EXP" + label + "\n"); walk_expression(get_while_condition(n)) ; // not write_to_output("not\n"); // if-goto end write_to_output("if-goto WHILE_END" + label + "\n"); walk_sequence(get_while_body(n)) ; // goto label write_to_output("goto WHILE_EXP" + label + "\n"); // label end write_to_output("label WHILE_END" + label + "\n"); pop_error_context() ; } // ast create_if(ast condition,ast if_true) static void walk_if(ast n) { push_error_context("walk_if()") ; string label = to_string(if_counter++) ; walk_expression(get_if_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_if_true(n)) ; // label else write_to_output("label IF_FALSE" + label + '\n'); pop_error_context() ; } // ast create_if_else(ast condition,ast if_true,ast if_false) static void walk_if_else(ast n) { push_error_context("walk_if_else()") ; string label = to_string(if_counter++) ; walk_expression(get_if_else_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_else_if_true(n)) ; // goto_ end write_to_output("goto IF_END" + label + '\n'); // label else write_to_output("label IF_FALSE" + label + '\n'); walk_sequence(get_if_else_if_false(n)) ; // label end write_to_output("label IF_END" + label + '\n'); pop_error_context() ; } // ast create_let(ast variable,ast expression) static void walk_let(ast n) { ast var = get_let_variable(n) ; string segment = get_variable_segment(var) ; int offset = get_variable_offset(var) ; walk_expression(get_let_expression(n)) ; write_to_output("pop " + segment + ' ' + std::to_string(offset) + "\n") ; } // ast create_statements(vector<ast> statements) ; static void walk_sequence(ast n) { push_error_context("walk_sequence()") ; int children = size_of_statements(n) ; for ( int i = 0 ; i < children ; i++ ){ walk_statement(get_statements(n,i)) ; } pop_error_context() ; } // there are no expression nodes, only ast_infix_op, ast_variable and ast_int nodes // ast create_infix_op(ast lhs,string op,ast rhs) static void walk_expression(ast n) { push_error_context("walk_expression()") ; ast expr = get_expression_expression(n) ; if ( ast_have_kind(expr,ast_infix_op) ){ walk_term(get_infix_op_lhs(expr)) ; walk_term(get_infix_op_rhs(expr)) ; string op = get_infix_op_op(expr) ; write_to_output(translate_op(op) + '\n') ; }else{ walk_term(expr) ; } pop_error_context() ; } // there are no term nodes, only ast_variable and ast_int nodes // ast create_variable(string name,string segment,int offset,string type) static void walk_term(ast n) { push_error_context("walk_term()") ; ast term = get_term_term(n) ; switch(ast_node_kind(term)) { case ast_variable: { string segment = get_variable_segment(term) ; int offset = get_variable_offset(term) ; write_to_output("push " + segment + ' ' + std::to_string(offset) + "\n"); break ; } case ast_int: { int number = get_int_constant(term) ; write_to_output("push constant " + std::to_string(number) + "\n"); break ; } default: fatal_error(0,"Unknown kind of term node found") ; break ; } pop_error_context() ; } // main program for workshop 11 XML to VM code translator int main(int argc,char **argv) { // make all output and errors appear immediately config_output(iob_immediate) ; config_errors(iob_immediate) ; walk_program(ast_parse_xml()) ; // flush the output and any errors print_output() ; print_errors() ; }
25.818713
95
0.648471
raymondsim
1358c027fd241943d2d4940191d014559b6cdedb
723
cpp
C++
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
//'''This code is from after reading tutorial''' #include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; bool can(int m,int s){ return s >=0 && s <= 9*m; } int main(){ int a,b,c,d,i,m,s; cin >> m >> s; string minn; a = s; for(i=0 ; i < m; i++){ for(d=0; d < 10; d++){ if((i > 0 || d > 0 || (m == 1 && d==0)) && can(m-i-1,s-d)){ minn += char('0'+d); s-=d; break; } } } if(minn.size() != m){ cout << -1 << " " << -1 << endl; return 0; } cout << minn << " "; string maxx; for(i=0; i < m; i++){ for(d=9; d >=0; d--){ if(can(m-i-1,a-d)){ maxx += char('0'+ d); a -=d ; break ; } } } cout << maxx << endl; return 0; }
15.0625
62
0.453665
Binary-bug
13618be9f365b65ad584ba2d5f342c91624a25b1
750
cpp
C++
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int closestValue(TreeNode* root, double target) { double diff = target - root->val; if (diff < 0 && root->left != NULL) { int leftVal = closestValue(root->left, target); return fabs(diff) < fabs(leftVal - target) ? root->val : leftVal; } else if (diff > 0 && root->right != NULL) { int rightVal = closestValue(root->right, target); return fabs(diff) < fabs(rightVal - target) ? root->val : rightVal; } return root->val; } };
31.25
79
0.545333
tsenmu
13647431df0d0e33c3f278fa19c5923de23b3073
6,245
cpp
C++
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** bomberman ** File description: ** LoadState.cpp */ #ifdef __linux__ #include <glob.h> #elif _WIN32 #include <windows.h> #endif #include "../../include/States/LoadState.hpp" #include "../../include/Singletons/StateMachine.hpp" #include "../../include/Singletons/IrrManager.hpp" #include "../../include/Singletons/EventReceiver.hpp" #include "../../include/Singletons/AssetsPool.hpp" #include "../../include/States/TransitionToGameState.hpp" #include "../../include/PathManager.hpp" const std::map<LoadState::Actions, LoadState::ButtonsDesc> LoadState::_descs { {LoadState::SAVE1, { {610, 250, 1300, 300}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 0]), false); return true; } }}, {LoadState::SAVE2, { {610, 350, 1300, 400}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 1]), false); return true; } }}, {LoadState::SAVE3, { {610, 450, 1300, 500}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 2]), false); return true; } }}, {LoadState::SAVE4, { {610, 550, 1300, 600}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 3]), false); return true; } }}, {LoadState::CANCEL, { {1570, 850, 1870, 900}, "cancel", [](LoadState *self) { self->externalEventsClean(); StateMachine::getInstance().pop(); return false; } }}, {LoadState::PREV, { {785, 850, 935, 900}, "prev", [](LoadState *self) { self->_idx -= 1; self->setSaveButtons(); return true; } }}, {LoadState::NEXT, { {985, 850, 1135, 900}, "next", [](LoadState *self) { self->_idx += 1; self->setSaveButtons(); return true; } }} }; LoadState::LoadState(AStateShare &_share) : AState(_share), AMenuSound(), _idx(0), _eventsActivate(false) { } LoadState::~LoadState() { eventsClean(); } void LoadState::loadButtons() { auto gui = IrrManager::getInstance().getGuienv(); auto &er = EventReceiver::getInstance(); auto &ap = AssetsPool::getInstance(); for (auto &n : _descs) { auto b = gui->addButton(n.second.pos, nullptr, n.first); auto name = n.second.name; b->setImage(ap.loadTexture("buttons/" + name + ".png")); b->setPressedImage(ap.loadTexture("buttons/" + name + "_hover.png")); b->setOverrideFont(_share.getFont()); _buttons.push_back(b); } #ifdef __linux__ glob_t glob_result; glob(PathManager::getHomePath("save/*.dat").c_str(), GLOB_TILDE, NULL, &glob_result); for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) _saves.emplace_back(glob_result.gl_pathv[i]); _idx = 0; #elif _WIN32 HANDLE hFind; WIN32_FIND_DATA data; auto path = PathManager::getHomePath("save/"); auto pattern = PathManager::getHomePath("save/*.dat"); hFind = FindFirstFile(pattern.c_str(), &data); if (hFind != INVALID_HANDLE_VALUE) { do { _saves.emplace_back(path + std::string(data.cFileName)); } while (FindNextFile(hFind, &data)); FindClose(hFind); } #endif setSaveButtons(); } void LoadState::unloadButtons() { for (auto &n : _buttons) n->remove(); _buttons.clear(); } void LoadState::load() { eventsSetup(); loadButtons(); AState::load(); } void LoadState::unload() { unloadButtons(); AState::unload(); } void LoadState::update() { _share.getFunc("rotateMenu")(); AState::update(); AssetsPool::getInstance().cleanSound(); if (getSharedResources().isKeyDown(irr::KEY_ESCAPE)) StateMachine::getInstance().pop(); } void LoadState::draw() { auto &im = IrrManager::getInstance(); im.getSmgr()->drawAll(); im.getGuienv()->drawAll(); } bool LoadState::applyEventButton(const irr::SEvent &ev, LoadState::Actions id) { auto b = getButton(id); auto hover_name = "buttons/" + _descs.at(id).name + "_hover.png"; auto name = "buttons/" + _descs.at(id).name + ".png"; auto &ap = AssetsPool::getInstance(); switch (ev.GUIEvent.EventType) { case irr::gui::EGET_BUTTON_CLICKED: playSelect(); return LoadState::_descs.at(id).fct(this); case irr::gui::EGET_ELEMENT_HOVERED: playCursor(); b->setImage(ap.loadTexture(hover_name)); break; case irr::gui::EGET_ELEMENT_LEFT: b->setImage(ap.loadTexture(name)); break; default: break; } return true; } irr::gui::IGUIButton *LoadState::getButton(LoadState::Actions id) const { if (id < SAVE1 || id > SAVE1 + LOAD_BUTTON_NUMBER) return nullptr; return (_buttons.at(id - SAVE1)); } void LoadState::setSaveButtons() { size_t i = _idx * 4; std::string empty = "- Empty Slot -"; for (; i < _saves.size() && (i == (_idx * 4) || i%4); ++i) { #ifdef _WIN32 std::string temp(_saves[i].substr(_saves[i].rfind('\\') + 1)); #else std::string temp(_saves[i].substr(_saves[i].rfind('/') + 1)); #endif _buttons[i%4]->setText(std::wstring(temp.begin(), temp.end()).c_str()); _buttons[i%4]->setEnabled(true); } for (; i == _idx * 4 || i%4; ++i) { _buttons[i%4]->setEnabled(false); _buttons[i%4]->setText(std::wstring(empty.begin(), empty.end()).c_str()); } _buttons[PREV - SAVE1]->setEnabled(_idx > 0); _buttons[NEXT - SAVE1]->setEnabled((_idx + 1) * 4 < _saves.size()); } void LoadState::eventsSetup() { _eventsActivate = true; auto &er = EventReceiver::getInstance(); er.registerEvent(20, irr::EEVENT_TYPE::EET_GUI_EVENT, [this](const irr::SEvent &ev) { if (!this->isLoaded() || !this->isEnable()) return true; auto id = static_cast<Actions >(ev.GUIEvent.Caller->getID()); if (LoadState::_descs.count(id) > 0) return this->applyEventButton(ev, id); return true; }); } void LoadState::eventsClean() { if (!_eventsActivate) return; auto &er = EventReceiver::getInstance(); er.unregisterEvent(20, irr::EEVENT_TYPE::EET_GUI_EVENT); _eventsActivate = false; } void LoadState::externalEventsClean() { if (!_eventsActivate) return; _eventsActivate = false; } const std::string LoadState::getName() const { return "load"; }
22.959559
86
0.651241
thibautcornolti
1370cbb219e5f0117e1fad56afdfdb8db4f3e237
3,282
cpp
C++
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
#include "Main.h" #include "Log.h" #include <glad/glad.h> #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include "Layers.h" #include "Box2DLayer.h" #include "FirstTriangleLayer.h" #include "Core\Input.h" int main() { float lastTimeFrame = 0; Zinc::Log::Init(); ZINC_CORE_WARN("Initialized Log"); if (!glfwInit()) return -1; GLFWwindow *window = glfwCreateWindow(1024, 800, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); Zinc::Input::Init(window); glfwSetKeyCallback(window, Zinc::Input::KeyCallBack); ZINC_CORE_ASSERT(gladLoadGL(), "glad not loaded!"); ZINC_CORE_INFO("OpenGL Renderer:"); ZINC_CORE_INFO("Vendor: {0}", glGetString(GL_VENDOR)); ZINC_CORE_INFO("Renderer: {0}", glGetString(GL_RENDERER)); ZINC_CORE_INFO("Version: {0}", glGetString(GL_VERSION)); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows //io.ConfigViewportsNoAutoMerge = true; //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(); Zinc::Layers *layers = new Zinc::Layers(); //layers->Add(new Zinc::Box2DLayer()); layers->Add(new Zinc::FirstTriangleLayer()); layers->Awake(); while (!glfwWindowShouldClose(window)) { float time = glfwGetTime(); float timeStep = time - lastTimeFrame; lastTimeFrame = time; int display_w, display_h; glfwMakeContextCurrent(window); glfwGetFramebufferSize(window, &display_w, &display_h); //glViewport(0, 0, display_w, display_h); glClearColor(0.1f, 0.1f, 0.1f, 1); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); layers->Update(timeStep); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Update and Render additional Platform Windows // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere. // For this specific demo app we could also call glfwMakeContextCurrent(window) directly) if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); } glfwSwapBuffers(window); //Zinc::Input::Update(); glfwPollEvents(); } layers->OnDestroy(); delete layers; glfwTerminate(); return 0; }
29.836364
133
0.736746
DragonJT
13735ee477db0faeaa68db3aaa223f05e78889cb
13,509
hpp
C++
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2020, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "helics/application_api/Publications.hpp" #include "helics/application_api/Subscriptions.hpp" #include "helics/application_api/ValueFederate.hpp" #ifndef HELICS_SHARED_LIBRARY # include "testFixtures.hpp" #else # include "testFixtures_shared.hpp" #endif #include <future> #include <gtest/gtest.h> #include <string> template<class X> void runFederateTest( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications auto& pubid = vFed->registerGlobalPublication<X>("pub1"); auto& subid = vFed->registerSubscription("pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); auto val = subid.getValue<X>(); EXPECT_EQ(val, defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); subid.getValue(val); EXPECT_EQ(val, testValue2); vFed->finalize(); EXPECT_TRUE(vFed->getCurrentMode() == helics::Federate::modes::finalize); helics::cleanupHelicsLibrary(); } template<class X> void runFederateTestObj( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications helics::PublicationT<X> pubid(helics::GLOBAL, vFed.get(), "pub1"); auto subid = helics::make_subscription<X>(*vFed, "pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); X val; subid.getValue(val); EXPECT_EQ(val, defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect val = subid.getValue(); EXPECT_EQ(val, testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); val = subid.getValue(); EXPECT_EQ(val, testValue2); vFed->finalize(); } template<class X> void runFederateTestv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications auto& pubid = vFed->registerGlobalPublication<X>("pub1"); auto& subid = vFed->registerSubscription("pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_TRUE(val == defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); subid.getValue(val); EXPECT_TRUE(val == testValue2); vFed->finalize(); helics::cleanupHelicsLibrary(); } template<class X> void runFederateTestObjv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications helics::PublicationT<X> pubid(helics::GLOBAL, vFed.get(), "pub1"); auto sub = helics::make_subscription<X>(vFed.get(), "pub1"); vFed->setProperty(helics_property_time_delta, 1.0); sub.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); auto val = sub.getValue(); EXPECT_TRUE(val == defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value sub.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect val = sub.getValue(); EXPECT_TRUE(val == testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); val = sub.getValue(); EXPECT_TRUE(val == testValue2); vFed->finalize(); } template<class X> void runDualFederateTest( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications auto& pubid = fedA->registerGlobalPublication<X>("pub1"); auto& subid = fedB->registerSubscription("pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_EQ(val, defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_EQ(val, testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestv2( const std::string& core_type_str, X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications auto& pubid = fedA->registerGlobalPublication<X>("pub1"); auto& subid = fedB->registerSubscription("pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_TRUE(val == defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_TRUE(val == testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestObj( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; using namespace helics; fixture.SetupTest<ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<ValueFederate>(0); auto fedB = fixture.GetFederateAs<ValueFederate>(1); // register the publications PublicationT<X> pubid(GLOBAL, fedA, "pub1"); auto subid = make_subscription<X>(*fedB, "pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val; subid.getValue(val); EXPECT_EQ(val, defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_EQ(val, testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestObjv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; using namespace helics; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications PublicationT<X> pubid(GLOBAL, fedA.get(), "pub1"); auto subid = helics::make_subscription<X>(fedB.get(), "pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue(); EXPECT_TRUE(val == defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_TRUE(val == testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); }
29.114224
114
0.6717
corinnegroth
1376a613e70c699d3bcf53a8db7debf8f5c5050a
1,616
hpp
C++
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
#pragma once // sqrt.hpp: sqrt functions for decimals // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/native/ieee754.hpp> #include <universal/number/decimal/numeric_limits.hpp> #ifndef DECIMAL_NATIVE_SQRT #define DECIMAL_NATIVE_SQRT 0 #endif namespace sw { namespace universal { #if DECIMAL_NATIVE_SQRT // native sqrt for decimal inline decimal sqrt(const decimal& f) { if (f < 0) throw decimal_negative_sqrt_arg(); using Decimal = decimal; constexpr Decimal eps = std::numeric_limits<Rational>::epsilon(); Decimal y(f); Decimal x(f); x >>= 1; // divide by 2 Decimal diff = (x * x - y); int iterations = 0; while (sw::universal::abs(diff) > eps) { x = (x + y); x >>= 1; y = f / x; diff = x - y; // std::cout << " x: " << x << " y: " << y << " diff " << diff << '\n'; if (++iterations > rbits) break; } if (iterations > rbits) std::cerr << "sqrt(" << double(f) << ") failed to converge\n"; return x; } #else inline decimal sqrt(const decimal& f) { #if DECIMAL_THROW_ARITHMETIC_EXCEPTION if (f.isneg()) { throw decimal_negative_sqrt_arg(); } #else std::cerr << "decimal_negative_sqrt_arg\n"; #endif return decimal(std::sqrt((double)f)); } #endif // reciprocal sqrt // inline decimal rsqrt(const decimal& f) { // decimal rsqrt = sqrt(f); // return rsqrt.reciprocate(); // } /////////////////////////////////////////////////////////////////// // specialized sqrt configurations }} // namespace sw::universal
26.491803
106
0.631807
FloEdelmann
13835e1be5cbc376d80aa3ae1000cabecfae8863
899
cpp
C++
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
2
2020-10-28T15:02:41.000Z
2021-10-02T13:18:24.000Z
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
4
2020-10-07T05:59:13.000Z
2021-10-02T08:01:27.000Z
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
51
2020-10-01T03:07:30.000Z
2021-10-05T16:25:22.000Z
//Mid Point Circle Drawing Algorithm #include<iostream> #include<graphics.h> #include<conio.h> #include<stdlib.h> #include<stdio.h> using namespace std; void symPlot(int xc, int yc, int x, int y) { putpixel(x+xc,y+yc,RED); putpixel(x+xc,-y+yc,YELLOW); putpixel(-x+xc,-y+yc,GREEN); putpixel(-x+xc,y+yc,BLUE); putpixel(y+xc,x+yc,BLUE); putpixel(y+xc,-x+yc,GREEN); putpixel(-y+xc,-x+yc,YELLOW); putpixel(-y+xc,x+yc,RED); } void solve(int x, int y, int r){ int X=0, Y=r; int d = 5/4 - r; while(X <= Y) { symPlot(x,y,X,Y); if(d < 0) { d = d + 2*X + 3; } else{ d = d + 2*(X - Y) + 5; Y--; } X++; } } int main() { int x1, y1, radius; cout<<"Enter X Y (Center of Circle)"<<endl; cin>>x1>>y1; cout<<"Enter Radius of Circle"<<endl; cin>>radius; initwindow(500,500); solve(x1,y1,radius); getch(); closegraph(); return 0; }
17.627451
44
0.571746
VishalGupta0609
1383e6fe074288fe9a2042fd4bc6e29ad0a6653e
194
cpp
C++
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
2
2019-06-28T04:54:47.000Z
2020-02-25T08:39:19.000Z
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
null
null
null
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int N; cin >> N; if (N < 1200) { cout << "ABC" << endl; } else { cout << "ARC" << endl; } return 0; }
14.923077
40
0.551546
hakatashi
13855053e1f8caae95cbd9e531cd093b9c4dabc0
763
cpp
C++
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int merge(int *a, int s, int e){ int mid= (s+e)/2; int i=s; int j=mid+1; int k=s; int temp[1000]; int cnt=0; while(i<=mid and j<=e){ if(a[i]<=a[j]){ temp[k++]=a[i++]; } else{ temp[k++]=a[i++]; cnt+= mid-i+1; } } while(i<=mid){ temp[k++]= a[i++]; } while(j<=e){ temp[k++]=a[i++]; } for(int i=s;i<=e;i++){ a[i]=temp[i]; } return cnt; } int inversion_count(int *a, int s, int e){ if(s>=e){ return 0; } int mid= (s+e)/2; int x= inversion_count(a,s,mid); int y= inversion_count(a,mid+1,e); int z= merge(a,s,e); return x+y+z; } int main() { int a[]= {1,3,4,6,8,0}; int n= sizeof(a)/sizeof(int); cout<<inversion_count(a,0,n-1)<<endl; }
16.586957
43
0.503277
alpha-neutr0n
138558479437968fdc997651caa726335995032f
298
cc
C++
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
1
2020-03-15T08:12:31.000Z
2020-03-15T08:12:31.000Z
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
null
null
null
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
null
null
null
// 11231 Black and white painting finding patterns harder // focus on the lower left tile #include <iostream> using namespace std; int main() { int n, m, c; while (cin >> n >> m >> c and n + m + c) { cout << ((n - 7) * (m - 7) / 2 + ((((n - 7) * (m - 7)) % 2) & c)) << '\n'; } }
29.8
82
0.496644
chq-matteo
13868b21220037ba8818a86835951a0d278ef5b8
723
cpp
C++
GumpEditor-0.32/GumpPaperdoll.cpp
zerodowned/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
1
2019-02-08T18:03:28.000Z
2019-02-08T18:03:28.000Z
GumpEditor-0.32/GumpPaperdoll.cpp
SiENcE/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
null
null
null
GumpEditor-0.32/GumpPaperdoll.cpp
SiENcE/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
7
2015-03-11T22:06:23.000Z
2019-12-21T09:49:57.000Z
#include "StdAfx.h" #include "GumpEditor.h" #include ".\gumppaperdoll.h" CGumpPaperdoll::CGumpPaperdoll(CGumpPtr pGump) : CGumpPicture(NULL) { SetGump(pGump); SetTitle("paperdoll"); SetType("paperdoll"); CString strName; strName.Format("paperdoll_%x", pGump ? pGump->GetGumpID() : 0); SetName(strName); //AddPropertyPage( &m_page ); } CGumpPaperdoll::~CGumpPaperdoll(void) { } CDiagramEntity* CGumpPaperdoll::Clone() { CGumpPaperdoll* obj = new CGumpPaperdoll(m_pGump); obj->Copy( this ); return obj; } CDiagramEntity* CGumpPaperdoll::CreateFromString( XML::Node* node ) { CGumpPaperdoll* obj = new CGumpPaperdoll(NULL); if(!obj->FromString( node ) ) { delete obj; obj = NULL; } return obj; }
16.813953
67
0.706777
zerodowned
138b76dce495b006a8db1478e0c30014407eb225
11,524
cpp
C++
example/runtime_property_change.cpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
example/runtime_property_change.cpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
example/runtime_property_change.cpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
#include <thread> #include <dirent.h> #include <algorithm> #include <Elementary.h> #include <rive_tizen.hpp> #include "shapes/paint/fill.hpp" #include "shapes/paint/stroke.hpp" #include "shapes/paint/color.hpp" #include "shapes/paint/solid_color.hpp" #include "animation/linear_animation_instance.hpp" #include "artboard.hpp" #include "file.hpp" #include "tvg_renderer.hpp" using namespace std; #define WIDTH 1000 #define HEIGHT 700 #define LIST_HEIGHT 200 static unique_ptr<tvg::SwCanvas> canvas = nullptr; static rive::File* currentFile = nullptr; static rive::Artboard* artboard = nullptr; static rive::LinearAnimationInstance* animationInstance = nullptr; static Ecore_Animator *animator = nullptr; static Eo* view = nullptr; static vector<std::string> rivefiles; static double lastTime; static Eo* statePopup = nullptr; std::string currentColorInstance; Eo *entryR, *entryG, *entryB, *entryA; static void deleteWindow(void *data, Evas_Object *obj, void *ev) { elm_exit(); } static void drawToCanvas(void* data, Eo* obj) { if (canvas->draw() == tvg::Result::Success) canvas->sync(); } static void initAnimation(int index) { delete animationInstance; animationInstance = nullptr; auto animation = artboard->animation(index); if (animation) animationInstance = new rive::LinearAnimationInstance(animation); } static void loadRiveFile(const char* filename) { lastTime = ecore_time_get(); //Check point // Load Rive File FILE* fp = fopen(filename, "r"); fseek(fp, 0, SEEK_END); size_t length = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* bytes = new uint8_t[length]; if (fread(bytes, 1, length, fp) != length) { delete[] bytes; fprintf(stderr, "failed to read all of %s\n", filename); return; } auto reader = rive::BinaryReader(bytes, length); rive::File* file = nullptr; auto result = rive::File::import(reader, &file); if (result != rive::ImportResult::success) { delete[] bytes; fprintf(stderr, "failed to import %s\n", filename); return; } artboard = file->artboard(); artboard->advance(0.0f); delete animationInstance; animationInstance = nullptr; auto animation = artboard->firstAnimation(); if (animation) animationInstance = new rive::LinearAnimationInstance(animation); delete currentFile; currentFile = file; delete[] bytes; } Eina_Bool animationLoop(void *data) { canvas->clear(); double currentTime = ecore_time_get(); float elapsed = currentTime - lastTime; lastTime = currentTime; if (!artboard || !animationInstance) return ECORE_CALLBACK_RENEW; artboard->updateComponents(); animationInstance->advance(elapsed); animationInstance->apply(artboard); artboard->advance(elapsed); rive::TvgRenderer renderer(canvas.get()); renderer.save(); renderer.align(rive::Fit::contain, rive::Alignment::center, rive::AABB(0, 0, WIDTH, HEIGHT), artboard->bounds()); artboard->draw(&renderer); renderer.restore(); evas_object_image_pixels_dirty_set(view, EINA_TRUE); evas_object_image_data_update_add(view, 0, 0, WIDTH, HEIGHT); return ECORE_CALLBACK_RENEW; } static void runExample(uint32_t* buffer) { std::string path = RIVE_FILE_DIR; path.append("runtime_color_change.riv"); loadRiveFile(path.c_str()); //Create a Canvas canvas = tvg::SwCanvas::gen(); canvas->target(buffer, WIDTH, WIDTH, HEIGHT, tvg::SwCanvas::ARGB8888); animator = ecore_animator_add(animationLoop, nullptr); } static void cleanExample() { delete animationInstance; } static void animPopupItemCb(void *data EINA_UNUSED, Evas_Object *obj, void *event_info) { int animationIndex = static_cast<int>(reinterpret_cast<intptr_t>(data)); initAnimation(animationIndex); elm_ctxpopup_dismiss(statePopup); } static Elm_Object_Item* animPopupItemNew(Evas_Object *obj, const char *label, int index) { if (!obj) return nullptr; return elm_ctxpopup_item_append(obj, label, nullptr, animPopupItemCb, reinterpret_cast<void*>(index)); } static void animPopupDismissCb(void *data EINA_UNUSED, Evas_Object *obj, void *event_info EINA_UNUSED) { evas_object_del(obj); statePopup = nullptr; } static void viewClickedCb(void *data, Evas *e EINA_UNUSED, Evas_Object *obj EINA_UNUSED, void *event_info) { if (!artboard) return; if (statePopup) evas_object_del(statePopup); statePopup = elm_ctxpopup_add(obj); evas_object_smart_callback_add(statePopup, "dismissed", animPopupDismissCb, nullptr); for (size_t index = 0; index < artboard->animationCount(); index++) animPopupItemNew(statePopup, artboard->animation(index)->name().c_str(), index); int x, y; evas_pointer_canvas_xy_get(evas_object_evas_get(obj), &x, &y); evas_object_move(statePopup, x, y); evas_object_show(statePopup); } static void selectedCb(void *data EINA_UNUSED, Evas_Object *obj EINA_UNUSED, void *event_info) { const char *text = elm_object_item_text_get((Elm_Object_Item*)event_info); currentColorInstance = text; } static void applyCb(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { const char *r = elm_object_text_get(entryR); const char *g = elm_object_text_get(entryG); const char *b = elm_object_text_get(entryB); const char *a = elm_object_text_get(entryA); printf("current vector instance: %s r:%d g:%d b:%d a:%d\n", currentColorInstance.c_str(), atoi(r), atoi(g), atoi(b), atoi(a)); auto colorInstance = artboard->find<rive::Fill>(currentColorInstance.c_str()); if (colorInstance) colorInstance->paint()->as<rive::SolidColor>()->colorValue(rive::colorARGB(atoi(a), atoi(r), atoi(g), atoi(b))); } static void setupScreen(uint32_t* buffer) { Eo* win = elm_win_util_standard_add(nullptr, "Rive-Tizen Viewer"); evas_object_smart_callback_add(win, "delete,request", deleteWindow, 0); Eo* box = elm_box_add(win); evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_win_resize_object_add(win, box); evas_object_show(box); view = evas_object_image_filled_add(evas_object_evas_get(box)); evas_object_image_size_set(view, WIDTH, HEIGHT); evas_object_image_data_set(view, buffer); evas_object_image_pixels_get_callback_set(view, drawToCanvas, nullptr); evas_object_image_pixels_dirty_set(view, EINA_TRUE); evas_object_image_data_update_add(view, 0, 0, WIDTH, HEIGHT); evas_object_size_hint_weight_set(view, EVAS_HINT_EXPAND, 0.0); evas_object_size_hint_min_set(view, WIDTH, HEIGHT); evas_object_show(view); elm_box_pack_end(box, view); evas_object_event_callback_add(view, EVAS_CALLBACK_MOUSE_UP, viewClickedCb, nullptr); Eo* hoversel = elm_hoversel_add(win); elm_hoversel_auto_update_set(hoversel, EINA_TRUE); elm_hoversel_hover_parent_set(hoversel, win); evas_object_smart_callback_add(hoversel, "selected", selectedCb, NULL); evas_object_size_hint_weight_set(hoversel, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(hoversel, EVAS_HINT_FILL, 0.0); elm_object_text_set(hoversel, "Vector Instances"); elm_hoversel_item_add(hoversel, "body_color", NULL, ELM_ICON_NONE, NULL, NULL); elm_hoversel_item_add(hoversel, "straw_color", NULL, ELM_ICON_NONE, NULL, NULL); elm_hoversel_item_add(hoversel, "eye_left_color", NULL, ELM_ICON_NONE, NULL, NULL); elm_hoversel_item_add(hoversel, "eye_right_color", NULL, ELM_ICON_NONE, NULL, NULL); elm_hoversel_item_add(hoversel, "mouse_color", NULL, ELM_ICON_NONE, NULL, NULL); evas_object_show(hoversel); elm_box_pack_end(box, hoversel); Eo* colorBox = elm_box_add(win); elm_box_horizontal_set(colorBox, true); evas_object_size_hint_weight_set(colorBox, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(colorBox, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_box_pack_end(box, colorBox); Eo* colorRText = elm_label_add(colorBox); elm_object_text_set(colorRText, "R : "); evas_object_size_hint_weight_set(colorRText, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_show(colorRText); entryR = elm_entry_add(colorBox); elm_entry_scrollable_set(entryR, EINA_TRUE); elm_entry_single_line_set(entryR, EINA_TRUE); elm_scroller_policy_set(entryR, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_OFF); evas_object_size_hint_weight_set(entryR, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(entryR, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_show(entryR); elm_box_pack_end(colorBox, colorRText); elm_box_pack_end(colorBox, entryR); Eo* colorGText = elm_label_add(colorBox); elm_object_text_set(colorGText, "G : "); evas_object_size_hint_weight_set(colorGText, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_show(colorGText); entryG = elm_entry_add(colorBox); elm_entry_single_line_set(entryG, EINA_TRUE); elm_entry_scrollable_set(entryG, EINA_TRUE); elm_entry_single_line_set(entryG, EINA_TRUE); evas_object_size_hint_weight_set(entryG, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(entryG, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_show(entryG); elm_box_pack_end(colorBox, colorGText); elm_box_pack_end(colorBox, entryG); Eo* colorBText = elm_label_add(colorBox); elm_object_text_set(colorBText, "B : "); evas_object_size_hint_weight_set(colorBText, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_show(colorBText); entryB = elm_entry_add(colorBox); elm_entry_single_line_set(entryB, EINA_TRUE); elm_entry_scrollable_set(entryB, EINA_TRUE); elm_entry_single_line_set(entryB, EINA_TRUE); evas_object_size_hint_weight_set(entryB, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(entryB, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_show(entryB); elm_box_pack_end(colorBox, colorBText); elm_box_pack_end(colorBox, entryB); Eo* colorAText = elm_label_add(colorBox); elm_object_text_set(colorAText, "A : "); evas_object_size_hint_weight_set(colorAText, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_show(colorAText); entryA = elm_entry_add(colorBox); elm_entry_single_line_set(entryA, EINA_TRUE); elm_entry_scrollable_set(entryA, EINA_TRUE); elm_entry_single_line_set(entryA, EINA_TRUE); evas_object_size_hint_weight_set(entryA, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(entryA, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_show(entryA); elm_box_pack_end(colorBox, colorAText); elm_box_pack_end(colorBox, entryA); Eo* applyButton = elm_button_add(colorBox); elm_object_text_set(applyButton, "Apply"); evas_object_smart_callback_add(applyButton, "clicked", applyCb, nullptr); evas_object_show(applyButton); elm_box_pack_end(colorBox, applyButton); evas_object_show(colorBox); evas_object_resize(win, WIDTH, HEIGHT + LIST_HEIGHT); evas_object_show(win); } int main(int argc, char **argv) { static uint32_t buffer[WIDTH * HEIGHT]; tvg::Initializer::init(tvg::CanvasEngine::Sw, thread::hardware_concurrency()); elm_init(argc, argv); setupScreen(buffer); runExample(buffer); elm_run(); cleanExample(); elm_shutdown(); tvg::Initializer::term(tvg::CanvasEngine::Sw); return 0; }
33.114943
129
0.738719
JSUYA
138e11ef61f9342e7b2e8b4cd1c556cf7272247f
2,680
cpp
C++
src/nc/common/Escaping.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
6
2016-09-06T02:10:08.000Z
2021-01-19T09:02:04.000Z
src/nc/common/Escaping.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
null
null
null
src/nc/common/Escaping.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
6
2015-10-02T14:11:45.000Z
2021-01-19T09:02:07.000Z
/* The file is part of Snowman decompiler. */ /* See doc/licenses.asciidoc for the licensing information. */ // // SmartDec decompiler - SmartDec is a native code to C/C++ decompiler // Copyright (C) 2015 Alexander Chernov, Katerina Troshina, Yegor Derevenets, // Alexander Fokin, Sergey Levin, Leonid Tsvetkov // // This file is part of SmartDec decompiler. // // SmartDec decompiler 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. // // SmartDec decompiler 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 SmartDec decompiler. If not, see <http://www.gnu.org/licenses/>. // #include "Escaping.h" #include <Foreach.h> //#include <Qfbstring> namespace nc { fbstring escapeDotString(const fbstring &string) { fbstring result; result.reserve(string.size()); foreach (char c, string) { //toLatin1() switch (c) { case '\\': result += "\\\\"; break; case '"': result += "\\\""; break; case '\n': result += "\\n"; break; default: result += c; break; } } return result; } fbstring escapeCString(const fbstring &string) { fbstring result; result.reserve(string.size()); foreach (char c, string) { switch (c) { case '\\': result += "\\\\"; break; case '\a': result += "\\a"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; case '\v': result += "\\v"; break; case '"': result += "\\\""; break; default: result += c; break; } } return result; } } // namespace nc /* vim:set et sts=4 sw=4: */
26.019417
79
0.496269
treadstoneproject
ca5cb1098c67ed0ca812b1b9b7acaab7ab34ed61
2,846
cpp
C++
Tuniac1/tak_Plugin/TAKDecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
3
2022-01-05T08:47:51.000Z
2022-01-06T12:42:18.000Z
Tuniac1/tak_Plugin/TAKDecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
null
null
null
Tuniac1/tak_Plugin/TAKDecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
1
2022-01-06T16:12:58.000Z
2022-01-06T16:12:58.000Z
#include "StdAfx.h" #include "takdecoder.h" CTAKDecoder::CTAKDecoder(void) { } CTAKDecoder::~CTAKDecoder(void) { } bool CTAKDecoder::Open(LPTSTR szSource) { char tempname[MAX_PATH]; WideCharToMultiByte(CP_UTF8, 0, szSource, -1, tempname, MAX_PATH, 0, 0); Options.Cpu = tak_Cpu_Any; Options.Flags = NULL; Decoder = tak_SSD_Create_FromFile (tempname, &Options, NULL, NULL); if (Decoder == NULL) return false; if (tak_SSD_Valid (Decoder) != tak_True) return false; if (tak_SSD_GetStreamInfo (Decoder, &StreamInfo) != tak_res_Ok) return false; //SamplesPerBuf = StreamInfo.Sizes.FrameSizeInSamples; //SampleSize = StreamInfo.Audio.BlockSize; /* Frame / Sample size. */ //BufSize = SamplesPerBuf * SampleSize; /* Enough space to hold a decoded frame. */ buffer = new char [4096 * StreamInfo.Audio.BlockSize]; m_Buffer = new float [4096 * StreamInfo.Audio.BlockSize]; if(StreamInfo.Audio.SampleBits == 8) { m_divider = 128.0f; } else if(StreamInfo.Audio.SampleBits == 16) { m_divider = 32767.0f; } else if(StreamInfo.Audio.SampleBits == 24) { m_divider = 8388608.0f; } else if(StreamInfo.Audio.SampleBits == 32) { m_divider = 2147483648.0f; } return(true); } void CTAKDecoder::Destroy(void) { tak_SSD_Destroy (Decoder); if(buffer) { delete [] buffer; buffer = NULL; } if(m_Buffer) { delete [] m_Buffer; m_Buffer = NULL; } delete this; } bool CTAKDecoder::GetFormat(unsigned long * SampleRate, unsigned long * Channels) { *SampleRate = StreamInfo.Audio.SampleRate; *Channels = StreamInfo.Audio.ChannelNum; return(true); } bool CTAKDecoder::GetLength(unsigned long * MS) { *MS = StreamInfo.Sizes.SampleNum/StreamInfo.Audio.SampleRate*1000; return true; } bool CTAKDecoder::SetPosition(unsigned long * MS) { unsigned long sample = (*MS * StreamInfo.Audio.SampleRate)/1000; tak_SSD_Seek(Decoder, sample); return true; } bool CTAKDecoder::SetState(unsigned long State) { return(true); } bool CTAKDecoder::GetBuffer(float ** ppBuffer, unsigned long * NumSamples) { *NumSamples =0; OpResult = tak_SSD_ReadAudio (Decoder, buffer, 4096, &ReadNum); if ((OpResult != tak_res_Ok) && (OpResult != tak_res_ssd_FrameDamaged)) { //char ErrorMsg[tak_ErrorStringSizeMax]; //tak_SSD_GetErrorString (tak_SSD_State (Decoder), ErrorMsg, tak_ErrorStringSizeMax); return false; } if (ReadNum > 0) { short * pData = (short*)buffer; float * pBuffer = m_Buffer; for(int x=0; x<ReadNum * StreamInfo.Audio.ChannelNum; x++) { *pBuffer = (*pData) / m_divider; pData ++; pBuffer++; } *ppBuffer = m_Buffer; } else return false; *NumSamples = ReadNum * StreamInfo.Audio.ChannelNum; return true; }
21.398496
88
0.665847
Harteex
ca5e1cf6af97b55dfbe6ab458a620d084e887766
3,835
cpp
C++
example/rsp/rsp_engine.cpp
krakeusz/bot-judge
d4879f7e58ecb91d6668d7e317018a8a184a4923
[ "MIT" ]
null
null
null
example/rsp/rsp_engine.cpp
krakeusz/bot-judge
d4879f7e58ecb91d6668d7e317018a8a184a4923
[ "MIT" ]
null
null
null
example/rsp/rsp_engine.cpp
krakeusz/bot-judge
d4879f7e58ecb91d6668d7e317018a8a184a4923
[ "MIT" ]
null
null
null
// Rock, Scissors, Paper engine #include "engine.h" #include <algorithm> #include <array> #include <cctype> #include <cstring> #include <limits> #include <memory> namespace Engine { using std::array; using std::string; using std::to_string; using std::unique_ptr; using std::vector; class Choice { public: virtual bool losesAgainstPaper() const = 0; virtual bool losesAgainstRock() const = 0; virtual bool losesAgainstScissors() const = 0; virtual bool beats(const Choice& choice) const = 0; }; class Rock : public Choice { public: virtual bool losesAgainstPaper() const override { return true; } virtual bool losesAgainstRock() const override { return false; } virtual bool losesAgainstScissors() const override { return false; } virtual bool beats(const Choice& choice) const override { return choice.losesAgainstRock(); } }; class Paper : public Choice { public: virtual bool losesAgainstPaper() const override { return false; } virtual bool losesAgainstRock() const override { return false; } virtual bool losesAgainstScissors() const override { return true; } virtual bool beats(const Choice& choice) const override { return choice.losesAgainstPaper(); } }; class Scissors : public Choice { public: virtual bool losesAgainstPaper() const override { return false; } virtual bool losesAgainstRock() const override { return true; } virtual bool losesAgainstScissors() const override { return false; } virtual bool beats(const Choice& choice) const override { return choice.losesAgainstScissors(); } }; void ignoreLine(std::istream& istr) { istr.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } unique_ptr<Choice> choiceFromString(const string& str) { string upperStr = str; if (str == "ROCK") { return unique_ptr<Choice>(new Rock); } else if (str == "PAPER") { return unique_ptr<Choice>(new Paper); } else if (str == "SCISSORS") { return unique_ptr<Choice>(new Scissors); } return nullptr; } constexpr int PLAYERS = 2; GameResult play_game(vector<PlayerData>& players) noexcept { try { if (players.size() != PLAYERS) { return GameResult::createError(players, "This game is meant for " + to_string(PLAYERS) + " players only"); } array<int, PLAYERS> winCount = { 0, 0 }; constexpr int ROUNDS = 10; for (int i = 0; i < ROUNDS; i++) { vector<unique_ptr<Choice>> choices; for (auto& player: players) { auto& stream = player.playerStream(); string response; stream.set_timeout_ms(100); stream << "MOVE" << std::endl; stream >> response; ignoreLine(stream); if (stream.eof()) { string details = string("Win by opponent error: ") + stream.get_last_strerror(); return GameResult::createWin(players, players[1-player.getPlayerId()], details); } auto choiceP = choiceFromString(response); if (!choiceP) { string details = "Win by opponent error: move not recognized: '" + response + "'"; return GameResult::createWin(players, players[1-player.getPlayerId()], details); } choices.push_back(std::move(choiceP)); } if (choices[0]->beats(*choices[1])) winCount[0]++; if (choices[1]->beats(*choices[0])) winCount[1]++; } int winnerId = (winCount[0] > winCount[1] ? 0 : 1); string details = to_string(winCount[winnerId]) + "-" + to_string(winCount[1-winnerId]); if (winCount[0] == winCount[1]) { return GameResult::createDraw(players, details); } return GameResult::createWin(players, players[winnerId], details); } catch (std::exception& e) { return GameResult::createError(players, e.what()); } } } // namespace Engine
27.589928
99
0.652151
krakeusz