hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
3fb1ebf9364cbd45fbb144e29d9f765692aebd35
8,541
cpp
C++
src/gsw/parsers/src/TelemetryInfoGenerator.cpp
athena255/FlightSoftware
c3fd7dcc6c265fad9843f8992b60d5a773c99f23
[ "MIT" ]
null
null
null
src/gsw/parsers/src/TelemetryInfoGenerator.cpp
athena255/FlightSoftware
c3fd7dcc6c265fad9843f8992b60d5a773c99f23
[ "MIT" ]
1
2020-09-20T20:11:06.000Z
2020-09-20T20:11:06.000Z
src/gsw/parsers/src/TelemetryInfoGenerator.cpp
athena255/FlightSoftware
c3fd7dcc6c265fad9843f8992b60d5a773c99f23
[ "MIT" ]
null
null
null
#include "TelemetryInfoGenerator.hpp" #include <type_traits> #include <typeinfo> #include <array> TelemetryInfoGenerator::TelemetryInfoGenerator( const std::vector<DownlinkProducer::FlowData>& _flow_data) : r(), fcp(r, _flow_data), flow_data(_flow_data) {} /************** Helper functions for telemetry info generation. ***********/ using nlohmann::json; template<typename T> std::string type_name() { if (std::is_same<unsigned int, T>::value) return "unsigned int"; else if (std::is_same<signed int, T>::value) return "signed int"; else if (std::is_same<unsigned char, T>::value) return "unsigned char"; else if (std::is_same<signed char, T>::value) return "signed char"; else if (std::is_same<float, T>::value) return "float"; else if (std::is_same<double, T>::value) return "double"; else if (std::is_same<f_vector_t, T>::value) return "std float vector"; else if (std::is_same<lin::Vector3f, T>::value) return "lin float vector"; else if (std::is_same<d_vector_t, T>::value) return "std double vector"; else if (std::is_same<lin::Vector3d, T>::value) return "lin double vector"; else if (std::is_same<f_quat_t, T>::value) return "std float quaternion"; else if (std::is_same<lin::Vector4f, T>::value) return "lin float quaternion"; else if (std::is_same<d_quat_t, T>::value) return "std double quaternion"; else if (std::is_same<lin::Vector4d, T>::value) return "lin double quaternion"; else if (std::is_same<bool, T>::value) return "bool"; else if (std::is_same<gps_time_t, T>::value) return "gps_time_t"; else { std::cout << "Invalid typename specified to stringify: " << typeid(T).name() << std::endl; assert(false); } } template<template<typename> class StateFieldType, typename UnderlyingType, class StateFieldBaseType> bool try_collect_field_info(const StateFieldBaseType* field, json& field_info) { const StateFieldType<UnderlyingType>* ptr = dynamic_cast<const StateFieldType<UnderlyingType>*>(field); if (!ptr) return false; field_info["type"] = type_name<UnderlyingType>(); field_info["min"] = ptr->get_serializer_min(); field_info["max"] = ptr->get_serializer_max(); return true; } template<template<typename> class StateFieldType, typename UnderlyingType, class StateFieldBaseType> bool try_collect_vector_field_info(const StateFieldBaseType* field, json& field_info) { static_assert(std::is_floating_point<UnderlyingType>::value, "Can't collect vector field info for a vector of non-float or non-double type."); using UnderlyingArrayVectorType = std::array<UnderlyingType, 3>; using UnderlyingLinVectorType = lin::Vector<UnderlyingType, 3>; const StateFieldType<UnderlyingArrayVectorType>* ptr1 = dynamic_cast<const StateFieldType<UnderlyingArrayVectorType>*>(field); const StateFieldType<UnderlyingLinVectorType>* ptr2 = dynamic_cast<const StateFieldType<UnderlyingLinVectorType>*>(field); if (ptr1) { field_info["type"] = type_name<UnderlyingArrayVectorType>(); field_info["min"] = ptr1->get_serializer_min()[0]; field_info["max"] = ptr1->get_serializer_max()[0]; } else if (ptr2) { field_info["type"] = type_name<UnderlyingLinVectorType>(); field_info["min"] = ptr2->get_serializer_min()(0); field_info["max"] = ptr2->get_serializer_max()(0); } else return false; return true; } template<template<typename> class StateFieldType, typename UnderlyingType, class StateFieldBaseType> bool try_collect_unbounded_field_info(const StateFieldBaseType* field, json& field_info) { static_assert(std::is_same<UnderlyingType, gps_time_t>::value || std::is_same<UnderlyingType, bool>::value || std::is_same<UnderlyingType, d_quat_t>::value || std::is_same<UnderlyingType, f_quat_t>::value || std::is_same<UnderlyingType, lin::Vector4d>::value || std::is_same<UnderlyingType, lin::Vector4f>::value, "Can't collect unbounded field info for a non-bool, non-GPS time, or non-quaternion type."); const StateFieldType<UnderlyingType>* ptr = dynamic_cast<const StateFieldType<UnderlyingType>*>(field); if (!ptr) return false; field_info["type"] = type_name<UnderlyingType>(); return true; } template<template<typename> class StateFieldType, class StateFieldBaseType> json get_field_info(const StateFieldBaseType* field) { json field_info; field_info["bitsize"] = field->bitsize(); bool found_field_type = false; found_field_type |= try_collect_field_info<StateFieldType, unsigned int, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_field_info<StateFieldType, signed int, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_field_info<StateFieldType, unsigned char, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_field_info<StateFieldType, signed char, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_field_info<StateFieldType, float, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_field_info<StateFieldType, double, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_vector_field_info<StateFieldType, float, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_vector_field_info<StateFieldType, double, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, bool, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, gps_time_t, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, f_quat_t, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, lin::Vector4f, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, d_quat_t, StateFieldBaseType>(field, field_info); found_field_type |= try_collect_unbounded_field_info<StateFieldType, lin::Vector4d, StateFieldBaseType>(field, field_info); if(!found_field_type) { std::cout << "Could not find field type for field: " << field->name() << std::endl; assert(false); } return field_info; } json get_writable_field_info(const WritableStateFieldBase* field) { json field_info = get_field_info<WritableStateField, WritableStateFieldBase>(field); field_info["writable"] = true; return field_info; } json get_readable_field_info(const ReadableStateFieldBase* field) { json field_info = get_field_info<ReadableStateField, ReadableStateFieldBase>(field); field_info["writable"] = false; return field_info; } /************** End helper functions. ***********/ json TelemetryInfoGenerator::generate_telemetry_info() { json ret; // Get field data ret["fields"] = json::object(); for(const WritableStateFieldBase* wf : r.writable_fields) { const std::string& field_name = wf->name(); if (ret["fields"].find(field_name) != ret["fields"].end()) continue; ret["fields"][field_name] = get_writable_field_info(wf); if (wf->eeprom_save_period() > 0) ret["eeprom_saved_fields"][field_name] = wf->eeprom_save_period(); } for(const ReadableStateFieldBase* rf : r.readable_fields) { const std::string& field_name = rf->name(); if (ret["fields"].find(field_name) != ret["fields"].end()) continue; ret["fields"][field_name] = get_readable_field_info(rf); if (rf->eeprom_save_period() > 0) ret["eeprom_saved_fields"][field_name] = rf->eeprom_save_period(); } // Get flow data ret["flows"] = json::array(); for(size_t i = 0; i < flow_data.size(); i++) { const DownlinkProducer::FlowData& f = flow_data[i]; ret["flows"].push_back({ {"id", f.id}, {"priority", i}, {"fields", f.field_list}, {"active", f.is_active} }); for (const std::string& field_name : f.field_list) { ret["fields"][field_name]["flow_id"] = f.id; } } for(auto& field : ret["fields"]) { if (field.find("flow_id") == field.end()) field["flow_id"] = "undefined"; } return ret; }
46.418478
127
0.693127
[ "object", "vector" ]
3fb241d39af3ce99f7a3a8d7487f20f9ac193fff
2,271
cpp
C++
aoj/GRL/GRL4A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
aoj/GRL/GRL4A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
aoj/GRL/GRL4A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_A #include <vector> #include <algorithm> class Solver { int N; std::vector<std::vector<int>> adj; public: // O(V) Solver(int size): N(size), adj(size) {} // O(1) int size() { return N; } // O(1) void add_edge(int from, int to) { throw_if_invalid_index(from); throw_if_invalid_index(to); adj[from].push_back(to); } // O(E) bool solve(std::vector<int>& cycle) { std::vector<int> color(N, 0); std::vector<int> parent(N, -1); std::pair<int,int> be; bool found = false; for (int v = 0; v < N; ++v) { if (color[v] != 0) continue; if (dfs(v, color, parent, be)) { found = true; break; } } if (!found) { return false; } cycle.clear(); cycle.push_back(be.first); for (int v = be.second; v != be.first; v = parent[v]) { cycle.push_back(v); } cycle.push_back(be.first); reverse(cycle.begin(), cycle.end()); return true; } private: void throw_if_invalid_index(int index) { if (index < 0 || index >= N) throw "index out of range"; } bool dfs(int v, std::vector<int>& color, std::vector<int>& parent, std::pair<int,int>& be) { color[v] = 1; for (int u : adj[v]) { if (color[u] == 0) { parent[u] = v; if (dfs(u, color, parent, be)) { return true; } } else if (color[u] == 1) { be.first = u; // cycle begin be.second = v; // cycle end return true; } } color[v] = 2; return false; } }; #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int V, E; cin >> V >> E; Solver solver(V); for (int i = 0; i < E; ++i) { int u, v; cin >> u >> v; solver.add_edge(u, v); } vector<int> cycle; bool has_cycle = solver.solve(cycle); cout << (has_cycle ? 1 : 0) << endl; return 0; }
22.939394
96
0.465874
[ "vector" ]
3fb29fe94c9f3065ea2f99a9b2006c5f175a4901
3,703
cpp
C++
NodeVisitor/main.cpp
pfcstyle/osg72
9d3ce7369637807226a2f6c59b55a1162507494b
[ "Apache-2.0" ]
null
null
null
NodeVisitor/main.cpp
pfcstyle/osg72
9d3ce7369637807226a2f6c59b55a1162507494b
[ "Apache-2.0" ]
null
null
null
NodeVisitor/main.cpp
pfcstyle/osg72
9d3ce7369637807226a2f6c59b55a1162507494b
[ "Apache-2.0" ]
null
null
null
#include "../Common/Common.h" #include <iostream> #include <osgViewer/Viewer> #include <osgDB/ReadFile> #include <osg/ShapeDrawable> #include <osg/Geode> #include <osg/Geometry> #ifdef _DEBUG #pragma comment(lib, "../x64/Debug/Commond.lib") #else #pragma comment(lib, "../x64/Release/Common.lib") #endif // _DEBUG /*class VisitorNodePath : public osg::NodeVisitor { public: VisitorNodePath():osg::NodeVisitor(TRAVERSE_PARENTS){} void apply(osg::Node &node) { std::cout<<"Apply node: " << node.getName()<<std::endl; if(node.getName() == "glider") { //Do something } traverse(node); } void apply(osg::Group &group) { std::cout<<"Apply group: " << group.getName()<<std::endl; if(group.getName() == "root") { //Do something } traverse(group); } void apply(osg::MatrixTransform &mt) { std::cout<<"Apply mtransfor:"<<mt.getName()<<std::endl; if(mt.getName()== "child2") { //Do something } traverse(mt); } };*/ osg::ref_ptr<osg::Geode> CreateBox(osg::Vec3Array *va) { osg::ref_ptr<osg::Geode> gnode = new osg::Geode; for (osg::Vec3Array::iterator iter = va->begin(); iter != va->end(); iter++) { gnode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(iter->x(), iter->y(), iter->z()), 0.02, 0.02, 0.02))); } return gnode; } class BoundVisitor : public osg::NodeVisitor { public: void apply(osg::Group &gnode) { for (unsigned i=0; i < gnode.getNumChildren(); i++) { osg::ref_ptr<osg::Node> node = gnode.getChild(i); std::cout << "Apply node: " << node->getName() << std::endl; } } void setGroup(osg::Group *gp) { group = gp; } private: osg::ref_ptr<osg::Group> group; }; int main() { /*osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer; osg::ref_ptr<osg::Group> root = new osg::Group; osg::ref_ptr<osg::Node> glider = osgDB::readNodeFile("glider.osg"); osg::ref_ptr<osg::Node> cow = osgDB::readNodeFile("cow.osg"); osg::ref_ptr<osg::MatrixTransform> child1 = new osg::MatrixTransform; osg::ref_ptr<osg::MatrixTransform> child2 = new osg::MatrixTransform; osg::ref_ptr<osg::MatrixTransform> child3 = new osg::MatrixTransform; osg::ref_ptr<osg::MatrixTransform> child4 = new osg::MatrixTransform; osg::ref_ptr<osg::MatrixTransform> child5 = new osg::MatrixTransform; VisitorNodePath vn; root->setName("root"); glider->setName("glider"); cow->setName("cow"); root->addChild(glider); //root->glider root->addChild(child1); root->addChild(child2); child1->setName("child1"); child1->setMatrix(osg::Matrix::translate(-5, -5, 0)); child1->addChild(glider); child1->addChild(child3); child1->addChild(child4); child2->setName("child2"); child2->setMatrix(osg::Matrix::translate(5, -5, 0)); child2->addChild(glider); child2->addChild(child5); child3->setName("child3"); child3->setMatrix(osg::Matrix::translate(-5, -5, 0)); child3->addChild(cow); child4->setName("child4"); child4->setMatrix(osg::Matrix::translate(5, -5, 0)); child4->addChild(cow); child5->setName("child5"); child5->setMatrix(osg::Matrix::translate(5, -5, 0)); child5->addChild(cow); root->addChild(glider); viewer->setSceneData(root); viewer->addEventHandler(new ChangeWindow()); cow->accept(vn); return viewer->run();*/ osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer; osg::ref_ptr<osg::Node> glider = osgDB::readNodeFile("lz.osgt"); osg::ref_ptr<osg::NodeVisitor> bv = new BoundVisitor; osg::ref_ptr<osg::Group> group = new osg::Group; group->setName("root"); glider->accept(*(bv.get())); glider->setName("glider"); group->addChild(glider); viewer->setSceneData(group); viewer->addEventHandler(new ChangeWindow); return viewer->run(); }
24.852349
121
0.669997
[ "geometry" ]
3fc7b6dd6e4c3d949e234cf7f0e75696a64cb7fb
569
cpp
C++
leetcode/two_sum/leetcode_1.cpp
HuangJingGitHub/PracMakePert_C
94e570c55d9e391913ccd9c5c72026ab926809b2
[ "Apache-2.0" ]
1
2019-10-17T03:13:29.000Z
2019-10-17T03:13:29.000Z
leetcode/two_sum/leetcode_1.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
leetcode/two_sum/leetcode_1.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; unordered_map<int, int> hashMap; for (int i = 0; i < nums.size(); i++){ if (hashMap.find(nums[i]) != hashMap.end()){ res.push_back(hashMap.find(nums[i])->second); res.push_back(i); return res; } hashMap.insert(std::make_pair(target-nums[i], i)); // Instead store the pair (nums[i], i), store (target - nums[i], i) } return res; } };
31.611111
131
0.499121
[ "vector" ]
3fca87906c1c33dd43079a4509e0a47b53a49db7
2,020
cpp
C++
Uncategorized/oly19practice44.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/oly19practice44.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/oly19practice44.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; struct UnionFindBipartite{ vector<int> par, sz; vector<char> parity, odd; void init(int MM){ par.resize(MM); iota(all(par), 0); sz.resize(MM, 1); parity.resize(MM); odd.resize(MM); } pair<int, int> find(int x){ int v = 0; while(x != par[x]){ v ^= parity[x]; x = par[x]; } return {x, v}; } bool merge(int x, int y){ auto [a, va] = find(x); auto [b, vb] = find(y); if(a == b){ if(!odd[a] and va == vb){ odd[a] = 1; return 1; } } else{ if(sz[a] > sz[b]) swap(a, b), swap(va, vb); par[a] = b; sz[b] += sz[a]; odd[b] |= odd[a]; if(va == vb) parity[a] ^= 1; return 1; } return 0; } }; namespace game_of_palindrome{ // https://dmoj.ca/problem/oly19practice44 const int MM = 5005, NN = 5e5+5; vector<int> adj[MM]; int n, m, qu; string s; array<int, 2> e[NN]; bool vis[MM][MM]; queue<pair<int, int>> q; UnionFindBipartite dsu[2]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>m>>qu>>s; s = " "+s; dsu[0].init(MM); dsu[1].init(MM); for(int i = 0,a,b; i < m; i++){ cin>>a>>b; e[i] = {a, b}; bool f = s[a] == s[b]; if(dsu[f].merge(a, b)){ adj[a].emplace_back(b); adj[b].emplace_back(a); } } for(int i = 1; i <= n; i++){ vis[i][i] = 1; q.emplace(i, i); for(int j: adj[i]){ if(s[i] == s[j]){ vis[i][j] = 1; q.emplace(i, j); } } } while(size(q)){ auto [a, b] = q.front(); q.pop(); if(!vis[b][a]){ vis[b][a] = 1; q.emplace(b, a); } for(int c: adj[a]){ for(int d: adj[b]){ if(s[c] == s[d] and !vis[c][d]){ vis[c][d] = 1; q.emplace(c, d); } } } } while(qu--){ int a, b; cin>>a>>b; cout<<(vis[a][b] ? "YES\n" : "NO\n"); } return 0; } } int main(){ game_of_palindrome::main(); }
18.198198
44
0.456931
[ "vector" ]
3fce68bb7ed1e2c058e9b1dfe31065b57d0b8cc3
9,240
cpp
C++
bytesteady/huffman_codec_test.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
3
2021-11-08T19:18:32.000Z
2022-03-06T06:09:58.000Z
bytesteady/huffman_codec_test.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
null
null
null
bytesteady/huffman_codec_test.cpp
ElementAI/bytesteady
737cfc4a5fc0f0ad783ccc70b73200b5e3cef06f
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 ServiceNow * 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 "bytesteady/huffman_codec.hpp" #include <stdio.h> #include <string> #include <queue> #include <vector> #include "gtest/gtest.h" #include "thunder/serializer.hpp" #include "bytesteady/integer.hpp" namespace bytesteady { namespace { TEST(HuffmanCodecTest, constructorTest) { typedef typename HuffmanCodec::size_array size_array; HuffmanCodec codec({1,2,4}); const size_array &gram = codec.gram(); EXPECT_EQ(3, gram.size()); EXPECT_EQ(1, gram[0]); EXPECT_EQ(2, gram[1]); EXPECT_EQ(4, gram[2]); } TEST(HuffmanCodecTest, buildTreesAndTablesTest) { typedef typename HuffmanCodec::byte_array byte_array; typedef typename HuffmanCodec::byte_table byte_table; typedef typename HuffmanCodec::value_table value_table; typedef typename HuffmanCodec::data_callback data_callback; typedef typename HuffmanCodec::node_type node_type; // Build the frequency table ::std::vector< ::std::string > data_array; data_array.push_back("hello world!"); data_array.push_back("bytesteady"); data_array.push_back("text classification and tagging"); int n = 0; data_callback callback = [&](byte_array *input) -> bool { if (n >= data_array.size()) { n = 0; return false; } input->clear(); for (const char &data_char : data_array[n]) { input->push_back(static_cast< uint8_t >(data_char)); } n = n + 1; return true; }; value_table frequency; HuffmanCodec codec({1,2,4}); codec.buildFrequencyFromData(callback, &frequency); // TODO (xiang): check that the frequency table is okay. // for (const typename value_table::value_type &pair : frequency) { // printf("[%s]: %g\n", pair.first.c_str(), pair.second); // } // Build the decoder tree node_type tree{::std::string(), 0.0, nullptr, nullptr}; codec.buildTreeFromFrequency(frequency, &tree); ::std::queue< const node_type* > queue; queue.push(&tree); // Breadth-first order while (!queue.empty()) { const node_type *node = queue.front(); queue.pop(); if (node->left.get() != nullptr) { queue.push(node->left.get()); } if (node->right.get() != nullptr) { queue.push(node->right.get()); } // TODO (xiang): check that the current node is okay. // printf("[%s]: %g\n", node->key.c_str(), node->value); } // Build the encoder table byte_table table; codec.buildTableFromTree(tree, &table); // TODO (xiang): check that the byte table is okay. // for (const typename byte_table::value_type &pair : table) { // printf("[%s]: ", pair.first.c_str()); // for (const uint8_t bit : pair.second) { // printf("%d", bit); // } // printf("\n"); // } // Build decoder tree from the encoder table node_type second_tree; codec.buildTreeFromTable(frequency, table, &second_tree); ::std::queue< const node_type *> first_queue; ::std::queue< const node_type *> second_queue; first_queue.push(&tree); second_queue.push(&second_tree); while (!first_queue.empty()) { const node_type *first_node = first_queue.front(); first_queue.pop(); const node_type *second_node = second_queue.front(); second_queue.pop(); if (first_node->left.get() != nullptr) { first_queue.push(first_node->left.get()); ASSERT_NE(nullptr, second_node->left.get()); second_queue.push(second_node->left.get()); } else { EXPECT_EQ(nullptr, second_node->left.get()); } if (first_node->right.get() != nullptr) { first_queue.push(first_node->right.get()); ASSERT_NE(nullptr, second_node->right.get()); second_queue.push(second_node->right.get()); } else { EXPECT_EQ(nullptr, second_node->right.get()); } EXPECT_EQ(first_node->key, second_node->key); EXPECT_FLOAT_EQ(first_node->value, second_node->value); } } TEST(HuffmanCodecTest, encodeDecodeTest) { typedef typename HuffmanCodec::byte_array byte_array; typedef typename HuffmanCodec::data_callback data_callback; typedef typename HuffmanCodec::size_type size_type; // Build the encoder and decoder tables and trees. ::std::vector< ::std::string > data_array; data_array.push_back("hello world!"); data_array.push_back("bytesteady"); data_array.push_back("text classification and tagging"); int n = 0; data_callback callback = [&](byte_array *input) -> bool { if (n >= data_array.size()) { n = 0; return false; } input->clear(); for (const char &data_char : data_array[n]) { input->push_back(static_cast< uint8_t >(data_char)); } n = n + 1; return true; }; HuffmanCodec codec({1,2,4}); codec.build(callback); // Test for data in the dictionary for (const ::std::string &data_string : data_array) { byte_array data_input; for (const char &data_char : data_string) { data_input.push_back(static_cast< const uint8_t >(data_char)); } byte_array data_encoded; codec.encode(data_input, &data_encoded); byte_array data_decoded; codec.decode(data_encoded, &data_decoded); EXPECT_EQ(data_input.size(), data_decoded.size()); for (size_type i = 0; i < data_input.size(); ++i) { EXPECT_EQ(data_input[i], data_decoded[i]); } } // Test for data outside of the dictionary ::std::string data_string("A quick brown fox jumps over the lazy dog."); byte_array data_input; for (const char &data_char : data_string) { data_input.push_back(static_cast< const uint8_t >(data_char)); } byte_array data_encoded; codec.encode(data_input, &data_encoded); byte_array data_decoded; codec.decode(data_encoded, &data_decoded); EXPECT_GE(data_input.size(), data_encoded.size()); EXPECT_GE(data_input.size(), data_decoded.size()); // Test that the decoded sequence is a subsequence of input size_type data_decoded_index = 0; for (const uint8_t byte : data_input) { ASSERT_GE(data_decoded.size(), data_decoded_index); if (data_decoded_index < data_decoded.size() && byte == data_decoded[data_decoded_index]) { data_decoded_index = data_decoded_index + 1; } } EXPECT_EQ(data_decoded.size(), data_decoded_index); } TEST(HuffmanCodecTest, saveLoadTest) { typedef typename HuffmanCodec::byte_array byte_array; typedef typename HuffmanCodec::byte_table byte_table; typedef typename HuffmanCodec::data_callback data_callback; typedef typename HuffmanCodec::size_array size_array; typedef typename HuffmanCodec::value_table value_table; // Build the encoder and decoder tables and trees. ::std::vector< ::std::string > data_array; data_array.push_back("hello world!"); data_array.push_back("bytesteady"); data_array.push_back("text classification and tagging"); int n = 0; data_callback callback = [&](byte_array *input) -> bool { if (n >= data_array.size()) { n = 0; return false; } input->clear(); for (const char &data_char : data_array[n]) { input->push_back(static_cast< uint8_t >(data_char)); } n = n + 1; return true; }; HuffmanCodec codec1({1,2,4}); codec1.build(callback); // Serialize it ::thunder::StringBinarySerializer serializer; serializer.save(codec1); // Create another codec HuffmanCodec codec2({1,2}); codec2.build(callback); // Load codec serializer.load(&codec2); // Check the gram const size_array &gram1 = codec1.gram(); const size_array &gram2 = codec2.gram(); ASSERT_EQ(gram1.size(), gram2.size()); for (typename size_array::size_type i = 0; i < gram1.size(); ++i) { EXPECT_EQ(gram1[i], gram2[i]); } // Check the frequency const value_table &frequency1 = codec1.frequency(); const value_table &frequency2 = codec2.frequency(); EXPECT_EQ(frequency1.size(), frequency2.size()); for (const typename value_table::value_type &pair : frequency1) { ASSERT_NE(frequency2.end(), frequency2.find(pair.first)); EXPECT_FLOAT_EQ(pair.second, frequency2.at(pair.first)); } // Check the encoder table const byte_table &table1 = codec1.table(); const byte_table &table2 = codec2.table(); EXPECT_EQ(table1.size(), table2.size()); for (const typename byte_table::value_type &pair : table1) { ASSERT_NE(table2.end(), table2.find(pair.first)); const byte_array &bytes1 = pair.second; const byte_array &bytes2 = table2.at(pair.first); ASSERT_EQ(bytes1.size(), bytes2.size()); for (typename byte_array::size_type i = 0; i < bytes1.size(); ++i) { EXPECT_EQ(bytes1[i], bytes2[i]); } } } } // namespace } // namespace bytesteady
33.478261
75
0.674134
[ "vector" ]
3fd6088a4434aead9fc573a4470b91a3de4b4004
2,616
hpp
C++
dynamic_vino_lib/include/dynamic_vino_lib/outputs/ros_service_output.hpp
ashutoshtiwari13/ros2_openvino_toolkit
9de934a5aee3592da00eb0135c3293f22a33cbe1
[ "Apache-2.0" ]
null
null
null
dynamic_vino_lib/include/dynamic_vino_lib/outputs/ros_service_output.hpp
ashutoshtiwari13/ros2_openvino_toolkit
9de934a5aee3592da00eb0135c3293f22a33cbe1
[ "Apache-2.0" ]
1
2021-02-24T10:19:46.000Z
2021-02-24T10:19:46.000Z
dynamic_vino_lib/include/dynamic_vino_lib/outputs/ros_service_output.hpp
ashutoshtiwari13/ros2_openvino_toolkit
9de934a5aee3592da00eb0135c3293f22a33cbe1
[ "Apache-2.0" ]
1
2019-07-23T07:19:29.000Z
2019-07-23T07:19:29.000Z
// Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @brief A header file with declaration for RosTopicOutput Class * @file ros_topic_output.h */ #ifndef DYNAMIC_VINO_LIB__OUTPUTS__ROS_SERVICE_OUTPUT_HPP_ #define DYNAMIC_VINO_LIB__OUTPUTS__ROS_SERVICE_OUTPUT_HPP_ #include <object_msgs/msg/object.hpp> #include <object_msgs/msg/object_in_box.hpp> #include <object_msgs/msg/objects_in_boxes.hpp> #include <people_msgs/msg/emotion.hpp> #include <people_msgs/msg/emotions_stamped.hpp> #include <people_msgs/msg/age_gender.hpp> #include <people_msgs/msg/age_gender_stamped.hpp> #include <people_msgs/msg/head_pose.hpp> #include <people_msgs/msg/head_pose_stamped.hpp> #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/header.hpp> #include <memory> #include <string> #include <vector> #include "dynamic_vino_lib/inferences/face_detection.hpp" #include "dynamic_vino_lib/outputs/ros_topic_output.hpp" namespace Outputs { /** * @class RosServiceOutput * @brief This class handles and publish the detection result for service calling. */ class RosServiceOutput : public RosTopicOutput { public: explicit RosServiceOutput(std::string output_name) : RosTopicOutput(output_name) {} /** * @brief Publish all the detected infomations generated by the accept * functions with ros topic. */ void handleOutput() override {} void clearData() override; void setServiceResponse(std::shared_ptr<object_msgs::srv::DetectObject::Response> response); void setResponseForFace(std::shared_ptr<object_msgs::srv::DetectObject::Response> response); void setServiceResponse(std::shared_ptr<people_msgs::srv::AgeGenderSrv::Response> response); void setServiceResponse(std::shared_ptr<people_msgs::srv::EmotionSrv::Response> response); void setServiceResponse(std::shared_ptr<people_msgs::srv::HeadPoseSrv::Response> response); void setServiceResponse(std::shared_ptr<people_msgs::srv::People::Response> response); private: const std::string service_name_; }; } // namespace Outputs #endif // DYNAMIC_VINO_LIB__OUTPUTS__ROS_SERVICE_OUTPUT_HPP_
35.835616
94
0.782492
[ "object", "vector" ]
684b90877a7bdc5441214086e1963f7d5d77f734
6,851
cpp
C++
p3/tests/CellID_test.cpp
rolandomar/stheno
6b41f56f25be1e7d56c8be4973203bf943e4f041
[ "Apache-2.0" ]
7
2015-08-17T16:24:22.000Z
2022-03-16T15:54:19.000Z
p3/tests/CellID_test.cpp
rolandomar/stheno
6b41f56f25be1e7d56c8be4973203bf943e4f041
[ "Apache-2.0" ]
null
null
null
p3/tests/CellID_test.cpp
rolandomar/stheno
6b41f56f25be1e7d56c8be4973203bf943e4f041
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 Rolando Martins, CRACS & INESC-TEC, DCC/FCUP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * File: Runtime.cpp * Author: Rolando Martins (rolando.martins@gmail.com) * * Created on May 10, 2010, 1:00 PM */ #include "CellID_test.h" CPPUNIT_TEST_SUITE_REGISTRATION(CellID_test); #include <stheno/Stheno.h> #include <stdio.h> #include <euryale/common/uuid/UUID.h> #include <stheno/core/p2p/p3/superpeer/cell/CellID.h> #include <ace/String_Base.h> #include <stheno/core/p2p/p3/superpeer/cell/CellTree.h> CellID_test::CellID_test() { } CellID_test::~CellID_test() { } void CellID_test::setUp() { } void CellID_test::tearDown() { } void CellID_test::testMethod() { //Stheno runtime; ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)\nruntimeTest\n"))); //CellID* root = new CellID(CellID::ROOT_CELL_ID_STR); CellID* root = new CellID(CellID::INVALID_ID_STR); //CellIDPtr rootCellID(root); UUIDPtr rootCellID(root); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)\nruntimeTest2\n"))); //CellTree tree(CellID::ROOT_CELL_ID); CellTree tree(CellID::INVALID_CELL_ID); CellTreeNode* temp = 0; CellTreeNode* node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); temp = node; ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); node = tree.createCell(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%@)\n"), node)); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)node(%s)\n"), node->getCellID()->toString().c_str())); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)\n\n\n"))); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Tree:\n%s"), tree.toStringPerLevel().c_str())); CellTreeNode* removeNode = tree.removeCell(temp->getCellID()); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)oldNode=%s\n"), removeNode->toString().c_str())); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)removed=%@\n"), removeNode)); delete removeNode; ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Tree:\n%s"), tree.toStringPerLevel().c_str())); UUIDPtr pid1(UUID::generateUUID()); UUIDPtr fid(UUID::generateUUID()); EndpointPtr cellEndpoint; SAPInfoPtr meshSAP; SAPInfoPtr discoverySAP; SAPInfoPtr ftSAP; P3PeerInfo *pee1 = new P3PeerInfo(P3PeerInfo::SUPERPEER, pid1, fid, cellEndpoint,meshSAP, discoverySAP, ftSAP); UUIDPtr pid2(UUID::generateUUID()); P3PeerInfo *pee2 = new P3PeerInfo(P3PeerInfo::SUPERPEER, pid2, fid, cellEndpoint,meshSAP, discoverySAP, ftSAP); UUIDPtr pid3(UUID::generateUUID()); P3PeerInfo *pee3 = new P3PeerInfo(P3PeerInfo::SUPERPEER, pid3, fid, cellEndpoint,meshSAP, discoverySAP, ftSAP); /*CellTreeNode *addNode = 0; addNode = tree.addPeer(pee1); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)addNOde=%s\n", addNode->getCellID()->toString().c_str()); addNode = tree.addPeer(pee2); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)addNOde=%s\n", addNode->getCellID()->toString().c_str()); addNode = tree.addPeer(pee3); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)addNOde=%s\n", addNode->getCellID()->toString().c_str());*/ /*UUID uuid("00000000000000000000000000000000"); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)->%s\n",uuid.toString().c_str()); CellID id("01000000000000000000000000000000"); CellID id2("02000000000000000000000000000000"); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)DEPTH=%d char_at_depth=%d\n",id.getCellDepth(),id.getCellSpan(id.getCellDepth())); vector<int> lvls; id.getCellLevels(lvls); //for(int i=0; i < lvls.size(); i++){ //ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Lvl[%d]=%d\n",i,lvls[i]); //} CellID* next = id.getNextGroupID_2(); CellID* next2 = next->getNextGroupID_2(); CellID* next3 = next2->getNextGroupID_2(); CellID* next4 = next3->getNextGroupID_2(); CellID* next5 = next4->getNextGroupID_2(); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Next 0=%s 1=%s 2=%s 3=%s 4=%s 5=%s\n", id.toString().c_str(),next->toString().c_str(),next2->toString().c_str(),next3->toString().c_str(), next4->toString().c_str(),next5->toString().c_str()); CellID* parent = id.getParentGroupID(); bool isDescent = id.belongsToCellTree(&id2); if(parent != 0){ ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)ID=%s parent=%s isDescent=%d\n",id.toString().c_str(),parent->toString().c_str(),isDescent); }else{ ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)ID=%s parent=0 isDescent=%d\n",id.toString().c_str(),isDescent); } delete next; delete next2; delete next3; delete next4; delete next5; if(parent != 0) delete parent; UUID uuid2("094c57041a707dc479c86059be42ac34"); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)->%s\n",uuid2.toString().c_str()); */ CPPUNIT_ASSERT(true); }
40.064327
137
0.64954
[ "vector" ]
68604ac82c8a1f93ed03ce8305fcb87e30119cb5
15,529
cpp
C++
aidigger/libdigger/src/join_pics.cpp
MatrixAINetwork/Matrix_GPU_Mining_jerry
c3c44a6cdeeb83a886236e55c89cd5a76ecc2e7d
[ "MIT" ]
2
2021-06-27T16:09:35.000Z
2021-06-29T13:09:12.000Z
aidigger/libdigger/src/join_pics.cpp
MatrixAINetwork/Matrix_GPU_Mining_jerry
c3c44a6cdeeb83a886236e55c89cd5a76ecc2e7d
[ "MIT" ]
2
2021-03-09T18:47:07.000Z
2021-05-10T15:43:01.000Z
aidigger/libdigger/src/join_pics.cpp
MatrixAINetwork/Matrix_GPU_Mining_jerry
c3c44a6cdeeb83a886236e55c89cd5a76ecc2e7d
[ "MIT" ]
3
2021-06-29T13:09:13.000Z
2022-01-22T07:02:24.000Z
#define cimg_use_jpeg #include "join_pics.h" #include <stdio.h> #include <tuple> #include <vector> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <iostream> #include <chrono> #include "CImg.h" #include "sclog4c/sclog4c.h" using namespace cimg_library; CImg<unsigned char> imgs[16]; std::vector<int> gen_rand_list(int list_size, int max_value){ std::vector<int> rand_list; for(int j = 0; j < list_size; j++){ int r = rand()%max_value; rand_list.push_back(r); } return rand_list; } std::vector<std::tuple<int,int,int,int>> cal_anker_points(int img_size_x, int img_size_y, int divide_x, int divide_y, bool rand_axis_is_x = false){ std::vector<std::tuple<int,int,int,int>> anker_points; if(!rand_axis_is_x){ int step_x = img_size_x/divide_x; int anker_x = 0; int tile_size_x = step_x; for(int i = 0; i < divide_x; i++){ std::vector<int> rand_list = gen_rand_list(divide_y,10); int sum = 0; for(int r : rand_list){ r = r + 1; //plus 1 for avoiding divide zero //logm(SL4C_DEBUG, "r is %d\n", r); sum += r; } std::vector<int> anker_y_list; int sum_so_far = 0; //logm(SL4C_DEBUG, "sum is %d", sum); for(int r: rand_list){ r = r + 1; int anker_y = int(sum_so_far * img_size_y/sum); int tile_size_y = r * img_size_y/sum; anker_points.push_back(std::make_tuple(anker_x,anker_y,tile_size_x,tile_size_y)); sum_so_far += r; } anker_x += step_x; } } else{ int step_y = img_size_y/divide_y; int anker_y = 0; int tile_size_y = step_y; for(int i = 0; i < divide_y; i++){ std::vector<int> rand_list = gen_rand_list(divide_x,10); int sum = 0; for(int r : rand_list){ r = r + 1; sum += r; //plus 1 for avoiding divide zero; } std::vector<int> anker_x_list; int sum_so_far = 0; for(int r: rand_list){ r = r + 1; int anker_x = int(sum_so_far * img_size_x/sum); int tile_size_x = r * img_size_x/sum; anker_points.push_back(std::make_tuple(anker_x,anker_y, tile_size_x,tile_size_y)); sum_so_far += r; } anker_y += step_y; } } return anker_points; } void fill_image_with_image(CImg<unsigned char>& dest,CImg<unsigned char>& source, int anker_x = 0, int anker_y = 0){ const double bb_x_lu = anker_x, bb_y_lu = anker_y, bb_x_rd = anker_x + source.width(), bb_y_rd = anker_y + source.height(); int dx = source.width(), dy = source.height(), dz = std::max(dest.depth(),source.depth()), dv = std::max(dest.spectrum(),source.spectrum()); source.resize(dx,dy,dz,dv); //static_assert(bb_x_rd < dest.width() && bb_y_rd < dest.height()); cimg_forXYZC(dest,x,y,z,k) { if (x >= bb_x_lu && x <= bb_x_rd && y >= bb_y_lu && y <= bb_y_rd){ dest(x,y,z,k) = source(x - bb_x_lu, y - bb_y_lu,z,k); } } } bool has_suffix(const std::string &str, const std::string &suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } std::vector<std::string> choose_image(const char* path, int img_number){ std::vector<std::string> chose_img_names; DIR *dir = opendir(path); char buff[256]; struct dirent *dp; int pic_count = 0; std::vector<std::string> img_names; while ((dp = readdir(dir)) != NULL) { char* absFilename = buff; strcpy(absFilename,path); strcat(absFilename,dp->d_name); if(!has_suffix(absFilename,".jpg")) continue; img_names.push_back(absFilename); pic_count++; } printf("pic count is %d\n", pic_count); std::vector<int> rand_list = gen_rand_list(img_number, pic_count); for(auto r:rand_list){ chose_img_names.push_back(img_names.at(r)); } return chose_img_names; } CImg<unsigned char> get_rand_crop(const CImg<unsigned char>& img, int crop_size_x, int crop_size_y){ int rand_anker_x = rand()%(img.width()-crop_size_x); int rand_anker_y = rand()%(img.height()-crop_size_y); CImg<unsigned char> tmp_img(img); while((rand_anker_x+crop_size_x > tmp_img.width())||(rand_anker_y + crop_size_y > tmp_img.height())) tmp_img = tmp_img.get_resize_doubleXY(); return tmp_img.get_crop(rand_anker_x,rand_anker_y,rand_anker_x+crop_size_x, rand_anker_y + crop_size_y); } CImg<unsigned char> rand_join_pics(int dest_size_x, int dest_size_y, int divide_x, int divide_y,const char* pic_paths){ CImg<unsigned char> dest(dest_size_x,dest_size_y,3,3); std::vector<std::tuple<int,int,int,int>> anker_points = cal_anker_points(dest_size_x,dest_size_y,divide_x,divide_y); std::vector<std::string> img_names = choose_image(pic_paths, anker_points.size()); int pic_id = 0; for(auto anker_point:anker_points){ std::string pic_name = img_names.at(pic_id); CImg<unsigned char> source; source.load_jpeg(pic_name.c_str()); //source.display("emmm"); int anker_x = std::get<0>(anker_point), anker_y = std::get<1>(anker_point), crop_x = std::get<2>(anker_point), crop_y = std::get<3>(anker_point); //std::cout<<"anker_x "<<anker_x<<" anker_y "<<anker_y<<" size_x "<<crop_x<<" crop_y "<<crop_y<<std::endl; CImg<unsigned char> crop = get_rand_crop(source,crop_x,crop_y); //crop.display("crop"); fill_image_with_image(dest,crop,anker_x,anker_y); pic_id++; } return dest; } #ifdef __cplusplus extern "C" { #endif #define PICS_PATH "" int load_16_imgs(const char** picNames){ try{ printf("loading pics\n"); char buff[256]; const char* path = PICS_PATH; for (int i = 0; i < 16; i++){ char* absFilename = buff; strcpy(absFilename,path); const char* picName_chars = picNames[i]; strcat(absFilename,picName_chars); CImg<unsigned char>* source = &imgs[i]; source->load_jpeg(absFilename); } printf("finished loading pics\n"); return 1; } catch(...){ return 0; } } int join_16_pics(long rand_seed, const char** picNames,int join_pic_sizex, int join_pic_sizey, const char* join_pic_name){ srand(rand_seed); try{ logm(SL4C_DEBUG,"begin join join 16 pic for %s\n", join_pic_name); auto begin = std::chrono::high_resolution_clock::now(); CImg<unsigned char> dest(join_pic_sizex,join_pic_sizey,3,3); logm(SL4C_DEBUG,"cal ankers pic for %s\n", join_pic_name); std::vector<std::tuple<int,int,int,int>> anker_points = cal_anker_points(join_pic_sizex,join_pic_sizey,4,4); int pic_id = 0; char buff[256]; const char* path = PICS_PATH; logm(SL4C_DEBUG,"fill image with images for %s\n", join_pic_name); for(auto anker_point:anker_points){ CImg<unsigned char> *source = &imgs[rand()%16]; int anker_x = std::get<0>(anker_point), anker_y = std::get<1>(anker_point), crop_x = std::get<2>(anker_point), crop_y = std::get<3>(anker_point); //std::cout<<"anker_x "<<anker_x<<" anker_y "<<anker_y<<" size_x "<<crop_x<<" crop_y "<<crop_y<<std::endl; CImg<unsigned char> crop = get_rand_crop(*source,crop_x,crop_y); //crop.display("crop"); fill_image_with_image(dest,crop,anker_x,anker_y); pic_id++; } logm(SL4C_DEBUG,"saving pic for %s\n", join_pic_name); dest.save(join_pic_name); //dest.display("result"); // auto end = std::chrono::high_resolution_clock::now(); // auto dur = end - begin; // auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count(); // std::cout << "finished joining pic in "<<ms <<" ms"<< std::endl; logm(SL4C_DEBUG, "returning join pic function for %s\n", join_pic_name); return 1; } catch(...){ return 0; } } int join_pics(long rand_seed, int width,int height,int divide_x,int divide_y,const char* pics_path, const char* join_pic_name){ srand(rand_seed); auto begin = std::chrono::high_resolution_clock::now(); CImg<unsigned char> result = rand_join_pics(width,height,divide_x,divide_y,pics_path); auto end = std::chrono::high_resolution_clock::now(); auto dur = end - begin; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count(); std::cout << "finished in "<<ms <<" ms"<< std::endl; char buff[256]; result.save(join_pic_name); result.display(); return 1; } #ifdef __cplusplus } // extern "C" #endif
57.514815
6,116
0.351278
[ "vector" ]
68666168d21eb443eac72a75f5c72a0222c38ee6
9,484
hxx
C++
main/forms/source/component/Button.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/forms/source/component/Button.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/forms/source/component/Button.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _FRM_BUTTON_HXX_ #define _FRM_BUTTON_HXX_ #include "clickableimage.hxx" #include "togglestate.hxx" #include "formnavigation.hxx" #include "resettable.hxx" #include <com/sun/star/awt/MouseEvent.hpp> #include <com/sun/star/lang/EventObject.hpp> #include <com/sun/star/awt/ActionEvent.hpp> #include <com/sun/star/awt/XActionListener.hpp> #include <com/sun/star/awt/XButton.hpp> #include <com/sun/star/form/XReset.hpp> #include <com/sun/star/beans/PropertyChangeEvent.hpp> #include <cppuhelper/implbase1.hxx> //......................................................................... namespace frm { //......................................................................... //================================================================== // OButtonModel //================================================================== typedef ::cppu::ImplHelper1 < ::com::sun::star::form::XReset > OButtonModel_Base; class OButtonModel :public OClickableImageBaseModel ,public OButtonModel_Base { public: DECLARE_DEFAULT_LEAF_XTOR( OButtonModel ); // UNO DECLARE_UNO3_AGG_DEFAULTS( OButtonModel, OClickableImageBaseModel ); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw(::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OButtonModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::io::XPersistObject virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); // XReset virtual void SAL_CALL reset( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addResetListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XResetListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeResetListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XResetListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; // XPropertySet and friends virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const; virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception); virtual sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::lang::IllegalArgumentException); virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const; // OComponentHelper virtual void SAL_CALL disposing(); protected: DECLARE_XCLONEABLE(); private: void impl_resetNoBroadcast_nothrow(); using ::cppu::OPropertySetHelper::getFastPropertyValue; private: ResetHelper m_aResetHelper; // <properties> ToggleState m_eDefaultState; // the default check state // </properties> protected: using OClickableImageBaseModel::disposing; }; //================================================================== // OButtonControl //================================================================== typedef ::cppu::ImplHelper3 < ::com::sun::star::awt::XButton , ::com::sun::star::awt::XActionListener , ::com::sun::star::beans::XPropertyChangeListener > OButtonControl_BASE; class OButtonControl :public OButtonControl_BASE ,public OClickableImageBaseControl ,public OFormNavigationHelper { private: sal_uLong m_nClickEvent; sal_Int16 m_nTargetUrlFeatureId; /// caches the value of the "Enabled" property of our model sal_Bool m_bEnabledByPropertyValue; protected: // UNO Anbindung virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); public: OButtonControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OButtonControl(); // XServiceInfo IMPLEMENTATION_NAME(OButtonControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // UNO Anbindung DECLARE_UNO3_AGG_DEFAULTS(OButtonControl, OClickableImageBaseControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); // XActionListener virtual void SAL_CALL actionPerformed(const ::com::sun::star::awt::ActionEvent& rEvent) throw ( ::com::sun::star::uno::RuntimeException); // XButton virtual void SAL_CALL addActionListener(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XActionListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeActionListener(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XActionListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLabel(const ::rtl::OUString& Label) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setActionCommand(const ::rtl::OUString& _rCommand) throw(::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(); // XPropertyChangeListener virtual void SAL_CALL propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // XControl virtual sal_Bool SAL_CALL setModel( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& _rxModel ) throw ( ::com::sun::star::uno::RuntimeException ); void SAL_CALL setDesignMode(sal_Bool bOn) throw (::com::sun::star::uno::RuntimeException); protected: // OFormNavigationHelper overriables virtual void getSupportedFeatures( ::std::vector< sal_Int16 >& /* [out] */ _rFeatureIds ); virtual void featureStateChanged( sal_Int16 _nFeatureId, sal_Bool _bEnabled ); virtual void allFeatureStatesChanged( ); virtual bool isEnabled( sal_Int16 _nFeatureId ) const; // XDispatchProviderInterception disambiguaiton virtual void SAL_CALL registerDispatchProviderInterceptor( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterceptor >& Interceptor ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL releaseDispatchProviderInterceptor( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterceptor >& Interceptor ) throw (::com::sun::star::uno::RuntimeException); // OImageControl overridables virtual void actionPerformed_Impl( sal_Bool bNotifyListener, const ::com::sun::star::awt::MouseEvent& _rEvt ); private: DECL_LINK( OnClick, void* ); /** to be called whenever the feature URL represented by our model has potentially changed */ void modelFeatureUrlPotentiallyChanged( ); /** retrieves the feature id (see OFormNavigationHelper) of the TargetURL of the model. */ sal_Int16 getModelUrlFeatureId( ) const; /** starts or stops listening for changes in model properties we're interested in */ void startOrStopModelPropertyListening( bool _bStart ); }; //......................................................................... } // namespace frm //......................................................................... #endif // _FRM_BUTTON_HXX_
45.816425
222
0.658477
[ "vector", "model" ]
686aba1642de16fbeb62ade78cf3ee7c14936d2c
3,620
hpp
C++
src/MSRControlImp.hpp
RyoTTa/geopm
74246c8ce70ee47f53bc5629638f51c2c391027b
[ "BSD-3-Clause" ]
null
null
null
src/MSRControlImp.hpp
RyoTTa/geopm
74246c8ce70ee47f53bc5629638f51c2c391027b
[ "BSD-3-Clause" ]
null
null
null
src/MSRControlImp.hpp
RyoTTa/geopm
74246c8ce70ee47f53bc5629638f51c2c391027b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MSRCONTROLIMP_HPP_INCLUDE #define MSRCONTROLIMP_HPP_INCLUDE #include "MSRControl.hpp" namespace geopm { class MSRControlImp : public MSRControl { public: /// @brief Constructor for the MSRControlImp class used when the /// control is enforced with a single bit field in a /// single MSR. /// @param [in] msr_obj Pointer to the MSR object /// describing the MSR that contains the control. /// @param [in] cpu_idx The logical Linux CPU index to /// write the MSR. /// @param [in] control_idx The index of the control within /// the MSR that the class represents. MSRControlImp(const MSR &msr_obj, int domain_type, int cpu_idx, int control_idx); std::unique_ptr<MSRControl> copy_and_remap(uint64_t *field, uint64_t *mask) const override; virtual ~MSRControlImp(); virtual std::string name(void) const override; int domain_type(void) const override; int cpu_idx(void) const override; void adjust(double setting) override; uint64_t offset(void) const override; uint64_t mask(void) const override; void map_field(uint64_t *field, uint64_t *mask) override; private: // Copying is disallowed except through copy_and_remap() method MSRControlImp(const MSRControlImp &other); MSRControlImp &operator=(const MSRControlImp &other) = default; const std::string m_name; const MSR &m_msr_obj; const int m_domain_type; const int m_cpu_idx; const int m_control_idx; uint64_t *m_field_ptr; uint64_t *m_mask_ptr; bool m_is_field_mapped; }; } #endif
43.614458
86
0.645856
[ "object" ]
686fd0a851ac61dd111e1cbabab3c71d225995df
4,245
cpp
C++
wxdraw/gui/Canvas.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/gui/Canvas.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/gui/Canvas.cpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
#include "wxdraw/component/ContainerComponent.hpp" #include "wxdraw/component/LayoutComponent.hpp" #include "wxdraw/component/ViewComponent.hpp" #include "wxdraw/gui/Canvas.hpp" #include "wxdraw/gui/MainFrame.hpp" #include "wxdraw/gui/Outliner.hpp" #include "wxdraw/gui/Renderer.hpp" #include "wxdraw/node/Node.hpp" namespace wxdraw::gui { wxBrush Canvas::BackgroundBrush; /** コンストラクタ @param parent 親 @param mainFrame メインフレーム */ Canvas::Canvas(wxWindow* parent, MainFrame* mainFrame) : super(parent), mainFrame_(mainFrame), offset_(0.0), zoom_(1.0) { SetDoubleBuffered(true); Bind(wxEVT_LEFT_DOWN, &Canvas::onLeftDown, this); Bind(wxEVT_MOTION, &Canvas::onMotion, this); Bind(wxEVT_MOUSEWHEEL, &Canvas::onMouseWheel, this); Bind(wxEVT_RIGHT_DOWN, &Canvas::onRightDown, this); } /** */ const wxBrush& Canvas::GetBackgroundBrush() { const int SIZE = 8; const wxColour C1(0x70, 0x70, 0x70); const wxColour C2(0x90, 0x90, 0x90); if(!BackgroundBrush.IsOk()) { wxImage image(SIZE * 2, SIZE * 2); for(int x = 0; x < 2; x++) { for(int y = 0; y < 2; y++) { wxRect rect(wxPoint(SIZE * x, SIZE * y), wxSize(SIZE, SIZE)); if(((x + y) & 1) == 0) { image.SetRGB(rect, C1.Red(), C1.Green(), C1.Blue()); } else { image.SetRGB(rect, C2.Red(), C2.Green(), C2.Blue()); } } } BackgroundBrush.SetStipple(image); } return BackgroundBrush; } /** 描画 */ void Canvas::OnDraw(wxDC& dc) { super::OnDraw(dc); dc.SetBackground(GetBackgroundBrush()); dc.Clear(); viewNode_ = nullptr; if(auto selectNode = mainFrame_->getOutliner()->getSelectNode()) { if(auto view = Node::GetParentComponent<ViewComponent>(selectNode)) { viewNode_ = view->getNode(); auto size = GetSize(); viewTransform_ = Transform(glm::dvec2(size.GetWidth(), size.GetHeight()), glm::dvec2(zoom_), offset_); Renderer renderer(dc); viewNode_->render(renderer, viewTransform_); drawCursor(renderer, selectNode); } } } /** */ void Canvas::onLeftDown(wxMouseEvent& event) { if(viewNode_) { auto pos = glm::dvec2(event.GetX(), event.GetY()); if(auto node = getNode(viewNode_, viewTransform_, pos)) { mainFrame_->getOutliner()->selectNode(node); } } } /** */ void Canvas::onRightDown(wxMouseEvent& event) { mousePos_ = event.GetPosition(); } /** */ void Canvas::onMotion(wxMouseEvent& event) { auto pos = event.GetPosition(); if(event.RightIsDown()) { offset_ += glm::dvec2(pos.x - mousePos_.x, pos.y - mousePos_.y); Refresh(); } mousePos_ = pos; } /** */ void Canvas::onMouseWheel(wxMouseEvent& event) { if(event.GetWheelRotation() < 0) { zoom_ *= 0.9; } else if(event.GetWheelRotation() > 0) { zoom_ *= 1.1; } Refresh(); } /** 選択中のノードにカーソルを表示する @param renderer レンダラー @param node 選択中のノード */ void Canvas::drawCursor(Renderer& renderer, const NodePtr& node) { auto& context = renderer.getContext(); auto transform = getTransform(node); renderer.setMatrix(transform.matrix); context.SetPen(context.CreatePen(wxGraphicsPenInfo(*wxRED, 0.5))); context.SetBrush(wxNullBrush); auto& rect = transform.rect; context.DrawRectangle(rect.pos.x, rect.pos.y, rect.size.x, rect.size.y); } /** */ NodePtr Canvas::getNode(const NodePtr& node, const Transform& parent, const glm::dvec2& pos) const { auto transform = node->getLayout()->apply(parent); if(auto container = node->getContainer()) { for(auto iter = std::rbegin(container->getChildren()); iter != std::rend(container->getChildren()); iter++) { if(auto found = getNode(*iter, transform, pos)) { return found; } } } auto p = glm::inverse(transform.matrix) * glm::dvec3(pos, 1.0); return transform.rect.isContain(p) ? node : nullptr; } /** */ Transform Canvas::getTransform(const NodePtr& node) const { auto parent = node->getParent(); return node->getLayout()->apply((node == viewNode_ || !parent) ? viewTransform_ : getTransform(parent)); } }
28.3
80
0.623322
[ "render", "transform" ]
68705837d3dea96ff6eae9f0f1cde982c887a700
3,868
hh
C++
libgringo/gringo/input/literal.hh
0x326/clingo
225f1b482ed68797211855db014d18e88d0ddc7b
[ "MIT" ]
1
2018-11-20T10:29:50.000Z
2018-11-20T10:29:50.000Z
libgringo/gringo/input/literal.hh
tsahyt/clingo
5c5a61dc0ac5f54d8245e6c4ec28f6040882b151
[ "MIT" ]
1
2019-08-30T15:34:43.000Z
2019-08-30T16:45:51.000Z
libgringo/gringo/input/literal.hh
tsahyt/clingo
5c5a61dc0ac5f54d8245e6c4ec28f6040882b151
[ "MIT" ]
null
null
null
// {{{ MIT License // Copyright 2017 Roland Kaminski // 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. // }}} #ifndef _GRINGO_INPUT_LITERAL_HH #define _GRINGO_INPUT_LITERAL_HH #include <gringo/term.hh> #include <gringo/domain.hh> #include <gringo/input/types.hh> namespace Gringo { namespace Input { // {{{ declaration of Literal struct Projection { Projection(UTerm &&projected, UTerm &&project); Projection(Projection &&); Projection &operator=(Projection &&); ~Projection(); operator Term const &() const; UTerm projected; UTerm project; bool done = false; }; struct Projections { using ProjectionMap = UniqueVec<Projection, std::hash<Term>, std::equal_to<Term>>; Projections(); Projections(Projections &&x); ProjectionMap::Iterator begin(); ProjectionMap::Iterator end(); ~Projections(); UTerm add(Term &term); ProjectionMap proj; }; struct Literal : Printable, Hashable, Locatable, Comparable<Literal>, Clonable<Literal> { using AssignVec = std::vector<std::pair<UTerm, UTerm>>; virtual unsigned projectScore() const { return 2; } //! Removes all occurrences of PoolTerm instances. //! Returns all unpooled incarnations of the literal. //! \note The literal becomes unusable after the method returns. //! \post The returned pool does not contain PoolTerm instances. virtual ULitVec unpool(bool beforeRewrite) const = 0; //! Simplifies the literal. //! Flag positional=true indicates that anonymous variables in this literal can be projected. //! Flag singleton=true disables projections for positive predicate literals (e.g., in non-monotone aggregates) virtual bool simplify(Logger &log, Projections &project, SimplifyState &state, bool positional = true, bool singleton = false) = 0; //! Collects variables. //! \pre Must be called after simplify to properly account for bound variables. virtual void collect(VarTermBoundVec &vars, bool bound) const = 0; //! Removes non-invertible arithmetics. //! \note This method will not be called for head literals. virtual void rewriteArithmetics(Term::ArithmeticsMap &arith, AssignVec &assign, AuxGen &auxGen) = 0; virtual void toTuple(UTermVec &tuple, int &id) = 0; virtual Symbol isEDB() const; virtual bool hasPool(bool beforeRewrite) const = 0; virtual void replace(Defines &dx) = 0; virtual Ground::ULit toGround(DomainData &x, bool auxiliary) const = 0; virtual ULit shift(bool negate) = 0; virtual UTerm headRepr() const = 0; virtual bool auxiliary() const = 0; virtual void auxiliary(bool auxiliary) = 0; virtual void getNeg(std::function<void (Sig)> f) const = 0; virtual ~Literal() { } }; // }}} } } // namespace Input Gringo GRINGO_HASH(Gringo::Input::Literal) #endif // _GRINGO_INPUT_LITERAL_HH
38.68
135
0.722337
[ "vector" ]
68793ab8684714da71c5db3dfb774ebaa279ee9a
14,542
c++
C++
map.c++
elskater98/tanks-game
5cb0a22547d5e40b54e679bf09af902b8cd35a16
[ "MIT" ]
null
null
null
map.c++
elskater98/tanks-game
5cb0a22547d5e40b54e679bf09af902b8cd35a16
[ "MIT" ]
null
null
null
map.c++
elskater98/tanks-game
5cb0a22547d5e40b54e679bf09af902b8cd35a16
[ "MIT" ]
null
null
null
/* [Additional Information] - Symbol ‘#’ represents a “wall” - Symbol ' ' represents a “corridor” - link of interest: https://pragprog.com/titles/jbmaze/mazes-for-programmers/ */ // Libraries #include <iostream> #include <cmath> #include <GL/glut.h> #include <random> #include <algorithm> // std::random_shuffle #include <vector> //#include "textures.c++" // namespace using namespace std; // constants #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 #define MAX_WALLS_TO_REMOVE 100 class Map { public: int width, height, cell_width; char *array2D; // https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new // initMap void create(int width, int height, int cell_width) { this->width = width; this->height = height; this->cell_width = cell_width; array2D = new char[(int)width * (int)height]; initWalls(); recursiveAlgorithm(1, 1); removeMazeWalls(); } int getPosition(int x, int y) { // Obtain the position representated with single dimension (X*Y) using two-dimensional axis (X,Y).[1,2,3,4,5,6] = [[1,2],[3,4],[5,6]] return x + y * width; } char getWallSymbol() { return WALL_SYMBOL; } char getCorridorSymbol() { return CORRIDOR_SYMBOL; } void print() { cout << "Rows:" << width << " Columns:" << height << "\n\n"; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { cout << array2D[getPosition(i, j)] << " "; // horizontal Print } cout << "\n"; } } // GL/glut display void display() { // Function that loops over map and display each place for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (array2D[getPosition(x, y)] == getWallSymbol()) { displayWall(x, y); } else if (array2D[getPosition(x, y)] == getCorridorSymbol()) { if (x == 1 && y == height - 2) { displayInitialPlayer(x, y); } else if (x == width - 2 && y == 1) { displayInitialEnemy(x, y); } else { displayCorridor(x, y); } } } } } // private class methods private: char WALL_SYMBOL = '#'; char CORRIDOR_SYMBOL = ' '; void initWalls() { std::fill_n(array2D, width * height, WALL_SYMBOL); // set all walls } void recursiveAlgorithm(int x, int y) { // https://stackoverflow.com/questions/38502/whats-a-good-algorithm-to-generate-a-maze // https://hurna.io/academy/algorithms/maze_generator/recursive_division.html // http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking int direction[4] = {UP, RIGHT, DOWN, LEFT}; // shuffle: https://stackoverflow.com/questions/922256/c-array-shuffle std::random_shuffle(direction, direction + (sizeof(direction) / sizeof(direction[0]))); array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; // base // Loop to attempt to visit that direction for (int i = 0; i < 4; i++) { //Initialize aux variables int dx = 0, dy = 0; switch (direction[i]) { case UP: dy = -1; break; case RIGHT: dx = 1; break; case DOWN: dy = 1; break; case LEFT: dx = -1; break; } generatePath(x + dx * 2, y + dy * 2, dx, dy); } } int isBound(int x, int y) { return !(x < 0 || y < 0 || x >= width || y >= height); } void generatePath(int x, int y, int dx, int dy) { if (isBound(x, y) && array2D[getPosition(x, y)] == WALL_SYMBOL) { array2D[getPosition(x - dx, y - dy)] = CORRIDOR_SYMBOL; recursiveAlgorithm(x, y); // restart } } bool removeWall(int x, int y) { // remove wall if possible. bool evenRow = ((y % 2) == 0); bool evenIndex = ((x % 2) == 0); // check if (array2D[getPosition(x, y)] != WALL_SYMBOL) { return false; } if (!evenRow && evenIndex) { // Uneven row and even column bool hasTop = (y - 2 > 0) && (array2D[getPosition(x, y - 2)] == WALL_SYMBOL); bool hasBottom = (y + 2 > 0) && (array2D[getPosition(x, y + 2)] == WALL_SYMBOL); if (hasTop && hasBottom) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } else if (!hasTop && hasBottom) { bool left = (array2D[getPosition(x - 1, y - 1)] == WALL_SYMBOL); bool right = (array2D[getPosition(x + 1, y - 1)] == WALL_SYMBOL); if (left || right) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } } else if (!hasBottom && hasTop) { bool left = (array2D[getPosition(x - 1, y + 1)] == WALL_SYMBOL); bool right = (array2D[getPosition(x + 1, y + 1)] == WALL_SYMBOL); if (left || right) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } } } else if (evenRow && !evenIndex) { // Even row and uneven column bool hasLeft = (array2D[getPosition(x - 2, y)] == WALL_SYMBOL); bool hasRight = (array2D[getPosition(x + 2, y)] == WALL_SYMBOL); if (hasLeft && hasRight) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } else if (!hasLeft && hasRight) { bool top = (array2D[getPosition(x - 1, y - 1)] == WALL_SYMBOL); bool bottom = (array2D[getPosition(x - 1, y + 1)] == WALL_SYMBOL); if (top || bottom) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } } else if (!hasRight && hasLeft) { bool top = (array2D[getPosition(x + 1, y - 1)] == WALL_SYMBOL); bool bottom = (array2D[getPosition(x + 1, y + 1)] == WALL_SYMBOL); if (top || bottom) { array2D[getPosition(x, y)] = CORRIDOR_SYMBOL; return true; } } } return false; } // https://github.com/keesiemeijer/maze-generator void removeMazeWalls() { /*if (!this.removeWalls || !this.matrix.length) { return; }*/ int min = 0; int max = height - 1; int maxTries = MAX_WALLS_TO_REMOVE; int tries = 0; int wallsRemoved = 0; while (tries < maxTries) { tries++; if (wallsRemoved >= maxTries) { // is goal achieved? break; } // Get random row from array2D int y = floor(((float)rand() / (float)RAND_MAX) * (max - min + 1)) + min; if (y == min) { y = y + 1; } else if (y == max) { y = y - 1; } /* * using std:vector instead of array, * to work with it as a STACK when requiring dynamics push * at first the size is not know */ std::vector<int> walls_vector; // fixed y, only saving x coordinate for (int x = 1; x < width - 2; x++) { if (array2D[getPosition(x, y)] == WALL_SYMBOL) { walls_vector.push_back(x); } } // shuffle walls randomly std::random_shuffle(walls_vector.begin(), walls_vector.end()); for (int i = 0; i < walls_vector.size(); i++) { if (removeWall(walls_vector[i], y)) { wallsRemoved++; break; } } } } void displayWall(int x, int y) { // Function that represents the walls glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 2); glBegin(GL_QUADS); glTexCoord2f(-0.25, 0.0); glVertex3i(x * (cell_width), y * (cell_width), cell_width); glTexCoord2f(0.25, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), cell_width); glTexCoord2f(0.25, 0.25); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, cell_width); glTexCoord2f(-0.25, 0.25); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, cell_width); glEnd(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glTexCoord2f(-1.0, 0.0); glVertex3i(x * (cell_width), y * (cell_width), 0); glTexCoord2f(1.0, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), 0); glTexCoord2f(1.0, 1.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, 0); glTexCoord2f(-1.0, 1.0); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, 0); glEnd(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glTexCoord2f(-1.0, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), 0); glTexCoord2f(1.0, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, 0); glTexCoord2f(1.0, 1.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, cell_width); glTexCoord2f(-1.0, 1.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), cell_width); glEnd(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glTexCoord2f(-1.0, 0.0); glVertex3i(x * (cell_width), y * (cell_width), 0); glTexCoord2f(1.0, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), 0); glTexCoord2f(1.0, 1.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width), cell_width); glTexCoord2f(-1.0, 1.0); glVertex3i(x * (cell_width), y * (cell_width), cell_width); glEnd(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glTexCoord2f(-1.0, 0.0); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, 0); glTexCoord2f(1.0, 0.0); glVertex3i(x * (cell_width), y * (cell_width), 0); glTexCoord2f(1.0, 1.0); glVertex3i(x * (cell_width), y * (cell_width), cell_width); glTexCoord2f(-1.0, 1.0); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, cell_width); glEnd(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glTexCoord2f(1.0, 0.0); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, 0); glTexCoord2f(-1.0, 0.0); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, 0); glTexCoord2f(-0.5, 0.5); glVertex3i(x * (cell_width), y * (cell_width) + cell_width, cell_width); glTexCoord2f(0.5, 0.5); glVertex3i(x * (cell_width) + cell_width, y * (cell_width) + cell_width, cell_width); glEnd(); glDisable(GL_TEXTURE_2D); } void displayCorridor(int x, int y) { // Function that represents the corrider as floor glBindTexture(GL_TEXTURE_2D, 1); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(-0.5, 0.0); glVertex2i(x * (cell_width), y * (cell_width)); glTexCoord2f(0.5, 0.0); glVertex2i(x * (cell_width) + cell_width, y * (cell_width)); glTexCoord2f(0.5, 0.5); glVertex2i(x * (cell_width) + cell_width, y * (cell_width) + cell_width); glTexCoord2f(-0.5, 0.5); glVertex2i(x * (cell_width), y * (cell_width) + cell_width); glEnd(); glDisable(GL_TEXTURE_2D); } void displayInitialPlayer(int x, int y) { // Function that represents the initial point of the player glBindTexture(GL_TEXTURE_2D, 3); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(-0.5, 0.0); glVertex2i(x * (cell_width), y * (cell_width)); glTexCoord2f(0.5, 0.0); glVertex2i(x * (cell_width) + cell_width, y * (cell_width)); glTexCoord2f(0.5, 0.5); glVertex2i(x * (cell_width) + cell_width, y * (cell_width) + cell_width); glTexCoord2f(-0.5, 0.5); glVertex2i(x * (cell_width), y * (cell_width) + cell_width); glEnd(); glDisable(GL_TEXTURE_2D); } void displayInitialEnemy(int x, int y) { // Function that represents the initial point of the enemy glBindTexture(GL_TEXTURE_2D, 4); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(-0.5, 0.0); glVertex2i(x * (cell_width), y * (cell_width)); glTexCoord2f(0.5, 0.0); glVertex2i(x * (cell_width) + cell_width, y * (cell_width)); glTexCoord2f(0.5, 0.5); glVertex2i(x * (cell_width) + cell_width, y * (cell_width) + cell_width); glTexCoord2f(-0.5, 0.5); glVertex2i(x * (cell_width), y * (cell_width) + cell_width); glEnd(); glDisable(GL_TEXTURE_2D); } };
31.890351
141
0.501719
[ "vector" ]
68848d5681e8e69d70f3b6504541916f1b5ea8e9
667
cpp
C++
Practice/Hackerrank_Interview_Prep_Kit/minimum_abs_diff.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
11
2020-03-20T17:24:28.000Z
2022-01-08T02:43:24.000Z
Practice/Hackerrank_Interview_Prep_Kit/minimum_abs_diff.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
1
2021-07-25T11:24:46.000Z
2021-07-25T12:09:25.000Z
Practice/Hackerrank_Interview_Prep_Kit/minimum_abs_diff.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
4
2020-03-20T17:24:36.000Z
2021-12-07T19:22:59.000Z
#include<iostream> #include<vector> #include<algorithm> using namespace std; int minimumAbsoluteDifference(vector<int> arr) { sort(arr.begin(), arr.end()); auto diff = INT_MAX; // from 1st element to last. auto start_itr = next(arr.begin()); for(auto i=start_itr; i!= arr.end(); i++) { diff = min(diff, (*i - *prev(i))); } return diff; } int main(int argc, char const *argv[]) { // vector<int> arr = {1, -3, 71, 68, 17}; // vector<int> arr = {-59, -36, -13, 1, -53, -92, -2, -96, -54, 75}; vector<int> arr = {3, -7, 0}; auto res = minimumAbsoluteDifference(arr); cout<<res; return 0; }
19.057143
72
0.557721
[ "vector" ]
68855deedbf1824a4d9fe59e52c43efb14266543
23,363
cc
C++
Alignment/LaserDQM/plugins/LaserDQM.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
Alignment/LaserDQM/plugins/LaserDQM.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
Alignment/LaserDQM/plugins/LaserDQM.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
/** \file LaserDQM.cc * DQM Monitors for Laser Alignment System * * $Date: 2009/12/14 22:21:46 $ * $Revision: 1.7 $ * \author Maarten Thomas */ #include "Alignment/LaserDQM/plugins/LaserDQM.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" LaserDQM::LaserDQM(edm::ParameterSet const& theConf) : theDebugLevel(theConf.getUntrackedParameter<int>("DebugLevel",0)), theSearchPhiTIB(theConf.getUntrackedParameter<double>("SearchWindowPhiTIB",0.05)), theSearchPhiTOB(theConf.getUntrackedParameter<double>("SearchWindowPhiTOB",0.05)), theSearchPhiTEC(theConf.getUntrackedParameter<double>("SearchWindowPhiTEC",0.05)), theSearchZTIB(theConf.getUntrackedParameter<double>("SearchWindowZTIB",1.0)), theSearchZTOB(theConf.getUntrackedParameter<double>("SearchWindowZTOB",1.0)), theDigiProducersList(theConf.getParameter<Parameters>("DigiProducersList")), theDQMFileName(theConf.getUntrackedParameter<std::string>("DQMFileName","testDQM.root")), theDaqMonitorBEI(), theMEBeam0Ring4Disc1PosAdcCounts(0), theMEBeam0Ring4Disc2PosAdcCounts(0), theMEBeam0Ring4Disc3PosAdcCounts(0), theMEBeam0Ring4Disc4PosAdcCounts(0), theMEBeam0Ring4Disc5PosAdcCounts(0), theMEBeam0Ring4Disc6PosAdcCounts(0), theMEBeam0Ring4Disc7PosAdcCounts(0), theMEBeam0Ring4Disc8PosAdcCounts(0), theMEBeam0Ring4Disc9PosAdcCounts(0), // Adc counts for Beam 1 in Ring 4 theMEBeam1Ring4Disc1PosAdcCounts(0), theMEBeam1Ring4Disc2PosAdcCounts(0), theMEBeam1Ring4Disc3PosAdcCounts(0), theMEBeam1Ring4Disc4PosAdcCounts(0), theMEBeam1Ring4Disc5PosAdcCounts(0), theMEBeam1Ring4Disc6PosAdcCounts(0), theMEBeam1Ring4Disc7PosAdcCounts(0), theMEBeam1Ring4Disc8PosAdcCounts(0), theMEBeam1Ring4Disc9PosAdcCounts(0), // plots for TEC2TEC theMEBeam1Ring4Disc1PosTEC2TECAdcCounts(0), theMEBeam1Ring4Disc2PosTEC2TECAdcCounts(0), theMEBeam1Ring4Disc3PosTEC2TECAdcCounts(0), theMEBeam1Ring4Disc4PosTEC2TECAdcCounts(0), theMEBeam1Ring4Disc5PosTEC2TECAdcCounts(0), // Adc counts for Beam 2 in Ring 4 theMEBeam2Ring4Disc1PosAdcCounts(0), theMEBeam2Ring4Disc2PosAdcCounts(0), theMEBeam2Ring4Disc3PosAdcCounts(0), theMEBeam2Ring4Disc4PosAdcCounts(0), theMEBeam2Ring4Disc5PosAdcCounts(0), theMEBeam2Ring4Disc6PosAdcCounts(0), theMEBeam2Ring4Disc7PosAdcCounts(0), theMEBeam2Ring4Disc8PosAdcCounts(0), theMEBeam2Ring4Disc9PosAdcCounts(0), // plots for TEC2TEC theMEBeam2Ring4Disc1PosTEC2TECAdcCounts(0), theMEBeam2Ring4Disc2PosTEC2TECAdcCounts(0), theMEBeam2Ring4Disc3PosTEC2TECAdcCounts(0), theMEBeam2Ring4Disc4PosTEC2TECAdcCounts(0), theMEBeam2Ring4Disc5PosTEC2TECAdcCounts(0), // Adc counts for Beam 3 in Ring 4 theMEBeam3Ring4Disc1PosAdcCounts(0), theMEBeam3Ring4Disc2PosAdcCounts(0), theMEBeam3Ring4Disc3PosAdcCounts(0), theMEBeam3Ring4Disc4PosAdcCounts(0), theMEBeam3Ring4Disc5PosAdcCounts(0), theMEBeam3Ring4Disc6PosAdcCounts(0), theMEBeam3Ring4Disc7PosAdcCounts(0), theMEBeam3Ring4Disc8PosAdcCounts(0), theMEBeam3Ring4Disc9PosAdcCounts(0), // Adc counts for Beam 4 in Ring 4 theMEBeam4Ring4Disc1PosAdcCounts(0), theMEBeam4Ring4Disc2PosAdcCounts(0), theMEBeam4Ring4Disc3PosAdcCounts(0), theMEBeam4Ring4Disc4PosAdcCounts(0), theMEBeam4Ring4Disc5PosAdcCounts(0), theMEBeam4Ring4Disc6PosAdcCounts(0), theMEBeam4Ring4Disc7PosAdcCounts(0), theMEBeam4Ring4Disc8PosAdcCounts(0), theMEBeam4Ring4Disc9PosAdcCounts(0), // plots for TEC2TEC theMEBeam4Ring4Disc1PosTEC2TECAdcCounts(0), theMEBeam4Ring4Disc2PosTEC2TECAdcCounts(0), theMEBeam4Ring4Disc3PosTEC2TECAdcCounts(0), theMEBeam4Ring4Disc4PosTEC2TECAdcCounts(0), theMEBeam4Ring4Disc5PosTEC2TECAdcCounts(0), // Adc counts for Beam 5 in Ring 4 theMEBeam5Ring4Disc1PosAdcCounts(0), theMEBeam5Ring4Disc2PosAdcCounts(0), theMEBeam5Ring4Disc3PosAdcCounts(0), theMEBeam5Ring4Disc4PosAdcCounts(0), theMEBeam5Ring4Disc5PosAdcCounts(0), theMEBeam5Ring4Disc6PosAdcCounts(0), theMEBeam5Ring4Disc7PosAdcCounts(0), theMEBeam5Ring4Disc8PosAdcCounts(0), theMEBeam5Ring4Disc9PosAdcCounts(0), // Adc counts for Beam 6 in Ring 4 theMEBeam6Ring4Disc1PosAdcCounts(0), theMEBeam6Ring4Disc2PosAdcCounts(0), theMEBeam6Ring4Disc3PosAdcCounts(0), theMEBeam6Ring4Disc4PosAdcCounts(0), theMEBeam6Ring4Disc5PosAdcCounts(0), theMEBeam6Ring4Disc6PosAdcCounts(0), theMEBeam6Ring4Disc7PosAdcCounts(0), theMEBeam6Ring4Disc8PosAdcCounts(0), theMEBeam6Ring4Disc9PosAdcCounts(0), // plots for TEC2TEC theMEBeam6Ring4Disc1PosTEC2TECAdcCounts(0), theMEBeam6Ring4Disc2PosTEC2TECAdcCounts(0), theMEBeam6Ring4Disc3PosTEC2TECAdcCounts(0), theMEBeam6Ring4Disc4PosTEC2TECAdcCounts(0), theMEBeam6Ring4Disc5PosTEC2TECAdcCounts(0), // Adc counts for Beam 7 in Ring 4 theMEBeam7Ring4Disc1PosAdcCounts(0), theMEBeam7Ring4Disc2PosAdcCounts(0), theMEBeam7Ring4Disc3PosAdcCounts(0), theMEBeam7Ring4Disc4PosAdcCounts(0), theMEBeam7Ring4Disc5PosAdcCounts(0), theMEBeam7Ring4Disc6PosAdcCounts(0), theMEBeam7Ring4Disc7PosAdcCounts(0), theMEBeam7Ring4Disc8PosAdcCounts(0), theMEBeam7Ring4Disc9PosAdcCounts(0), // plots for TEC2TEC theMEBeam7Ring4Disc1PosTEC2TECAdcCounts(0), theMEBeam7Ring4Disc2PosTEC2TECAdcCounts(0), theMEBeam7Ring4Disc3PosTEC2TECAdcCounts(0), theMEBeam7Ring4Disc4PosTEC2TECAdcCounts(0), theMEBeam7Ring4Disc5PosTEC2TECAdcCounts(0), // Adc counts for Beam 0 in Ring 6 theMEBeam0Ring6Disc1PosAdcCounts(0), theMEBeam0Ring6Disc2PosAdcCounts(0), theMEBeam0Ring6Disc3PosAdcCounts(0), theMEBeam0Ring6Disc4PosAdcCounts(0), theMEBeam0Ring6Disc5PosAdcCounts(0), theMEBeam0Ring6Disc6PosAdcCounts(0), theMEBeam0Ring6Disc7PosAdcCounts(0), theMEBeam0Ring6Disc8PosAdcCounts(0), theMEBeam0Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 1 in Ring 6 theMEBeam1Ring6Disc1PosAdcCounts(0), theMEBeam1Ring6Disc2PosAdcCounts(0), theMEBeam1Ring6Disc3PosAdcCounts(0), theMEBeam1Ring6Disc4PosAdcCounts(0), theMEBeam1Ring6Disc5PosAdcCounts(0), theMEBeam1Ring6Disc6PosAdcCounts(0), theMEBeam1Ring6Disc7PosAdcCounts(0), theMEBeam1Ring6Disc8PosAdcCounts(0), theMEBeam1Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 2 in Ring 6 theMEBeam2Ring6Disc1PosAdcCounts(0), theMEBeam2Ring6Disc2PosAdcCounts(0), theMEBeam2Ring6Disc3PosAdcCounts(0), theMEBeam2Ring6Disc4PosAdcCounts(0), theMEBeam2Ring6Disc5PosAdcCounts(0), theMEBeam2Ring6Disc6PosAdcCounts(0), theMEBeam2Ring6Disc7PosAdcCounts(0), theMEBeam2Ring6Disc8PosAdcCounts(0), theMEBeam2Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 3 in Ring 6 theMEBeam3Ring6Disc1PosAdcCounts(0), theMEBeam3Ring6Disc2PosAdcCounts(0), theMEBeam3Ring6Disc3PosAdcCounts(0), theMEBeam3Ring6Disc4PosAdcCounts(0), theMEBeam3Ring6Disc5PosAdcCounts(0), theMEBeam3Ring6Disc6PosAdcCounts(0), theMEBeam3Ring6Disc7PosAdcCounts(0), theMEBeam3Ring6Disc8PosAdcCounts(0), theMEBeam3Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 4 in Ring 6 theMEBeam4Ring6Disc1PosAdcCounts(0), theMEBeam4Ring6Disc2PosAdcCounts(0), theMEBeam4Ring6Disc3PosAdcCounts(0), theMEBeam4Ring6Disc4PosAdcCounts(0), theMEBeam4Ring6Disc5PosAdcCounts(0), theMEBeam4Ring6Disc6PosAdcCounts(0), theMEBeam4Ring6Disc7PosAdcCounts(0), theMEBeam4Ring6Disc8PosAdcCounts(0), theMEBeam4Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 5 in Ring 6 theMEBeam5Ring6Disc1PosAdcCounts(0), theMEBeam5Ring6Disc2PosAdcCounts(0), theMEBeam5Ring6Disc3PosAdcCounts(0), theMEBeam5Ring6Disc4PosAdcCounts(0), theMEBeam5Ring6Disc5PosAdcCounts(0), theMEBeam5Ring6Disc6PosAdcCounts(0), theMEBeam5Ring6Disc7PosAdcCounts(0), theMEBeam5Ring6Disc8PosAdcCounts(0), theMEBeam5Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 6 in Ring 6 theMEBeam6Ring6Disc1PosAdcCounts(0), theMEBeam6Ring6Disc2PosAdcCounts(0), theMEBeam6Ring6Disc3PosAdcCounts(0), theMEBeam6Ring6Disc4PosAdcCounts(0), theMEBeam6Ring6Disc5PosAdcCounts(0), theMEBeam6Ring6Disc6PosAdcCounts(0), theMEBeam6Ring6Disc7PosAdcCounts(0), theMEBeam6Ring6Disc8PosAdcCounts(0), theMEBeam6Ring6Disc9PosAdcCounts(0), // Adc counts for Beam 7 in Ring 6 theMEBeam7Ring6Disc1PosAdcCounts(0), theMEBeam7Ring6Disc2PosAdcCounts(0), theMEBeam7Ring6Disc3PosAdcCounts(0), theMEBeam7Ring6Disc4PosAdcCounts(0), theMEBeam7Ring6Disc5PosAdcCounts(0), theMEBeam7Ring6Disc6PosAdcCounts(0), theMEBeam7Ring6Disc7PosAdcCounts(0), theMEBeam7Ring6Disc8PosAdcCounts(0), theMEBeam7Ring6Disc9PosAdcCounts(0), /* Laser Beams in TEC- */ // Adc counts for Beam 0 in Ring 4 theMEBeam0Ring4Disc1NegAdcCounts(0), theMEBeam0Ring4Disc2NegAdcCounts(0), theMEBeam0Ring4Disc3NegAdcCounts(0), theMEBeam0Ring4Disc4NegAdcCounts(0), theMEBeam0Ring4Disc5NegAdcCounts(0), theMEBeam0Ring4Disc6NegAdcCounts(0), theMEBeam0Ring4Disc7NegAdcCounts(0), theMEBeam0Ring4Disc8NegAdcCounts(0), theMEBeam0Ring4Disc9NegAdcCounts(0), // Adc counts for Beam 1 in Ring 4 theMEBeam1Ring4Disc1NegAdcCounts(0), theMEBeam1Ring4Disc2NegAdcCounts(0), theMEBeam1Ring4Disc3NegAdcCounts(0), theMEBeam1Ring4Disc4NegAdcCounts(0), theMEBeam1Ring4Disc5NegAdcCounts(0), theMEBeam1Ring4Disc6NegAdcCounts(0), theMEBeam1Ring4Disc7NegAdcCounts(0), theMEBeam1Ring4Disc8NegAdcCounts(0), theMEBeam1Ring4Disc9NegAdcCounts(0), // plots for TEC2TEC theMEBeam1Ring4Disc1NegTEC2TECAdcCounts(0), theMEBeam1Ring4Disc2NegTEC2TECAdcCounts(0), theMEBeam1Ring4Disc3NegTEC2TECAdcCounts(0), theMEBeam1Ring4Disc4NegTEC2TECAdcCounts(0), theMEBeam1Ring4Disc5NegTEC2TECAdcCounts(0), // Adc counts for Beam 2 in Ring 4 theMEBeam2Ring4Disc1NegAdcCounts(0), theMEBeam2Ring4Disc2NegAdcCounts(0), theMEBeam2Ring4Disc3NegAdcCounts(0), theMEBeam2Ring4Disc4NegAdcCounts(0), theMEBeam2Ring4Disc5NegAdcCounts(0), theMEBeam2Ring4Disc6NegAdcCounts(0), theMEBeam2Ring4Disc7NegAdcCounts(0), theMEBeam2Ring4Disc8NegAdcCounts(0), theMEBeam2Ring4Disc9NegAdcCounts(0), // plots for TEC2TEC theMEBeam2Ring4Disc1NegTEC2TECAdcCounts(0), theMEBeam2Ring4Disc2NegTEC2TECAdcCounts(0), theMEBeam2Ring4Disc3NegTEC2TECAdcCounts(0), theMEBeam2Ring4Disc4NegTEC2TECAdcCounts(0), theMEBeam2Ring4Disc5NegTEC2TECAdcCounts(0), // Adc counts for Beam 3 in Ring 4 theMEBeam3Ring4Disc1NegAdcCounts(0), theMEBeam3Ring4Disc2NegAdcCounts(0), theMEBeam3Ring4Disc3NegAdcCounts(0), theMEBeam3Ring4Disc4NegAdcCounts(0), theMEBeam3Ring4Disc5NegAdcCounts(0), theMEBeam3Ring4Disc6NegAdcCounts(0), theMEBeam3Ring4Disc7NegAdcCounts(0), theMEBeam3Ring4Disc8NegAdcCounts(0), theMEBeam3Ring4Disc9NegAdcCounts(0), // Adc counts for Beam 4 in Ring 4 theMEBeam4Ring4Disc1NegAdcCounts(0), theMEBeam4Ring4Disc2NegAdcCounts(0), theMEBeam4Ring4Disc3NegAdcCounts(0), theMEBeam4Ring4Disc4NegAdcCounts(0), theMEBeam4Ring4Disc5NegAdcCounts(0), theMEBeam4Ring4Disc6NegAdcCounts(0), theMEBeam4Ring4Disc7NegAdcCounts(0), theMEBeam4Ring4Disc8NegAdcCounts(0), theMEBeam4Ring4Disc9NegAdcCounts(0), // plots for TEC2TEC theMEBeam4Ring4Disc1NegTEC2TECAdcCounts(0), theMEBeam4Ring4Disc2NegTEC2TECAdcCounts(0), theMEBeam4Ring4Disc3NegTEC2TECAdcCounts(0), theMEBeam4Ring4Disc4NegTEC2TECAdcCounts(0), theMEBeam4Ring4Disc5NegTEC2TECAdcCounts(0), // Adc counts for Beam 5 in Ring 4 theMEBeam5Ring4Disc1NegAdcCounts(0), theMEBeam5Ring4Disc2NegAdcCounts(0), theMEBeam5Ring4Disc3NegAdcCounts(0), theMEBeam5Ring4Disc4NegAdcCounts(0), theMEBeam5Ring4Disc5NegAdcCounts(0), theMEBeam5Ring4Disc6NegAdcCounts(0), theMEBeam5Ring4Disc7NegAdcCounts(0), theMEBeam5Ring4Disc8NegAdcCounts(0), theMEBeam5Ring4Disc9NegAdcCounts(0), // Adc counts for Beam 6 in Ring 4 theMEBeam6Ring4Disc1NegAdcCounts(0), theMEBeam6Ring4Disc2NegAdcCounts(0), theMEBeam6Ring4Disc3NegAdcCounts(0), theMEBeam6Ring4Disc4NegAdcCounts(0), theMEBeam6Ring4Disc5NegAdcCounts(0), theMEBeam6Ring4Disc6NegAdcCounts(0), theMEBeam6Ring4Disc7NegAdcCounts(0), theMEBeam6Ring4Disc8NegAdcCounts(0), theMEBeam6Ring4Disc9NegAdcCounts(0), // plots for TEC2TEC theMEBeam6Ring4Disc1NegTEC2TECAdcCounts(0), theMEBeam6Ring4Disc2NegTEC2TECAdcCounts(0), theMEBeam6Ring4Disc3NegTEC2TECAdcCounts(0), theMEBeam6Ring4Disc4NegTEC2TECAdcCounts(0), theMEBeam6Ring4Disc5NegTEC2TECAdcCounts(0), // Adc counts for Beam 7 in Ring 4 theMEBeam7Ring4Disc1NegAdcCounts(0), theMEBeam7Ring4Disc2NegAdcCounts(0), theMEBeam7Ring4Disc3NegAdcCounts(0), theMEBeam7Ring4Disc4NegAdcCounts(0), theMEBeam7Ring4Disc5NegAdcCounts(0), theMEBeam7Ring4Disc6NegAdcCounts(0), theMEBeam7Ring4Disc7NegAdcCounts(0), theMEBeam7Ring4Disc8NegAdcCounts(0), theMEBeam7Ring4Disc9NegAdcCounts(0), // plots for TEC2TEC theMEBeam7Ring4Disc1NegTEC2TECAdcCounts(0), theMEBeam7Ring4Disc2NegTEC2TECAdcCounts(0), theMEBeam7Ring4Disc3NegTEC2TECAdcCounts(0), theMEBeam7Ring4Disc4NegTEC2TECAdcCounts(0), theMEBeam7Ring4Disc5NegTEC2TECAdcCounts(0), // Adc counts for Beam 0 in Ring 6 theMEBeam0Ring6Disc1NegAdcCounts(0), theMEBeam0Ring6Disc2NegAdcCounts(0), theMEBeam0Ring6Disc3NegAdcCounts(0), theMEBeam0Ring6Disc4NegAdcCounts(0), theMEBeam0Ring6Disc5NegAdcCounts(0), theMEBeam0Ring6Disc6NegAdcCounts(0), theMEBeam0Ring6Disc7NegAdcCounts(0), theMEBeam0Ring6Disc8NegAdcCounts(0), theMEBeam0Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 1 in Ring 6 theMEBeam1Ring6Disc1NegAdcCounts(0), theMEBeam1Ring6Disc2NegAdcCounts(0), theMEBeam1Ring6Disc3NegAdcCounts(0), theMEBeam1Ring6Disc4NegAdcCounts(0), theMEBeam1Ring6Disc5NegAdcCounts(0), theMEBeam1Ring6Disc6NegAdcCounts(0), theMEBeam1Ring6Disc7NegAdcCounts(0), theMEBeam1Ring6Disc8NegAdcCounts(0), theMEBeam1Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 2 in Ring 6 theMEBeam2Ring6Disc1NegAdcCounts(0), theMEBeam2Ring6Disc2NegAdcCounts(0), theMEBeam2Ring6Disc3NegAdcCounts(0), theMEBeam2Ring6Disc4NegAdcCounts(0), theMEBeam2Ring6Disc5NegAdcCounts(0), theMEBeam2Ring6Disc6NegAdcCounts(0), theMEBeam2Ring6Disc7NegAdcCounts(0), theMEBeam2Ring6Disc8NegAdcCounts(0), theMEBeam2Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 3 in Ring 6 theMEBeam3Ring6Disc1NegAdcCounts(0), theMEBeam3Ring6Disc2NegAdcCounts(0), theMEBeam3Ring6Disc3NegAdcCounts(0), theMEBeam3Ring6Disc4NegAdcCounts(0), theMEBeam3Ring6Disc5NegAdcCounts(0), theMEBeam3Ring6Disc6NegAdcCounts(0), theMEBeam3Ring6Disc7NegAdcCounts(0), theMEBeam3Ring6Disc8NegAdcCounts(0), theMEBeam3Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 4 in Ring 6 theMEBeam4Ring6Disc1NegAdcCounts(0), theMEBeam4Ring6Disc2NegAdcCounts(0), theMEBeam4Ring6Disc3NegAdcCounts(0), theMEBeam4Ring6Disc4NegAdcCounts(0), theMEBeam4Ring6Disc5NegAdcCounts(0), theMEBeam4Ring6Disc6NegAdcCounts(0), theMEBeam4Ring6Disc7NegAdcCounts(0), theMEBeam4Ring6Disc8NegAdcCounts(0), theMEBeam4Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 5 in Ring 6 theMEBeam5Ring6Disc1NegAdcCounts(0), theMEBeam5Ring6Disc2NegAdcCounts(0), theMEBeam5Ring6Disc3NegAdcCounts(0), theMEBeam5Ring6Disc4NegAdcCounts(0), theMEBeam5Ring6Disc5NegAdcCounts(0), theMEBeam5Ring6Disc6NegAdcCounts(0), theMEBeam5Ring6Disc7NegAdcCounts(0), theMEBeam5Ring6Disc8NegAdcCounts(0), theMEBeam5Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 6 in Ring 6 theMEBeam6Ring6Disc1NegAdcCounts(0), theMEBeam6Ring6Disc2NegAdcCounts(0), theMEBeam6Ring6Disc3NegAdcCounts(0), theMEBeam6Ring6Disc4NegAdcCounts(0), theMEBeam6Ring6Disc5NegAdcCounts(0), theMEBeam6Ring6Disc6NegAdcCounts(0), theMEBeam6Ring6Disc7NegAdcCounts(0), theMEBeam6Ring6Disc8NegAdcCounts(0), theMEBeam6Ring6Disc9NegAdcCounts(0), // Adc counts for Beam 7 in Ring 6 theMEBeam7Ring6Disc1NegAdcCounts(0), theMEBeam7Ring6Disc2NegAdcCounts(0), theMEBeam7Ring6Disc3NegAdcCounts(0), theMEBeam7Ring6Disc4NegAdcCounts(0), theMEBeam7Ring6Disc5NegAdcCounts(0), theMEBeam7Ring6Disc6NegAdcCounts(0), theMEBeam7Ring6Disc7NegAdcCounts(0), theMEBeam7Ring6Disc8NegAdcCounts(0), theMEBeam7Ring6Disc9NegAdcCounts(0), // TOB Beams // Adc counts for Beam 0 theMEBeam0TOBPosition1AdcCounts(0), theMEBeam0TOBPosition2AdcCounts(0), theMEBeam0TOBPosition3AdcCounts(0), theMEBeam0TOBPosition4AdcCounts(0), theMEBeam0TOBPosition5AdcCounts(0), theMEBeam0TOBPosition6AdcCounts(0), // Adc counts for Beam 1 theMEBeam1TOBPosition1AdcCounts(0), theMEBeam1TOBPosition2AdcCounts(0), theMEBeam1TOBPosition3AdcCounts(0), theMEBeam1TOBPosition4AdcCounts(0), theMEBeam1TOBPosition5AdcCounts(0), theMEBeam1TOBPosition6AdcCounts(0), // Adc counts for Beam 2 theMEBeam2TOBPosition1AdcCounts(0), theMEBeam2TOBPosition2AdcCounts(0), theMEBeam2TOBPosition3AdcCounts(0), theMEBeam2TOBPosition4AdcCounts(0), theMEBeam2TOBPosition5AdcCounts(0), theMEBeam2TOBPosition6AdcCounts(0), // Adc counts for Beam 3 theMEBeam3TOBPosition1AdcCounts(0), theMEBeam3TOBPosition2AdcCounts(0), theMEBeam3TOBPosition3AdcCounts(0), theMEBeam3TOBPosition4AdcCounts(0), theMEBeam3TOBPosition5AdcCounts(0), theMEBeam3TOBPosition6AdcCounts(0), // Adc counts for Beam 4 theMEBeam4TOBPosition1AdcCounts(0), theMEBeam4TOBPosition2AdcCounts(0), theMEBeam4TOBPosition3AdcCounts(0), theMEBeam4TOBPosition4AdcCounts(0), theMEBeam4TOBPosition5AdcCounts(0), theMEBeam4TOBPosition6AdcCounts(0), // Adc counts for Beam 5 theMEBeam5TOBPosition1AdcCounts(0), theMEBeam5TOBPosition2AdcCounts(0), theMEBeam5TOBPosition3AdcCounts(0), theMEBeam5TOBPosition4AdcCounts(0), theMEBeam5TOBPosition5AdcCounts(0), theMEBeam5TOBPosition6AdcCounts(0), // Adc counts for Beam 6 theMEBeam6TOBPosition1AdcCounts(0), theMEBeam6TOBPosition2AdcCounts(0), theMEBeam6TOBPosition3AdcCounts(0), theMEBeam6TOBPosition4AdcCounts(0), theMEBeam6TOBPosition5AdcCounts(0), theMEBeam6TOBPosition6AdcCounts(0), // Adc counts for Beam 7 theMEBeam7TOBPosition1AdcCounts(0), theMEBeam7TOBPosition2AdcCounts(0), theMEBeam7TOBPosition3AdcCounts(0), theMEBeam7TOBPosition4AdcCounts(0), theMEBeam7TOBPosition5AdcCounts(0), theMEBeam7TOBPosition6AdcCounts(0), // TIB Beams // Adc counts for Beam 0 theMEBeam0TIBPosition1AdcCounts(0), theMEBeam0TIBPosition2AdcCounts(0), theMEBeam0TIBPosition3AdcCounts(0), theMEBeam0TIBPosition4AdcCounts(0), theMEBeam0TIBPosition5AdcCounts(0), theMEBeam0TIBPosition6AdcCounts(0), // Adc counts for Beam 1 theMEBeam1TIBPosition1AdcCounts(0), theMEBeam1TIBPosition2AdcCounts(0), theMEBeam1TIBPosition3AdcCounts(0), theMEBeam1TIBPosition4AdcCounts(0), theMEBeam1TIBPosition5AdcCounts(0), theMEBeam1TIBPosition6AdcCounts(0), // Adc counts for Beam 2 theMEBeam2TIBPosition1AdcCounts(0), theMEBeam2TIBPosition2AdcCounts(0), theMEBeam2TIBPosition3AdcCounts(0), theMEBeam2TIBPosition4AdcCounts(0), theMEBeam2TIBPosition5AdcCounts(0), theMEBeam2TIBPosition6AdcCounts(0), // Adc counts for Beam 3 theMEBeam3TIBPosition1AdcCounts(0), theMEBeam3TIBPosition2AdcCounts(0), theMEBeam3TIBPosition3AdcCounts(0), theMEBeam3TIBPosition4AdcCounts(0), theMEBeam3TIBPosition5AdcCounts(0), theMEBeam3TIBPosition6AdcCounts(0), // Adc counts for Beam 4 theMEBeam4TIBPosition1AdcCounts(0), theMEBeam4TIBPosition2AdcCounts(0), theMEBeam4TIBPosition3AdcCounts(0), theMEBeam4TIBPosition4AdcCounts(0), theMEBeam4TIBPosition5AdcCounts(0), theMEBeam4TIBPosition6AdcCounts(0), // Adc counts for Beam 5 theMEBeam5TIBPosition1AdcCounts(0), theMEBeam5TIBPosition2AdcCounts(0), theMEBeam5TIBPosition3AdcCounts(0), theMEBeam5TIBPosition4AdcCounts(0), theMEBeam5TIBPosition5AdcCounts(0), theMEBeam5TIBPosition6AdcCounts(0), // Adc counts for Beam 6 theMEBeam6TIBPosition1AdcCounts(0), theMEBeam6TIBPosition2AdcCounts(0), theMEBeam6TIBPosition3AdcCounts(0), theMEBeam6TIBPosition4AdcCounts(0), theMEBeam6TIBPosition5AdcCounts(0), theMEBeam6TIBPosition6AdcCounts(0), // Adc counts for Beam 7 theMEBeam7TIBPosition1AdcCounts(0), theMEBeam7TIBPosition2AdcCounts(0), theMEBeam7TIBPosition3AdcCounts(0), theMEBeam7TIBPosition4AdcCounts(0), theMEBeam7TIBPosition5AdcCounts(0), theMEBeam7TIBPosition6AdcCounts(0) { // load the configuration from the ParameterSet edm::LogInfo("LaserDQM") << "===========================================================" << "\n=== Start configuration ===" << "\n theDebugLevel = " << theDebugLevel << "\n theSearchPhiTIB = " << theSearchPhiTIB << "\n theSearchPhiTOB = " << theSearchPhiTOB << "\n theSearchPhiTEC = " << theSearchPhiTEC << "\n theSearchZTIB = " << theSearchZTIB << "\n theSearchZTOB = " << theSearchZTOB << "\n DQM filename = " << theDQMFileName << "\n==========================================================="; } LaserDQM::~LaserDQM() {} void LaserDQM::analyze(edm::Event const& theEvent, edm::EventSetup const& theSetup) { // do the Tracker Statistics trackerStatistics(theEvent, theSetup); } void LaserDQM::beginJob() { // get hold of DQM Backend interface theDaqMonitorBEI = edm::Service<DQMStore>().operator->(); // initialize the Monitor Elements initMonitors(); } void LaserDQM::endJob(void) { theDaqMonitorBEI->save(theDQMFileName.c_str()); } void LaserDQM::fillAdcCounts(MonitorElement * theMonitor, edm::DetSet<SiStripDigi>::const_iterator digiRangeIterator, edm::DetSet<SiStripDigi>::const_iterator digiRangeIteratorEnd) { // get the ROOT object from the MonitorElement TH1F * theMEHistogram = theMonitor->getTH1F(); // loop over all the digis in this det for (; digiRangeIterator != digiRangeIteratorEnd; ++digiRangeIterator) { const SiStripDigi *digi = &*digiRangeIterator; if ( theDebugLevel > 4 ) { std::cout << " Channel " << digi->channel() << " has " << digi->adc() << " adc counts " << std::endl; } // fill the number of adc counts in the histogram if (digi->channel() < 512) { Double_t theBinContent = theMEHistogram->GetBinContent(digi->channel()) + digi->adc(); theMEHistogram->SetBinContent(digi->channel(), theBinContent); } } } // define the SEAL module DEFINE_FWK_MODULE(LaserDQM);
39.868601
106
0.767025
[ "object" ]
6885b5f0394f9d1747b3d73bc688090eb4b20a52
7,646
cpp
C++
model/GetMessagePriceResponseCountriesItem.cpp
imissyouso/textmagic-rest-cpp
b5810fd41c08dbab320a52e93d524896e2c2200f
[ "MIT" ]
null
null
null
model/GetMessagePriceResponseCountriesItem.cpp
imissyouso/textmagic-rest-cpp
b5810fd41c08dbab320a52e93d524896e2c2200f
[ "MIT" ]
1
2020-03-18T19:06:28.000Z
2020-03-23T12:30:00.000Z
model/GetMessagePriceResponseCountriesItem.cpp
textmagic/textmagic-rest-cpp-v2
769c81c3ba5b9f5ac49728f47557db846a0e9a33
[ "MIT" ]
null
null
null
/** * TextMagic API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 2 * * * NOTE: This class is auto generated by the swagger code generator 2.4.8. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "GetMessagePriceResponseCountriesItem.h" namespace com { namespace textmagic { namespace client { namespace model { GetMessagePriceResponseCountriesItem::GetMessagePriceResponseCountriesItem() { m_Country = utility::conversions::to_string_t(""); m_CountryName = utility::conversions::to_string_t(""); m_AllowDedicated = false; m_Count = 0.0; m_Max = 0.0; m_Sum = utility::conversions::to_string_t(""); m_Landline = 0.0; } GetMessagePriceResponseCountriesItem::~GetMessagePriceResponseCountriesItem() { } void GetMessagePriceResponseCountriesItem::validate() { // TODO: implement validation } web::json::value GetMessagePriceResponseCountriesItem::toJson() const { web::json::value val = web::json::value::object(); val[utility::conversions::to_string_t("country")] = ModelBase::toJson(m_Country); val[utility::conversions::to_string_t("countryName")] = ModelBase::toJson(m_CountryName); val[utility::conversions::to_string_t("allowDedicated")] = ModelBase::toJson(m_AllowDedicated); val[utility::conversions::to_string_t("count")] = ModelBase::toJson(m_Count); val[utility::conversions::to_string_t("max")] = ModelBase::toJson(m_Max); val[utility::conversions::to_string_t("sum")] = ModelBase::toJson(m_Sum); val[utility::conversions::to_string_t("landline")] = ModelBase::toJson(m_Landline); return val; } void GetMessagePriceResponseCountriesItem::fromJson(web::json::value& val) { if(val.has_field(utility::conversions::to_string_t("country"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("country")]; if(!fieldValue.is_null()) { setCountry(ModelBase::stringFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("countryName"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("countryName")]; if(!fieldValue.is_null()) { setCountryName(ModelBase::stringFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("allowDedicated"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("allowDedicated")]; if(!fieldValue.is_null()) { setAllowDedicated(ModelBase::boolFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("count"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("count")]; if(!fieldValue.is_null()) { setCount(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("max"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("max")]; if(!fieldValue.is_null()) { setMax(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("sum"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("sum")]; if(!fieldValue.is_null()) { setSum(ModelBase::stringFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("landline"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("landline")]; if(!fieldValue.is_null()) { setLandline(ModelBase::doubleFromJson(fieldValue)); } } } void GetMessagePriceResponseCountriesItem::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("country"), m_Country)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("countryName"), m_CountryName)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("allowDedicated"), m_AllowDedicated)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("count"), m_Count)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("max"), m_Max)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("sum"), m_Sum)); multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("landline"), m_Landline)); } void GetMessagePriceResponseCountriesItem::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } setCountry(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("country")))); setCountryName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("countryName")))); setAllowDedicated(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("allowDedicated")))); setCount(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("count")))); setMax(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("max")))); setSum(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("sum")))); setLandline(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("landline")))); } utility::string_t GetMessagePriceResponseCountriesItem::getCountry() const { return m_Country; } void GetMessagePriceResponseCountriesItem::setCountry(utility::string_t value) { m_Country = value; } utility::string_t GetMessagePriceResponseCountriesItem::getCountryName() const { return m_CountryName; } void GetMessagePriceResponseCountriesItem::setCountryName(utility::string_t value) { m_CountryName = value; } bool GetMessagePriceResponseCountriesItem::isAllowDedicated() const { return m_AllowDedicated; } void GetMessagePriceResponseCountriesItem::setAllowDedicated(bool value) { m_AllowDedicated = value; } double GetMessagePriceResponseCountriesItem::getCount() const { return m_Count; } void GetMessagePriceResponseCountriesItem::setCount(double value) { m_Count = value; } double GetMessagePriceResponseCountriesItem::getMax() const { return m_Max; } void GetMessagePriceResponseCountriesItem::setMax(double value) { m_Max = value; } utility::string_t GetMessagePriceResponseCountriesItem::getSum() const { return m_Sum; } void GetMessagePriceResponseCountriesItem::setSum(utility::string_t value) { m_Sum = value; } double GetMessagePriceResponseCountriesItem::getLandline() const { return m_Landline; } void GetMessagePriceResponseCountriesItem::setLandline(double value) { m_Landline = value; } } } } }
32.815451
139
0.713445
[ "object", "model" ]
688b155b7d30ba5696939577eefccc5ea4b021c1
1,877
cc
C++
arch/x86-64/assemble/4_add_entry_exit_fragments.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
41
2015-10-15T19:56:58.000Z
2022-02-03T19:35:10.000Z
arch/x86-64/assemble/4_add_entry_exit_fragments.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
null
null
null
arch/x86-64/assemble/4_add_entry_exit_fragments.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
7
2015-10-16T21:16:20.000Z
2022-01-15T02:02:20.000Z
/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #define GRANARY_ARCH_INTERNAL #include "arch/x86-64/instruction.h" #include "granary/code/fragment.h" namespace granary { namespace arch { // Table mapping each iclass to the set of read and written flags by *any* // selection of that iclass. extern const FlagsSet IFORM_FLAGS[]; // Table telling us how flags are used by a particular iclass. extern const FlagActions ICLASS_FLAG_ACTIONS[]; enum : unsigned { ALL_AFLAGS_WITH_DF = 3285U, ALL_AFLAGS_WITHOUT_DF = 2261U, ZF = (1U << 6U) }; // Visits an instructions within the fragment and revives/kills architecture- // specific flags stored in the `FlagUsageInfo` object. void VisitInstructionFlags(const arch::Instruction &instr, FlagUsageInfo *flags) { const auto &instr_flags(arch::IFORM_FLAGS[instr.iform]); auto read_flags = instr_flags.read.flat; auto written_flags = instr_flags.written.flat; if (instr.has_prefix_rep || instr.has_prefix_repne) { read_flags |= ZF; written_flags |= ZF; } flags->all_written_flags |= written_flags & ALL_AFLAGS_WITH_DF; flags->all_read_flags |= read_flags & ALL_AFLAGS_WITH_DF; if (ICLASS_FLAG_ACTIONS[instr.iclass].is_conditional_write) { flags->entry_live_flags |= written_flags & ALL_AFLAGS_WITH_DF; } else { flags->entry_live_flags &= ~written_flags & ALL_AFLAGS_WITH_DF; } flags->entry_live_flags |= read_flags & ALL_AFLAGS_WITH_DF; } // Returns a bitmap representing all arithmetic flags being live. uint32_t AllArithmeticFlags(void) { return ALL_AFLAGS_WITHOUT_DF; /* // For documentation purposes only. xed_flag_set_t flags; flags.s.of = 1; flags.s.sf = 1; flags.s.zf = 1; flags.s.af = 1; flags.s.pf = 1; flags.s.cf = 1; return flags.flat; */ } } // namespace arch } // namespace granary
27.202899
77
0.726159
[ "object" ]
688fb0bc2cdb2629b3a47541571e6d0273575d4d
272
cpp
C++
contest/AtCoder/abc008/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AtCoder/abc008/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AtCoder/abc008/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "vector.hpp" int main() { int n(in); Vector<int> c(n, in); double res = 0; for (int i : c) { int cnt = 0; for (int j : c) { if (i % j == 0) { ++cnt; } } res += (cnt + 1) / 2 / double(cnt); } cout << res << endl; }
15.111111
39
0.408088
[ "vector" ]
689a72dec23efad5aef6fdbbd539936ff6769804
11,842
hpp
C++
include/seec/Trace/ScanFormatSpecifiers.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
7
2018-06-25T12:06:13.000Z
2022-01-18T09:20:13.000Z
include/seec/Trace/ScanFormatSpecifiers.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
20
2016-12-01T23:46:12.000Z
2019-08-11T02:41:04.000Z
include/seec/Trace/ScanFormatSpecifiers.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
1
2020-10-19T03:20:05.000Z
2020-10-19T03:20:05.000Z
//===- lib/Trace/ScanFormatSpecifiers.hpp ---------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #ifndef SEEC_TRACE_SCANFORMATSPECIFIERS_HPP #define SEEC_TRACE_SCANFORMATSPECIFIERS_HPP #include "FormatSpecifiers.hpp" #include "seec/DSA/MemoryArea.hpp" #include "seec/Preprocessor/Apply.h" #include "seec/RuntimeErrors/FormatSelects.hpp" #include "seec/Trace/DetectCalls.hpp" #include "seec/Trace/TraceThreadListener.hpp" #include "seec/Util/ConstExprCString.hpp" #include "seec/Util/DefaultArgPromotion.hpp" #include "seec/Util/Maybe.hpp" #include "llvm/Support/ErrorHandling.h" #include <memory> #include <string> #include <type_traits> #include <vector> namespace seec { namespace trace { /// \brief Represents a single conversion specifier for a scan format. /// struct ScanConversionSpecifier { /// Conversion specifier character. /// enum class Specifier { none, ///< Used when no specifier is found. #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ ID, #include "seec/Trace/ScanFormatSpecifiers.def" }; char const *Start; ///< Pointer to the initial '%' character. char const *End; ///< Pointer to the first character following the specifier. LengthModifier Length; ///< The length of the argument. Specifier Conversion; ///< The type of this specifier. unsigned long Width; ///< Maximum field width. bool WidthSpecified; ///< A width was specified. bool SuppressAssignment; ///< Assignment suppression specified (by '*'). bool SetNegation; ///< The set started with a ^ character. std::string SetCharacters; ///< All characters in set. std::unique_ptr<bool []> SetLookup; ///< Lookup for set characters. /// \brief Default constructor. /// ScanConversionSpecifier() : Start(nullptr), End(nullptr), Length(LengthModifier::none), Conversion(Specifier::none), Width(0), WidthSpecified(false), SuppressAssignment(false), SetNegation(false), SetCharacters(), SetLookup() {} /// \name Query properties of the current Conversion. /// @{ /// \brief Check if this specifier consumes whitespace. /// bool consumesWhitespace() const { switch (Conversion) { case Specifier::none: return false; #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ case Specifier::ID: return WSPACE; #include "seec/Trace/ScanFormatSpecifiers.def" } llvm_unreachable("illegal conversion specifier"); return false; } /// \brief Check if this specifier may have SuppressAssignment. /// bool allowedSuppressAssignment() const { switch (Conversion) { case Specifier::none: return false; #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ case Specifier::ID: return SUPPRESS; #include "seec/Trace/ScanFormatSpecifiers.def" } llvm_unreachable("illegal conversion specifier"); return false; } /// \brief Check if a given character is in the set. /// bool hasSetCharacter(char C) const { if (!SetLookup) return false; return SetLookup[static_cast<unsigned char>(C)]; } /// @} private: /// \brief Check if the argument type matches the given type. /// template<typename T> typename std::enable_if<!std::is_void<T>::value, bool>::type checkArgumentType(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { if (ArgIndex < Args.size()) { typedef typename default_arg_promotion_of<T>::type PromotedT; auto MaybeArg = Args.getAs<PromotedT>(ArgIndex); return MaybeArg.assigned(); } return false; } /// \brief Always accept conversions that require a void argument. /// /// This is used to represent conversions that take no argument, e.g. %%. /// template<typename T> typename std::enable_if<std::is_void<T>::value, bool>::type checkArgumentType(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { return true; } public: /// \brief Check if the argument type matches the required type. /// bool isArgumentTypeOK(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { // We use the X-Macro to generate a two levels of switching. The outer // level matches the conversion, and the inner level gets the appropriate // type given the current Length. If no appropriate type exists, then we // return false. switch (Conversion) { case Specifier::none: return false; #define SEEC_PP_CHECK_LENGTH(LENGTH, TYPE) \ case LengthModifier::LENGTH: \ return checkArgumentType<TYPE>(Args, ArgIndex); #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ case Specifier::ID: \ switch (Length) { \ SEEC_PP_APPLY(SEEC_PP_CHECK_LENGTH, LENS) \ default: return false; \ } #include "seec/Trace/ScanFormatSpecifiers.def" #undef SEEC_PP_CHECK_LENGTH } llvm_unreachable("illegal conversion specifier"); return false; } /// Represents the destination/pointee of a pointer argument. typedef std::pair<char const *, std::size_t> pointee_ty; private: /// \brief For pointer types return the area of the pointee. /// template<typename T> typename std::enable_if<std::is_pointer<T>::value, seec::Maybe<pointee_ty>>::type getArgumentPointee(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { if (ArgIndex < Args.size()) { auto MaybeArg = Args.getAs<T>(ArgIndex); if (MaybeArg.assigned()) { auto const Ptr = MaybeArg.template get<0>(); return std::make_pair(reinterpret_cast<char const *>(Ptr), sizeof(*Ptr)); } } return seec::Maybe<pointee_ty>(); } /// \brief For non-pointer types return an uninitialized Maybe. template<typename T> typename std::enable_if<!std::is_pointer<T>::value, seec::Maybe<pointee_ty>>::type getArgumentPointee(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { return seec::Maybe<pointee_ty>(); } public: /// \brief Get the address and size of the pointee of a pointer argument. /// seec::Maybe<pointee_ty> getArgumentPointee(detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex) const { // We use the X-Macro to generate a two levels of switching. The outer // level matches the conversion, and the inner level gets the appropriate // type given the current Length. If no appropriate type exists, then we // return an unassigned Maybe. switch (Conversion) { case Specifier::none: return seec::Maybe<pointee_ty>(); #define SEEC_PP_CHECK_LENGTH(LENGTH, TYPE) \ case LengthModifier::LENGTH: \ return getArgumentPointee<TYPE>(Args, ArgIndex); #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ case Specifier::ID: \ switch (Length) { \ SEEC_PP_APPLY(SEEC_PP_CHECK_LENGTH, LENS) \ default: return seec::Maybe<pointee_ty>(); \ } #include "seec/Trace/ScanFormatSpecifiers.def" #undef SEEC_PP_CHECK_LENGTH } llvm_unreachable("illegal conversion specifier"); return seec::Maybe<pointee_ty>(); } private: template<typename DestT, typename SrcT> typename std::enable_if<std::is_convertible<SrcT, DestT>::value, bool>::type assignPointee(DestT &Dest, SrcT const &Src) const { Dest = Src; return true; } template<typename DestT, typename SrcT> typename std::enable_if<!std::is_convertible<SrcT, DestT>::value, bool>::type assignPointee(DestT &Dest, SrcT const &Src) const { llvm_unreachable("assignPointee() called with inconvertible type."); return false; } template<typename DestT, typename SrcT> typename std::enable_if<!std::is_void<DestT>::value, bool>::type assignPointee(TraceThreadListener &Listener, detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex, SrcT const &Src) const { auto MaybeArg = Args.getAs<DestT>(ArgIndex); if (!MaybeArg.assigned()) return false; auto Ptr = MaybeArg.template get<0>(); auto Result = assignPointee(*Ptr, Src); return Result; } template<typename DestT, typename SrcT> typename std::enable_if<std::is_void<DestT>::value, bool>::type assignPointee(TraceThreadListener &Listener, detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex, SrcT const &Src) const { llvm_unreachable("assignPointee() called with void destination."); return false; } public: /// \brief Assign the given value to the pointee of a pointer argument. /// template<typename T> bool assignPointee(TraceThreadListener &Listener, detect_calls::VarArgList<TraceThreadListener> const &Args, unsigned ArgIndex, T Value) const { if (ArgIndex >= Args.size()) return false; // We use the X-Macro to generate a two levels of switching. The outer // level matches the conversion, and the inner level gets the appropriate // type given the current Length. switch (Conversion) { case Specifier::none: return false; #define SEEC_PP_CHECK_LENGTH(LENGTH, TYPE) \ case LengthModifier::LENGTH: \ return assignPointee<TYPE>(Listener, Args, ArgIndex, Value); #define SEEC_SCAN_FORMAT_SPECIFIER(ID, CHR, WSPACE, SUPPRESS, LENS) \ case Specifier::ID: \ switch (Length) { \ SEEC_PP_APPLY(SEEC_PP_CHECK_LENGTH, LENS) \ default: return false; \ } #include "seec/Trace/ScanFormatSpecifiers.def" #undef SEEC_PP_CHECK_LENGTH } llvm_unreachable("illegal conversion specifier"); return false; } /// \brief Find and read the first scan conversion specified in String. /// /// If no '%' is found, then the returned ScanConversionSpecifier will /// be default-constructed (in particular, its Start value will be nullptr). /// /// If a '%' is found but no valid conversion specifier is detected, then the /// returned ScanConversionSpecifier's End value will be nullptr. /// static ScanConversionSpecifier readNextFrom(char const * const String); }; } // namespace trace (in seec) } // namespace seec #endif // SEEC_TRACE_SCANFORMATSPECIFIERS_HPP
33.170868
80
0.61113
[ "vector" ]
689c23e443f096b817b33aa949f0f66e4564fb42
2,452
cpp
C++
Source/hypernet/BayesianOptimizerTrainer.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
66
2015-01-05T02:31:21.000Z
2021-04-11T18:45:42.000Z
Source/hypernet/BayesianOptimizerTrainer.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
null
null
null
Source/hypernet/BayesianOptimizerTrainer.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
16
2015-01-23T19:55:24.000Z
2021-11-07T20:41:22.000Z
/* AI Lib Copyright (C) 2014 Eric Laukien This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <hypernet/BayesianOptimizerTrainer.h> #include <algorithm> using namespace hn; BayesianOptimizerTrainer::BayesianOptimizerTrainer() : _runsPerExperiment(4), _fitness(0.0f) {} void BayesianOptimizerTrainer::create(const Config &config, float minWeight, float maxWeight, std::mt19937 &generator, float activationMultiplier) { _hyperNet.createRandom(config, 10000, 0.02f, -2.0f, 2.0f, generator, activationMultiplier); std::vector<float> weights; _hyperNet.getWeightsVector(weights); std::vector<float> minBounds(weights.size(), minWeight); std::vector<float> maxBounds(weights.size(), maxWeight); _optimizer.create(weights.size(), minBounds, maxBounds); _optimizer.generateNewVariables(generator); _hyperNet.createFromWeightsVector(config, _optimizer.getCurrentVariables()); } void BayesianOptimizerTrainer::evaluate(const Config &config, std::mt19937 &generator) { _fitness = 0.0f; for (size_t i = 0; i < _experiments.size(); i++) for (size_t j = 0; j < _runsPerExperiment; j++) _fitness += _experiments[i]->getExperimentWeight() * _experiments[i]->evaluate(_hyperNet, config, generator); _fitness /= _experiments.size() * _runsPerExperiment; _optimizer.update(_fitness); } void BayesianOptimizerTrainer::update(const Config &config, std::mt19937 &generator) { _optimizer.generateNewVariables(generator); _hyperNet.createFromWeightsVector(config, _optimizer.getCurrentVariables()); } void BayesianOptimizerTrainer::writeBestToStream(std::ostream &os) const { _hyperNet.writeToStream(os); }
36.058824
149
0.763458
[ "vector" ]
68a1a3885fb1acb46fe467a0213fa2598a194505
660
cpp
C++
leetcode/Hashmap/1.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/1.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/1.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
#include<iostream> #include<unordered_map> #include<vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; unordered_map<int,int> record; for(int i = 0; i < nums.size(); i++){ record[nums[i]] = i; } for(int i = 0; i < nums.size(); i++){ unordered_map<int,int>::iterator iter = record.find(target - nums[i]); if(iter != record.end() && iter->second != i){ return {i, iter->second}; } } throw invalid_argument("the input has no solution"); } };
30
83
0.519697
[ "vector" ]
68a7651c20b7426058a8afe319e477bfe440cf26
1,803
cpp
C++
DSFactoryDemo/components/greetdemo.GreetManagerImpl/src-gen/GreetManagerImpl_wrapper.cpp
magnet/ds4cpp
6afd0a226c8631a8e5e0359571c02e41879cb6e4
[ "Apache-2.0" ]
5
2017-05-27T01:45:52.000Z
2021-06-16T05:52:44.000Z
DSFactoryDemo/components/greetdemo.GreetManagerImpl/src-gen/GreetManagerImpl_wrapper.cpp
magnet/ds4cpp
6afd0a226c8631a8e5e0359571c02e41879cb6e4
[ "Apache-2.0" ]
null
null
null
DSFactoryDemo/components/greetdemo.GreetManagerImpl/src-gen/GreetManagerImpl_wrapper.cpp
magnet/ds4cpp
6afd0a226c8631a8e5e0359571c02e41879cb6e4
[ "Apache-2.0" ]
1
2020-11-26T02:39:30.000Z
2020-11-26T02:39:30.000Z
/* * GreetManagerImplWrapper.cpp * Wrapper for greetdemo.GreetManagerImpl */ #include "greetdemo.GreetManagerImpl/include/GreetManagerImpl.hpp" #include <usBase.h> #include <ServiceUtils.h> /** * @class GreetManagerImplWrapper * The wrapper class for component greetdemo::GreetManagerImpl * (provides inheritance with a generic base class for typing purposes) */ class GreetManagerImplWrapper: public ::us::Base, public greetdemo::GreetManagerImpl { }; extern "C" { DS_ABI_EXPORT GreetManagerImplWrapper* __greetdemo__GreetManagerImpl__create() { return new GreetManagerImplWrapper; } DS_ABI_EXPORT void __greetdemo__GreetManagerImpl__activate(GreetManagerImplWrapper* object) { object->activate(); } DS_ABI_EXPORT void __greetdemo__GreetManagerImpl__add_greetdemo__GreetProvider(GreetManagerImplWrapper* object, ::us::Base *service) { greetdemo::GreetProvider* lservice = dynamic_cast<greetdemo::GreetProvider*>(service); object->addGreetProvider(lservice); } DS_ABI_EXPORT void __greetdemo__GreetManagerImpl__remove_greetdemo__GreetProvider(GreetManagerImplWrapper* object, ::us::Base *service) { greetdemo::GreetProvider* lservice = dynamic_cast<greetdemo::GreetProvider*>(service); object->removeGreetProvider(lservice); } DS_ABI_EXPORT void __greetdemo__GreetManagerImpl__set_ds4cpp__ComponentFactory(GreetManagerImplWrapper* object, ::us::Base *service) { ds4cpp::ComponentFactory* lservice = dynamic_cast<ds4cpp::ComponentFactory*>(service); object->setComponentFactory(lservice); } DS_ABI_EXPORT void __greetdemo__GreetManagerImpl__unset_ds4cpp__ComponentFactory(GreetManagerImplWrapper* object, ::us::Base *service) { ds4cpp::ComponentFactory* lservice = dynamic_cast<ds4cpp::ComponentFactory*>(service); object->unsetComponentFactory(lservice); } } // extern "C"
31.631579
135
0.815862
[ "object" ]
68aba1255901084422bc06b6209ee37296738a11
3,697
cpp
C++
src/sysex/retmixerinputcontrol.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2018-07-16T14:13:10.000Z
2021-02-07T06:43:57.000Z
src/sysex/retmixerinputcontrol.cpp
dehnhardt/iconnconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2017-09-06T19:38:15.000Z
2021-01-04T17:54:02.000Z
src/sysex/retmixerinputcontrol.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
10
2018-03-03T14:50:03.000Z
2020-09-30T18:08:55.000Z
#include "retmixerinputcontrol.h" RetMixerInputControl::RetMixerInputControl(Device *device) : PortSysExMessage(RET_MIXER_INPUT_CONTROL, SysExMessage::QUERY, device) { // m_vPanCurves = std::vector<pk::PanCurve>(); } RetMixerInputControl::~RetMixerInputControl() {} void RetMixerInputControl::parseAnswerData() { unsigned long offset = 0; m_iCommandVersionNumber = m_pData->at(0); m_iPortId = parsePortId(); parseExistFlags(m_pData->at(3)); parseEditFlags(m_pData->at(4)); offset = 5; if (m_bHasPanControl) { m_iMaxPanValue = static_cast<int>(MIDI::byteJoin7bit(m_pData, offset, 3)); offset += 3; m_iNumberOfPanCurves = m_pData->at(offset); offset++; for (unsigned int i = 1; i <= m_iNumberOfPanCurves; i++) { m_vPanCurves.push_back(pk::PanCurve(m_pData->at(offset))); offset++; } } if (m_bHasVolumeControl) { m_iMinimumVolumeValue = MIDI::bytesToSignedInt(m_pData, offset, 3); offset += 3; m_iMaximumVolumeValue = MIDI::bytesToSignedInt(m_pData, offset, 3); offset += 3; m_iVolumeResolution = MIDI::bytesToSignedInt(m_pData, offset, 3); offset += 3; } } void RetMixerInputControl::parseExistFlags(unsigned char exist_flags) { m_bHasControls = exist_flags > 0; m_bHasPanControl = (exist_flags & 64); m_bHasInvertControl = (exist_flags & 32); m_bHasStereoLinkControl = (exist_flags & 16); m_bHasSoloPFLControl = (exist_flags & 8); m_bHasSoloControl = (exist_flags & 4); m_bHasMuteControl = (exist_flags & 2); m_bHasVolumeControl = (exist_flags & 1); } void RetMixerInputControl::parseEditFlags(unsigned char edit_flags) { m_bPanControlEditable = edit_flags & 64; m_bInvertControlEditable = edit_flags & 32; m_bStereoLinkControlEditable = edit_flags & 16; m_bSoloPFLControlEditable = edit_flags & 8; m_bSoloControlEditable = edit_flags & 4; m_bMuteControlEditable = edit_flags & 2; m_bVolumeControlEditable = edit_flags & 1; } bool RetMixerInputControl::hasControls() const { return m_bHasControls; } bool RetMixerInputControl::hasVolumeControl() const { return m_bHasVolumeControl; } bool RetMixerInputControl::hasMuteControl() const { return m_bHasMuteControl; } bool RetMixerInputControl::hasSoloControl() const { return m_bHasSoloControl; } bool RetMixerInputControl::hasSoloPFLControl() const { return m_bHasSoloPFLControl; } bool RetMixerInputControl::hasStereoLinkControl() const { return m_bHasStereoLinkControl; } bool RetMixerInputControl::hasInvertControl() const { return m_bHasInvertControl; } bool RetMixerInputControl::hasPanControl() const { return m_bHasPanControl; } bool RetMixerInputControl::getVolumeControlEditable() const { return m_bVolumeControlEditable; } bool RetMixerInputControl::getMuteControlEditable() const { return m_bMuteControlEditable; } bool RetMixerInputControl::getSoloControlEditable() const { return m_bSoloControlEditable; } bool RetMixerInputControl::getSoloPFLControlEditable() const { return m_bSoloPFLControlEditable; } bool RetMixerInputControl::getStereoLinkControlEditable() const { return m_bStereoLinkControlEditable; } bool RetMixerInputControl::getInvertControlEditable() const { return m_bInvertControlEditable; } bool RetMixerInputControl::getPanControlEditable() const { return m_bPanControlEditable; } int RetMixerInputControl::getMaxPanValue() const { return m_iMaxPanValue; } unsigned int RetMixerInputControl::getNumberOfPanCurves() const { return m_iNumberOfPanCurves; } int RetMixerInputControl::getMinimumVolumeValue() const { return m_iMinimumVolumeValue; } int RetMixerInputControl::getMaximumVolumeValue() const { return m_iMaximumVolumeValue; } int RetMixerInputControl::getVolumeResolution() const { return m_iVolumeResolution; }
28.882813
79
0.784961
[ "vector" ]
68abc83cefbc49d06dc925986281a3cc48504ac9
1,281
cpp
C++
codes/mock/14/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/14/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/14/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//misaka and rin will carry me to cm #include <iostream> #include <cstdio> #include <cstring> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <array> #include <tuple> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; ll arr[MX], srt[MX]; //ll b[MX]; int n, q; int z; void solve(){ cin >> n >> q; z = 0; for(int i = 0; i<n; i++){ cin >> arr[i]; if(arr[i] == 0) z++; } if(z > q){ cout << "Impossible"; //more free books than allowed return ; }else if(q == n){ cout << "Richman"; //he will always buy enough books return ; } ll tot = 0, b = 0, ind = 0; for(int i = 0; i<n; i++){ ind = i; if(b + z == q) break; if(arr[i]){ b++; tot += arr[i]; } } ll next = int_max; for(int i = ind; i<n; i++){ if(arr[i]){ next = min(next, arr[i]); } } ll ans = tot + next - 1; //cant bring enough money to buy the next book cout << ans; } int main(){ cin.tie(0) -> sync_with_stdio(0); int T = 1; cin >> T; while(T--){ solve(); if(T) cout << "\n"; } return 0; }
16.423077
72
0.557377
[ "vector" ]
68b184d418e3f45c45616f991813fbb3bb830e1d
30,341
cpp
C++
src/hgeparticle/hgeparticle.cpp
keestux/tuxcap
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
[ "MIT-0" ]
2
2017-10-10T20:44:49.000Z
2022-02-09T09:08:04.000Z
src/hgeparticle/hgeparticle.cpp
keestux/tuxcap
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
[ "MIT-0" ]
null
null
null
src/hgeparticle/hgeparticle.cpp
keestux/tuxcap
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
[ "MIT-0" ]
2
2017-11-23T13:23:30.000Z
2019-12-12T21:41:02.000Z
/* ** Haaf's Game Engine 1.5 ** Copyright (C) 2003-2004, Relish Games ** hge.relishgames.com ** ** hgeParticleSystem helper class implementation ** Hacked on by ** ** Kevin Lynx ** James Poag ** W.P. van Paassen ** Nicolas A. Barriga */ #include <stdio.h> #include <string.h> // memcpy #include <string> #include <limits.h> #include <assert.h> #include <map> #include "SexyMatrix.h" #include "SexyAppBase.h" #include "SWTri.h" #include "PakInterface.h" #include "Logging.h" #include "hgeparticle.h" #include "hgeRandom.h" using namespace HGE; bool hgeParticleSystem::m_bInitRandom = false; class InfoCache { public: InfoCache(const std::string & fname) : _fname(fname), _bufsize(0), _buf(NULL), _info() {} const struct hgeParticleSystemInfo * getInfo() const { return &_info; } int getInt32(int offset) const; float getFloat(int offset) const; bool getBool32(int offset) const; static InfoCache * find(const std::string & fname); static InfoCache * lookup_add(const std::string & fname); std::string _fname; int _bufsize; unsigned char * _buf; struct hgeParticleSystemInfo _info; static std::map<std::string, InfoCache*> _cache; }; std::map<std::string, InfoCache*> InfoCache::_cache; InfoCache * InfoCache::find(const std::string & fname) { std::map<std::string, InfoCache*>::const_iterator it; it = _cache.find(fname); if (it != _cache.end()) { return it->second; } return NULL; } InfoCache * InfoCache::lookup_add(const std::string & fname) { InfoCache * ic = find(fname); if (ic) { return ic; } ic = new InfoCache(fname); std::string fullfilename = gSexyAppBase->GetAppResourceFileName(fname); bool pak = GetPakPtr()->isLoaded(); if (pak) { PFILE *pfp = NULL; pfp = p_fopen(fullfilename.c_str(), "rb"); if (pfp == NULL) { // TODO. Throw exception. return NULL; } ic->_bufsize = GetPakPtr()->FSize(pfp); // Read file contents ic->_buf = new unsigned char[ic->_bufsize]; int nr = p_fread(ic->_buf, ic->_bufsize, 1, pfp); if (nr != 1) { // TODO. Throw exception. return NULL; } } else { FILE *fp = NULL; fp = fopen(fullfilename.c_str(), "rb"); if (fp == NULL) { // TODO. Throw exception. return NULL; } // Use the cheap trick to determine the file size fseek(fp, 0L, SEEK_END); ic->_bufsize = ftell(fp); fseek(fp, 0L, SEEK_SET); // rewind // Read file contents ic->_buf = new unsigned char[ic->_bufsize]; int nr = fread(ic->_buf, ic->_bufsize, 1, fp); if (nr != 1) { // TODO. Throw exception. return NULL; } } ic->_info.sprite = NULL; ic->_info.nEmission = ic->getInt32(4); ic->_info.fLifetime = ic->getFloat(8); ic->_info.fParticleLifeMin = ic->getFloat(12); ic->_info.fParticleLifeMax = ic->getFloat(16); ic->_info.fDirection = ic->getFloat(20); ic->_info.fSpread = ic->getFloat(24); ic->_info.bRelative = ic->getBool32(28); ic->_info.fSpeedMin = ic->getFloat(32); ic->_info.fSpeedMax = ic->getFloat(36); ic->_info.fGravityMin = ic->getFloat(40); ic->_info.fGravityMax = ic->getFloat(44); ic->_info.fRadialAccelMin = ic->getFloat(48); ic->_info.fRadialAccelMax = ic->getFloat(52); ic->_info.fTangentialAccelMin = ic->getFloat(56); ic->_info.fTangentialAccelMax = ic->getFloat(60); ic->_info.fSizeStart = ic->getFloat(64); ic->_info.fSizeEnd = ic->getFloat(68); ic->_info.fSizeVar = ic->getFloat(72); ic->_info.fSpinStart = ic->getFloat(76); ic->_info.fSpinEnd = ic->getFloat(80); ic->_info.fSpinVar = ic->getFloat(84); ic->_info.colColorStart.r = ic->getFloat(88); ic->_info.colColorStart.g = ic->getFloat(92); ic->_info.colColorStart.b = ic->getFloat(96); ic->_info.colColorStart.a = ic->getFloat(100); ic->_info.colColorEnd.r = ic->getFloat(104); ic->_info.colColorEnd.g = ic->getFloat(108); ic->_info.colColorEnd.b = ic->getFloat(112); ic->_info.colColorEnd.a = ic->getFloat(116); ic->_info.fColorVar = ic->getFloat(120); ic->_info.fAlphaVar = ic->getFloat(124); _cache[fname] = ic; return ic; } int InfoCache::getInt32(int offset) const { #if __BIG_ENDIAN__ char tmp[4]; for (int i = 0; i < 4; i++) { tmp[i] = _buf[offset + (4-1) - i]; } return *(int*)tmp; #else return *(int*)&_buf[offset]; #endif } bool InfoCache::getBool32(int offset) const { return getInt32(offset) != 0 ? true : false; } // For float we need to do the same as for int32 float InfoCache::getFloat(int offset) const { #if __BIG_ENDIAN__ char tmp[4]; for (int i = 0; i < 4; i++) { tmp[i] = _buf[offset + (4-1) - i]; } return *(float*)tmp; #else return *(float*)&_buf[offset]; #endif } hgeParticleSystem::hgeParticleSystem(const char *filename, DDImage *sprite, float fps /*= 0.0f*/, bool parseMetaData /*= true*/, bool old_format /*=true*/) // Change default behavior in header { mLogFacil = NULL; #ifdef DEBUG mLogFacil = LoggerFacil::find("hgeparticle"); Logger::tlog(mLogFacil, 1, Logger::format("create new from file: '%s', parseMetaData=%s", filename, parseMetaData?"True":"False")); #endif // LOAD DEFAULTS mbAdditiveBlend = false; mPlayMode = PLAY_ONCE; mAnimPlaying = false; mPlayMarker = 0; mPlayTime = 0.0f; mPlayTimer = 0.0f; mPlayTimerStepSize = 0.0f; mPingPong = PING; bOldFormat = old_format; vecLocation.x = vecPrevLocation.x = 0.0f; vecLocation.y = vecPrevLocation.y = 0.0f; fTx = fTy = 0; fScale = 1.0f; fParticleScale = 1.0f; fEmissionResidue = 0.0f; nParticlesAlive = 0; fAge = -2.0; if (fps != 0.0f) fUpdSpeed = 1.0f / fps; else fUpdSpeed = 0.0f; fResidue = 0.0f; rectBoundingBox.Clear(); bUpdateBoundingBox = false; InitRandom(); bInitOK = false; doNotDraw = false; InfoCache * ic = InfoCache::find(filename); bool from_cache = true; if (ic == NULL) { from_cache = false; } else { Logger::tlog(mLogFacil, 1, Logger::format("reading from cache")); } ic = InfoCache::lookup_add(filename); if (ic == NULL) { // Oops return; } info = *ic->getInfo(); int additiveBlendTmp = ic->getInt32(0); mbAdditiveBlend = (((additiveBlendTmp) >> 16) & 2) == 0; if (!from_cache) { #ifdef DEBUG dumpInfo(filename); #endif } info.sprite = sprite; if (parseMetaData) { // TODO assert(0); #if __BIG_ENDIAN__ // The parse functions won't work, yet. // One way to do this is to read the rest of the file in a buffer (via PAK or normal) // and to have a parsing function that uses get_float, get_bool, get_int32 etc assert(0); #endif } bInitOK = true; } #ifdef DEBUG void hgeParticleSystem::dumpInfo(const char *fname) const { #define myLogInt(m) Logger::tlog(mLogFacil, 2, Logger::format(" " #m "='%d'", info.m)) #define myLogFlt(m) Logger::tlog(mLogFacil, 2, Logger::format(" " #m "='%f'", info.m)) myLogInt(nEmission); myLogFlt(fLifetime); myLogFlt(fParticleLifeMin); myLogFlt(fParticleLifeMax); myLogFlt(fDirection); myLogFlt(fSpread); Logger::tlog(mLogFacil, 2, Logger::format("bRelative='%d'", info.bRelative)); } #endif hgeParticleSystem::hgeParticleSystem(hgeParticleSystemInfo *psi, float fps) { mLogFacil = NULL; #ifdef DEBUG mLogFacil = LoggerFacil::find("hgeparticle"); Logger::tlog(mLogFacil, 1, "create new from hgeParticleSystemInfo"); #endif info = *psi; vecLocation.x = vecPrevLocation.x = 0.0f; vecLocation.y = vecPrevLocation.y = 0.0f; fTx = fTy = 0; fScale = 1.0f; fEmissionResidue = 0.0f; nParticlesAlive = 0; fAge = -2.0; if (fps != 0.0f) fUpdSpeed = 1.0f / fps; else fUpdSpeed = 0.0f; fResidue = 0.0f; rectBoundingBox.Clear(); bUpdateBoundingBox = false; mbAdditiveBlend = false; InitRandom(); mPlayMode = STOPPED; mAnimPlaying = false; mPlayMarker = 0; bOldFormat = true; bInitOK = true; doNotDraw = false; } hgeParticleSystem::hgeParticleSystem(const hgeParticleSystem &ps) { mLogFacil = NULL; #ifdef DEBUG mLogFacil = LoggerFacil::find("hgeparticle"); Logger::tlog(mLogFacil, 1, "create new from copy"); #endif //*this = ps; memcpy(this, &ps, sizeof (hgeParticleSystem)); InitRandom(); mPlayMode = STOPPED; mAnimPlaying = false; mPlayMarker = 0; // TODO. Check if other class members must be initialized } void hgeParticleSystem::ParseMetaData(void * _ic) { // TODO. Use the InfoCache buffer assert(0); #if 0 InfoCache * ic = (InfoCache *)_ic; int offset = 128; while (offset < ic->getBufsize()) { unsigned char aMetaTag = ic->getUint8(offset); offset += 1; switch (aMetaTag) { // ... } } unsigned char aMetaTag = -1; // If you Change Size of MetaTag, change it in SaveMetaData char aBuffer[PATH_MAX] = {0}; memset(aBuffer, 0, PATH_MAX); //No Dirty Strings int aSize = 0; // Read Returns Zero when it doesn't read something while (fread(&aMetaTag, sizeof (aMetaTag), 1, aFile)) { switch (aMetaTag) { case ADDITIVE: fread(&mbAdditiveBlend, sizeof (bool), 1, aFile); break; case POSITION: //hgeVector vecPrevLocation; // => float x,y; if (fread(&vecPrevLocation, sizeof (vecPrevLocation), 1, aFile)) { vecLocation.x = vecPrevLocation.x; vecLocation.y = vecPrevLocation.y; } break; case TEXTURE_PATH: //length prefix string if (fread(&aSize, sizeof (int), 1, aFile) && fread(aBuffer, 1, aSize, aFile)) { // Attemp to Load Texture mTextureName = StrFormat("%s", aBuffer); if (mTextureName != "") { DDImage* aTempImage = gSexyAppBase->GetImage(mTextureName); if (aTempImage != NULL) { info.sprite = aTempImage; } } } break; case POLYGON_POINTS: if (fread(&aSize, sizeof (int), 1, aFile)) { for (int i = 0; i < aSize; ++i) { //Point aPoint // => float mX, mY; Sexy::Point aPoint; if (fread(&aPoint, sizeof (Sexy::Point), 1, aFile)) mPolygonClipPoints.push_back(aPoint); } } break; case WAY_POINTS: if (fread(&aSize, sizeof (int), 1, aFile)) { for (int i = 0; i < aSize; ++i) { //float mX, mY; Sexy::Point aPoint; if (fread(&aPoint, sizeof (Sexy::Point), 1, aFile)) mWayPoints.push_back(aPoint); } } break; case ANIMATION_DATA: { //int mPlayMode; //float mPlayTime; size_t br = fread(&mPlayTime, sizeof (mPlayTime), 1, aFile); br = fread(&mPlayMode, sizeof (mPlayMode), 1, aFile); break; } // TODO: Add your additional meta tags to this switch tree } } #endif } void hgeParticleSystem::SaveFile(const char *filename) { // This does not sense. // info.sprite shouldn't be written and the first 4 bytes are for the mAdditiveBlend assert(0); FILE* aFile = fopen(filename, "w+b"); if (aFile != NULL) { // Standard Format fwrite(&(info), sizeof (hgeParticleSystemInfo), 1, aFile); // Extended Format SaveMetaData(aFile); fclose(aFile); } } void hgeParticleSystem::SaveMetaData(FILE* aFile) { // First solve the endianness assert(0); unsigned char aMetaTag = 0; // If you change size of MetaTag, besure to change it in ParseMetaData int aSize = 0; // Step 1: Write Meta Tag // Step 2: Write Size Info (Optional) // Step 3: Write Meta Data aMetaTag = ADDITIVE; size_t bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); bw = fwrite(&mbAdditiveBlend, sizeof (bool), 1, aFile); aMetaTag = POSITION; bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); bw = fwrite(&vecLocation, sizeof (vecLocation), 1, aFile); aMetaTag = TEXTURE_PATH; bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); aSize = (int) mTextureName.size(); bw = fwrite(&aSize, sizeof (int), 1, aFile); bw = fwrite(mTextureName.c_str(), 1, aSize, aFile); aMetaTag = POLYGON_POINTS; bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); aSize = (int) mPolygonClipPoints.size(); bw = fwrite(&aSize, sizeof (int), 1, aFile); for (unsigned int i = 0; i < mPolygonClipPoints.size(); ++i) { bw = fwrite(&mPolygonClipPoints[i], sizeof (Sexy::Point), 1, aFile); } aMetaTag = WAY_POINTS; bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); aSize = (int) mWayPoints.size(); bw = fwrite(&aSize, sizeof (int), 1, aFile); for (unsigned int i = 0; i < mWayPoints.size(); ++i) { bw = fwrite(&mWayPoints[i], sizeof (Sexy::Point), 1, aFile); } aMetaTag = ANIMATION_DATA; bw = fwrite(&aMetaTag, sizeof (aMetaTag), 1, aFile); bw = fwrite(&mPlayTime, sizeof (mPlayTime), 1, aFile); bw = fwrite(&mPlayMode, sizeof (mPlayMode), 1, aFile); } void hgeParticleSystem::Update(float fDeltaTime) { if (fUpdSpeed == 0.0f) _update(fDeltaTime); else { fResidue += fDeltaTime; if (fResidue >= fUpdSpeed) { _update(fUpdSpeed); while (fResidue >= fUpdSpeed) fResidue -= fUpdSpeed; } } } void hgeParticleSystem::_update(float fDeltaTime) { int i; float ang; hgeParticle *par; hgeVector vecAccel, vecAccel2; if (fAge >= 0) { fAge += fDeltaTime; if (fAge >= info.fLifetime) fAge = -2.0f; } // Play Animation if (mAnimPlaying) _updatePlay(fDeltaTime); // update all alive particles if (bUpdateBoundingBox) rectBoundingBox.Clear(); par = particles; for (i = 0; i < nParticlesAlive; i++) { par->fAge += fDeltaTime; if (par->fAge >= par->fTerminalAge) { nParticlesAlive--; memcpy(par, &particles[nParticlesAlive], sizeof (hgeParticle)); i--; continue; } vecAccel = par->vecLocation - vecLocation; vecAccel.Normalize(); vecAccel2 = vecAccel; vecAccel *= par->fRadialAccel; // vecAccel2.Rotate(M_PI_2); // the following is faster ang = vecAccel2.x; vecAccel2.x = -vecAccel2.y; vecAccel2.y = ang; vecAccel2 *= par->fTangentialAccel; par->vecVelocity += (vecAccel + vecAccel2) * fDeltaTime; par->vecVelocity.y += par->fGravity*fDeltaTime; if (bOldFormat) par->vecLocation += par->vecVelocity; else par->vecLocation += par->vecVelocity * fDeltaTime; par->fSpin += par->fSpinDelta*fDeltaTime; par->fSize += par->fSizeDelta*fDeltaTime; par->colColor += par->colColorDelta*fDeltaTime; //-----use hgeColor if (bUpdateBoundingBox) rectBoundingBox.Encapsulate(par->vecLocation.x, par->vecLocation.y); par++; } // generate new particles if (fAge != -2.0f) { float fParticlesNeeded = info.nEmission * fDeltaTime + fEmissionResidue; int nParticlesCreated = (unsigned int) fParticlesNeeded; fEmissionResidue = fParticlesNeeded - nParticlesCreated; par = &particles[nParticlesAlive]; for (i = 0; i < nParticlesCreated; i++) { if (nParticlesAlive >= MAX_PARTICLES) break; par->fAge = 0.0f; //random par->fTerminalAge = Random_Float(info.fParticleLifeMin, info.fParticleLifeMax); par->vecLocation = vecPrevLocation + (vecLocation - vecPrevLocation) * Random_Float(0.0f, 1.0f); par->vecLocation.x += Random_Float(-2.0f, 2.0f); par->vecLocation.y += Random_Float(-2.0f, 2.0f); ang = info.fDirection - M_PI_2 + Random_Float(0, info.fSpread) - info.fSpread / 2.0f; if (info.bRelative) ang += (vecPrevLocation - vecLocation).Angle() + M_PI_2; par->vecVelocity.x = cosf(ang); par->vecVelocity.y = sinf(ang); par->vecVelocity *= Random_Float(info.fSpeedMin, info.fSpeedMax); par->fGravity = Random_Float(info.fGravityMin, info.fGravityMax); par->fRadialAccel = Random_Float(info.fRadialAccelMin, info.fRadialAccelMax); par->fTangentialAccel = Random_Float(info.fTangentialAccelMin, info.fTangentialAccelMax); par->fSize = Random_Float(info.fSizeStart, info.fSizeStart + (info.fSizeEnd - info.fSizeStart) * info.fSizeVar); par->fSizeDelta = (info.fSizeEnd - par->fSize) / par->fTerminalAge; par->fSpin = Random_Float(info.fSpinStart, info.fSpinStart + (info.fSpinEnd - info.fSpinStart) * info.fSpinVar); par->fSpinDelta = (info.fSpinEnd - par->fSpin) / par->fTerminalAge; ////-----use hgeColor par->colColor.r = Random_Float(info.colColorStart.r, info.colColorStart.r + (info.colColorEnd.r - info.colColorStart.r) * info.fColorVar); par->colColor.g = Random_Float(info.colColorStart.g, info.colColorStart.g + (info.colColorEnd.g - info.colColorStart.g) * info.fColorVar); par->colColor.b = Random_Float(info.colColorStart.b, info.colColorStart.b + (info.colColorEnd.b - info.colColorStart.b) * info.fColorVar); par->colColor.a = Random_Float(info.colColorStart.a, info.colColorStart.a + (info.colColorEnd.a - info.colColorStart.a) * info.fAlphaVar); par->colColorDelta.r = (info.colColorEnd.r - par->colColor.r) / par->fTerminalAge; par->colColorDelta.g = (info.colColorEnd.g - par->colColor.g) / par->fTerminalAge; par->colColorDelta.b = (info.colColorEnd.b - par->colColor.b) / par->fTerminalAge; par->colColorDelta.a = (info.colColorEnd.a - par->colColor.a) / par->fTerminalAge; if (bUpdateBoundingBox) rectBoundingBox.Encapsulate(par->vecLocation.x, par->vecLocation.y); nParticlesAlive++; par++; } } vecPrevLocation = vecLocation; } void hgeParticleSystem::_updatePlay(float fDeltaTime) { // Play WayPoints if (mAnimPlaying) { hgeVector anAnimPosVec; mPlayTimer += fDeltaTime; while (mPlayTimer > mPlayTimerStepSize) //Fast Forward! { mPlayTimer -= mPlayTimerStepSize; switch (mPlayMode) { case PLAY_ONCE: { if (++mPlayMarker >= (int) mWayPoints.size() - 1) { mAnimPlaying = false; } break; } case PLAY_LOOPED: { mPlayMarker = (mWayPoints.size() > 1) ? (++mPlayMarker) % (mWayPoints.size() - 1) : 0; break; } case PLAY_PINGPONGED: { switch (mPingPong) { case PING: { if (++mPlayMarker >= (int) mWayPoints.size()) { mPlayMarker = mWayPoints.size() - 1; mPingPong = PONG; } break; } case PONG: { if (--mPlayMarker < 0) { mPlayMarker = 0; mPingPong = PING; } break; } default: { mPingPong = PING; break; } } break; } default: { mAnimPlaying = false; break; } } } if (mAnimPlaying && mPlayMarker < (int) mWayPoints.size() - 1) { anAnimPosVec = hgeVector(mWayPoints[mPlayMarker + 1].mX - mWayPoints[mPlayMarker].mX, mWayPoints[mPlayMarker + 1].mY - mWayPoints[mPlayMarker].mY); anAnimPosVec.Normalize(); if (mPlayTimerStepSize != 0.0f) anAnimPosVec *= mPlayTimer / mPlayTimerStepSize; Point aPosPoint((int) (mWayPoints[mPlayMarker].mX + anAnimPosVec.x), (int) (mWayPoints[mPlayMarker].mY + anAnimPosVec.y)); MoveTo(aPosPoint.mX, aPosPoint.mY); } } } void hgeParticleSystem::MoveTo(float x, float y, bool bMoveParticles) { int i; float dx, dy; if (bMoveParticles) { dx = x - vecLocation.x; dy = y - vecLocation.y; for (i = 0; i < nParticlesAlive; i++) { particles[i].vecLocation.x += dx; particles[i].vecLocation.y += dy; } vecPrevLocation.x = vecPrevLocation.x + dx; vecPrevLocation.y = vecPrevLocation.y + dy; } else { if (fAge == -2.0) { vecPrevLocation.x = x; vecPrevLocation.y = y; } else { vecPrevLocation.x = vecLocation.x; vecPrevLocation.y = vecLocation.y; } } vecLocation.x = x; vecLocation.y = y; } void hgeParticleSystem::FireAt(float x, float y) { Stop(); MoveTo(x, y); Fire(); } void hgeParticleSystem::Play(int thePlayMode) { if (thePlayMode != MAX_PLAYMODES) mPlayMode = thePlayMode; if (mWayPoints.size() >= 2) { FireAt(mWayPoints[0].mX, mWayPoints[0].mY); mAnimPlaying = true; mPlayMarker = 0; mPlayTimerStepSize = (mPlayTime / mWayPoints.size() > 0) ? mPlayTime / mWayPoints.size() : 0.05f; mPlayTimer = 0.0f; } else mAnimPlaying = false; } void hgeParticleSystem::Fire() { if (info.fLifetime == -1.0f) fAge = -1.0f; else fAge = 0.0f; fResidue = 0.0; } void hgeParticleSystem::Stop(bool bKillParticles) { fAge = -2.0f; if (bKillParticles) { nParticlesAlive = 0; rectBoundingBox.Clear(); } } void hgeParticleSystem::Render(Graphics *g) { if (doNotDraw) return; // Check to make sure the texture is valid if (info.sprite == NULL) return; int blendMode = g->GetDrawMode(); if (mbAdditiveBlend && blendMode == Graphics::DRAWMODE_NORMAL) g->SetDrawMode(Graphics::DRAWMODE_ADDITIVE); else if (!mbAdditiveBlend && blendMode == Graphics::DRAWMODE_ADDITIVE) g->SetDrawMode(Graphics::DRAWMODE_NORMAL); g->SetColorizeImages(true); int i; //DWORD col; hgeParticle *par = particles; //col=info.sprite->GetColor(); Color col = g->GetColor(); /*****************************************************/ // This section sets up the poly points by wrapping // // the front around to the back. // /*****************************************************/ bool front_pushed = false; // Clip to Polygon 3 points is a triangle if (mPolygonClipPoints.size() > 2) { mPolygonClipPoints.push_back(mPolygonClipPoints.front()); front_pushed = true; } /*****************************************************/ /*****************************************************/ for (i = 0; i < nParticlesAlive; i++, par++) { /*****************************************************/ // Clip to Polygon: 3 points is a triangle plus the // // front pushed to the back // /*****************************************************/ if (mPolygonClipPoints.size() > 3) if (!wn_PnPoly(Point((int) (par->vecLocation.x + fTx), (int) (par->vecLocation.y + fTy)))) continue; /*****************************************************/ /*****************************************************/ //info.sprite->SetColor(par->colColor.GetHWColor()); //hgeColor col2( par->colColor.GetHWColor() ); DWORD col2 = par->colColor.GetHWColor(); //g->SetColor( Color( col2.r * 255, col2.g * 255, col2.b * 255, col2.a * 255 ) ); g->SetColor(Color(GETR(col2), GETG(col2), GETB(col2), GETA(col2))); //info.sprite->RenderEx(par->vecLocation.x+fTx, par->vecLocation.y+fTy, par->fSpin*particles[i].fAge, par->fSize); Transform t; SexyVector2 v; t.RotateRad(par->fSpin * particles[i].fAge); t.Scale(par->fSize*fParticleScale, par->fSize * fParticleScale); if (fScale == 1.0f) t.Translate(fTx, fTy); else { // grrrr, popcap should really improve their vector and point classes, this is ugly! //TODO use the stored location of the system in particle instead of vecLocation. This is to be used for scaling particlesystems which are moved around, currently this results in a funny effect v = SexyVector2(par->vecLocation.x - vecLocation.x, par->vecLocation.y - vecLocation.y); v *= fScale; v.x = vecLocation.x + v.x; v.y = vecLocation.y + v.y; t.Translate(fTx + v.x - par->vecLocation.x, fTy + v.y - par->vecLocation.y); } g->DrawImageTransformF(info.sprite, t, par->vecLocation.x, par->vecLocation.y); } if (front_pushed) mPolygonClipPoints.pop_back(); //info.sprite->SetColor(col); g->SetColor(col); g->SetColorizeImages(false); g->SetDrawMode(blendMode); } hgeRect *hgeParticleSystem::GetBoundingBox(hgeRect *rect) const { *rect = rectBoundingBox; rect->x1 *= fScale; rect->y1 *= fScale; rect->x2 *= fScale; rect->y2 *= fScale; return rect; } void hgeParticleSystem::InitRandom() { if (!m_bInitRandom) { Random_Seed(0); m_bInitRandom = true; } } // isLeft(): tests if a point is Left|On|Right of an infinite line. // Input: three points P0, P1, and P2 // Return: >0 for P2 left of the line through P0 and P1 // =0 for P2 on the line // <0 for P2 right of the line // See: the January 2001 Algorithm "Area of 2D and 3D Triangles and Polygons" inline int isLeft(Point P0, Point P1, Point P2) { return ( (P1.mX - P0.mX) * (P2.mY - P0.mY) - (P2.mX - P0.mX) * (P1.mY - P0.mY)); } //=================================================================== // wn_PnPoly(): winding number test for a point in a polygon // Input: P = a point, // V[] = vertex points of a polygon V[n+1] with V[n]=V[0] // Basically, the First vertex is duplicated after the last vertex // Return: wn = the winding number (=0 only if P is outside V[]) bool hgeParticleSystem::wn_PnPoly(Sexy::Point theTestPoint) { int wn = 0; // the winding number counter // loop through all edges of the polygon for (unsigned int i = 0; i < mPolygonClipPoints.size() - 1; i++) { // edge from mPolygonClipPoints[i] to mPolygonClipPoints[i+1] if (mPolygonClipPoints[i].mY <= theTestPoint.mY) { // start y <= theTestPoint.mY if (mPolygonClipPoints[i + 1].mY > theTestPoint.mY) // an upward crossing if (isLeft(mPolygonClipPoints[i], mPolygonClipPoints[i + 1], theTestPoint) > 0) // theTestPoint left of edge ++wn; // have a valid up intersect } else { // start y > theTestPoint.mY (no test needed) if (mPolygonClipPoints[i + 1].mY <= theTestPoint.mY) // a downward crossing if (isLeft(mPolygonClipPoints[i], mPolygonClipPoints[i + 1], theTestPoint) < 0) // theTestPoint right of edge --wn; // have a valid down intersect } } return (wn != 0); } //=================================================================== // cn_PnPoly(): crossing number test for a point in a polygon // Input: P = a point, // V[] = vertex points of a polygon V[n+1] with V[n]=V[0] // Return: 0 = outside, 1 = inside // This code is patterned after [Franklin, 2000] bool hgeParticleSystem::cn_PnPoly(Point theTestPoint) { int cn = 0; // the crossing number counter // loop through all edges of the polygon for (unsigned int i = 0; i < mPolygonClipPoints.size() - 1; i++) { // edge from mPolygonClipPoints[i] to mPolygonClipPoints[i+1] if (((mPolygonClipPoints[i].mY <= theTestPoint.mY) && (mPolygonClipPoints[i + 1].mY > theTestPoint.mY)) // an upward crossing || ((mPolygonClipPoints[i].mY > theTestPoint.mY) && (mPolygonClipPoints[i + 1].mY <= theTestPoint.mY))) { // a downward crossing // compute the actual edge-ray intersect x-coordinate float vt = (float) (theTestPoint.mY - mPolygonClipPoints[i].mY) / (mPolygonClipPoints[i + 1].mY - mPolygonClipPoints[i].mY); if (theTestPoint.mX < mPolygonClipPoints[i].mX + vt * (mPolygonClipPoints[i + 1].mX - mPolygonClipPoints[i].mX)) // theTestPoint.mX < intersect ++cn; // a valid crossing of y=theTestPoint.mY right of theTestPoint.mX } } return (cn & 1) != 0; // 0 if even (out), and 1 if odd (in) } unsigned int hgeParticleSystem::GetCollisionType() const { assert(false); //only supported in child class ParticlePhysicsSystem return 0; } unsigned int hgeParticleSystem::GetCollisionGroup() const { assert(false); //only supported in child class ParticlePhysicsSystem return 0; } void hgeParticleSystem::SetCollisionType(unsigned int type) { assert(false); //only supported in child class ParticlePhysicsSystem } void hgeParticleSystem::SetCollisionGroup(unsigned int group) { assert(false); //only supported in child class ParticlePhysicsSystem }
31.704284
205
0.572361
[ "render", "vector", "transform", "3d" ]
68bcde8a47c1fdb07c7ac026aa0fa55a4bed5cb3
86,321
cpp
C++
3.7.0/lldb-3.7.0.src/source/Symbol/ClangASTContext.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
3
2016-02-10T14:18:40.000Z
2018-02-05T03:15:56.000Z
3.7.0/lldb-3.7.0.src/source/Symbol/ClangASTContext.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
1
2016-02-10T15:40:03.000Z
2016-02-10T15:40:03.000Z
3.7.0/lldb-3.7.0.src/source/Symbol/ClangASTContext.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
null
null
null
//===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Symbol/ClangASTContext.h" // C Includes // C++ Includes #include <mutex> // std::once #include <string> // Other libraries and framework includes // Clang headers like to use NDEBUG inside of them to enable/disable debug // related features using "#ifndef NDEBUG" preprocessor blocks to do one thing // or another. This is bad because it means that if clang was built in release // mode, it assumes that you are building in release mode which is not always // the case. You can end up with functions that are defined as empty in header // files when NDEBUG is not defined, and this can cause link errors with the // clang .a files that you have since you might be missing functions in the .a // file. So we have to define NDEBUG when including clang headers to avoid any // mismatches. This is covered by rdar://problem/8691220 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF) #define LLDB_DEFINED_NDEBUG_FOR_CLANG #define NDEBUG // Need to include assert.h so it is as clang would expect it to be (disabled) #include <assert.h> #endif #include "clang/AST/ASTContext.h" #include "clang/AST/ASTImporter.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/Type.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Frontend/LangStandard.h" #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG #undef NDEBUG #undef LLDB_DEFINED_NDEBUG_FOR_CLANG // Need to re-include assert.h so it is as _we_ would expect it to be (enabled) #include <assert.h> #endif #include "lldb/Core/ArchSpec.h" #include "lldb/Core/dwarf.h" #include "lldb/Core/Flags.h" #include "lldb/Core/Log.h" #include "lldb/Core/RegularExpression.h" #include "lldb/Core/ThreadSafeDenseMap.h" #include "lldb/Core/UniqueCStringMap.h" #include "lldb/Expression/ASTDumper.h" #include "lldb/Symbol/ClangExternalASTSourceCommon.h" #include "lldb/Symbol/VerifyDecl.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/ObjCLanguageRuntime.h" #include <stdio.h> #include <mutex> using namespace lldb; using namespace lldb_private; using namespace llvm; using namespace clang; typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext*> ClangASTMap; static ClangASTMap & GetASTMap() { static ClangASTMap *g_map_ptr = nullptr; static std::once_flag g_once_flag; std::call_once(g_once_flag, []() { g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins }); return *g_map_ptr; } clang::AccessSpecifier ClangASTContext::ConvertAccessTypeToAccessSpecifier (AccessType access) { switch (access) { default: break; case eAccessNone: return AS_none; case eAccessPublic: return AS_public; case eAccessPrivate: return AS_private; case eAccessProtected: return AS_protected; } return AS_none; } static void ParseLangArgs (LangOptions &Opts, InputKind IK, const char* triple) { // FIXME: Cleanup per-file based stuff. // Set some properties which depend solely on the input kind; it would be nice // to move these to the language standard, and have the driver resolve the // input kind + language standard. if (IK == IK_Asm) { Opts.AsmPreprocessor = 1; } else if (IK == IK_ObjC || IK == IK_ObjCXX || IK == IK_PreprocessedObjC || IK == IK_PreprocessedObjCXX) { Opts.ObjC1 = Opts.ObjC2 = 1; } LangStandard::Kind LangStd = LangStandard::lang_unspecified; if (LangStd == LangStandard::lang_unspecified) { // Based on the base language, pick one. switch (IK) { case IK_None: case IK_AST: case IK_LLVM_IR: assert (!"Invalid input kind!"); case IK_OpenCL: LangStd = LangStandard::lang_opencl; break; case IK_CUDA: case IK_PreprocessedCuda: LangStd = LangStandard::lang_cuda; break; case IK_Asm: case IK_C: case IK_PreprocessedC: case IK_ObjC: case IK_PreprocessedObjC: LangStd = LangStandard::lang_gnu99; break; case IK_CXX: case IK_PreprocessedCXX: case IK_ObjCXX: case IK_PreprocessedObjCXX: LangStd = LangStandard::lang_gnucxx98; break; } } const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); Opts.LineComment = Std.hasLineComments(); Opts.C99 = Std.isC99(); Opts.CPlusPlus = Std.isCPlusPlus(); Opts.CPlusPlus11 = Std.isCPlusPlus11(); Opts.Digraphs = Std.hasDigraphs(); Opts.GNUMode = Std.isGNUMode(); Opts.GNUInline = !Std.isC99(); Opts.HexFloats = Std.hasHexFloats(); Opts.ImplicitInt = Std.hasImplicitInt(); Opts.WChar = true; // OpenCL has some additional defaults. if (LangStd == LangStandard::lang_opencl) { Opts.OpenCL = 1; Opts.AltiVec = 1; Opts.CXXOperatorNames = 1; Opts.LaxVectorConversions = 1; } // OpenCL and C++ both have bool, true, false keywords. Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; // if (Opts.CPlusPlus) // Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names); // // if (Args.hasArg(OPT_fobjc_gc_only)) // Opts.setGCMode(LangOptions::GCOnly); // else if (Args.hasArg(OPT_fobjc_gc)) // Opts.setGCMode(LangOptions::HybridGC); // // if (Args.hasArg(OPT_print_ivar_layout)) // Opts.ObjCGCBitmapPrint = 1; // // if (Args.hasArg(OPT_faltivec)) // Opts.AltiVec = 1; // // if (Args.hasArg(OPT_pthread)) // Opts.POSIXThreads = 1; // // llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility, // "default"); // if (Vis == "default") Opts.setValueVisibilityMode(DefaultVisibility); // else if (Vis == "hidden") // Opts.setVisibilityMode(LangOptions::Hidden); // else if (Vis == "protected") // Opts.setVisibilityMode(LangOptions::Protected); // else // Diags.Report(diag::err_drv_invalid_value) // << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis; // Opts.OverflowChecking = Args.hasArg(OPT_ftrapv); // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs // is specified, or -std is set to a conforming mode. Opts.Trigraphs = !Opts.GNUMode; // if (Args.hasArg(OPT_trigraphs)) // Opts.Trigraphs = 1; // // Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, // OPT_fno_dollars_in_identifiers, // !Opts.AsmPreprocessor); // Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings); // Opts.Microsoft = Args.hasArg(OPT_fms_extensions); // Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings); // if (Args.hasArg(OPT_fno_lax_vector_conversions)) // Opts.LaxVectorConversions = 0; // Opts.Exceptions = Args.hasArg(OPT_fexceptions); // Opts.RTTI = !Args.hasArg(OPT_fno_rtti); // Opts.Blocks = Args.hasArg(OPT_fblocks); Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault(); // Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar); // Opts.Freestanding = Args.hasArg(OPT_ffreestanding); // Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; // Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new); // Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions); // Opts.AccessControl = Args.hasArg(OPT_faccess_control); // Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors); // Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno); // Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99, // Diags); // Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime); // Opts.ObjCConstantStringClass = getLastArgValue(Args, // OPT_fconstant_string_class); // Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi); // Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior); // Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls); // Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); // Opts.Static = Args.hasArg(OPT_static_define); Opts.OptimizeSize = 0; // FIXME: Eliminate this dependency. // unsigned Opt = // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags); // Opts.Optimize = Opt != 0; unsigned Opt = 0; // This is the __NO_INLINE__ define, which just depends on things like the // optimization level and -fno-inline, not actually whether the backend has // inlining enabled. // // FIXME: This is affected by other options (-fno-inline). Opts.NoInlineDefine = !Opt; // unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags); // switch (SSP) { // default: // Diags.Report(diag::err_drv_invalid_value) // << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP; // break; // case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break; // case 1: Opts.setStackProtectorMode(LangOptions::SSPOn); break; // case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break; // } } ClangASTContext::ClangASTContext (const char *target_triple) : m_target_triple(), m_ast_ap(), m_language_options_ap(), m_source_manager_ap(), m_diagnostics_engine_ap(), m_target_options_rp(), m_target_info_ap(), m_identifier_table_ap(), m_selector_table_ap(), m_builtins_ap(), m_callback_tag_decl (nullptr), m_callback_objc_decl (nullptr), m_callback_baton (nullptr), m_pointer_byte_size (0) { if (target_triple && target_triple[0]) SetTargetTriple (target_triple); } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- ClangASTContext::~ClangASTContext() { if (m_ast_ap.get()) { GetASTMap().Erase(m_ast_ap.get()); } m_builtins_ap.reset(); m_selector_table_ap.reset(); m_identifier_table_ap.reset(); m_target_info_ap.reset(); m_target_options_rp.reset(); m_diagnostics_engine_ap.reset(); m_source_manager_ap.reset(); m_language_options_ap.reset(); m_ast_ap.reset(); } void ClangASTContext::Clear() { m_ast_ap.reset(); m_language_options_ap.reset(); m_source_manager_ap.reset(); m_diagnostics_engine_ap.reset(); m_target_options_rp.reset(); m_target_info_ap.reset(); m_identifier_table_ap.reset(); m_selector_table_ap.reset(); m_builtins_ap.reset(); m_pointer_byte_size = 0; } const char * ClangASTContext::GetTargetTriple () { return m_target_triple.c_str(); } void ClangASTContext::SetTargetTriple (const char *target_triple) { Clear(); m_target_triple.assign(target_triple); } void ClangASTContext::SetArchitecture (const ArchSpec &arch) { SetTargetTriple(arch.GetTriple().str().c_str()); } bool ClangASTContext::HasExternalSource () { ASTContext *ast = getASTContext(); if (ast) return ast->getExternalSource () != nullptr; return false; } void ClangASTContext::SetExternalSource (llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap) { ASTContext *ast = getASTContext(); if (ast) { ast->setExternalSource (ast_source_ap); ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true); //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true); } } void ClangASTContext::RemoveExternalSource () { ASTContext *ast = getASTContext(); if (ast) { llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap; ast->setExternalSource (empty_ast_source_ap); ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false); //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false); } } ASTContext * ClangASTContext::getASTContext() { if (m_ast_ap.get() == nullptr) { m_ast_ap.reset(new ASTContext (*getLanguageOptions(), *getSourceManager(), *getIdentifierTable(), *getSelectorTable(), *getBuiltinContext())); m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false); // This can be NULL if we don't know anything about the architecture or if the // target for an architecture isn't enabled in the llvm/clang that we built TargetInfo *target_info = getTargetInfo(); if (target_info) m_ast_ap->InitBuiltinTypes(*target_info); if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) { m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage(); //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage(); } GetASTMap().Insert(m_ast_ap.get(), this); } return m_ast_ap.get(); } ClangASTContext* ClangASTContext::GetASTContext (clang::ASTContext* ast) { ClangASTContext *clang_ast = GetASTMap().Lookup(ast); return clang_ast; } Builtin::Context * ClangASTContext::getBuiltinContext() { if (m_builtins_ap.get() == nullptr) m_builtins_ap.reset (new Builtin::Context()); return m_builtins_ap.get(); } IdentifierTable * ClangASTContext::getIdentifierTable() { if (m_identifier_table_ap.get() == nullptr) m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), nullptr)); return m_identifier_table_ap.get(); } LangOptions * ClangASTContext::getLanguageOptions() { if (m_language_options_ap.get() == nullptr) { m_language_options_ap.reset(new LangOptions()); ParseLangArgs(*m_language_options_ap, IK_ObjCXX, GetTargetTriple()); // InitializeLangOptions(*m_language_options_ap, IK_ObjCXX); } return m_language_options_ap.get(); } SelectorTable * ClangASTContext::getSelectorTable() { if (m_selector_table_ap.get() == nullptr) m_selector_table_ap.reset (new SelectorTable()); return m_selector_table_ap.get(); } clang::FileManager * ClangASTContext::getFileManager() { if (m_file_manager_ap.get() == nullptr) { clang::FileSystemOptions file_system_options; m_file_manager_ap.reset(new clang::FileManager(file_system_options)); } return m_file_manager_ap.get(); } clang::SourceManager * ClangASTContext::getSourceManager() { if (m_source_manager_ap.get() == nullptr) m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager())); return m_source_manager_ap.get(); } clang::DiagnosticsEngine * ClangASTContext::getDiagnosticsEngine() { if (m_diagnostics_engine_ap.get() == nullptr) { llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs()); m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions())); } return m_diagnostics_engine_ap.get(); } class NullDiagnosticConsumer : public DiagnosticConsumer { public: NullDiagnosticConsumer () { m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); } void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info) { if (m_log) { llvm::SmallVector<char, 32> diag_str(10); info.FormatDiagnostic(diag_str); diag_str.push_back('\0'); m_log->Printf("Compiler diagnostic: %s\n", diag_str.data()); } } DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const { return new NullDiagnosticConsumer (); } private: Log * m_log; }; DiagnosticConsumer * ClangASTContext::getDiagnosticConsumer() { if (m_diagnostic_consumer_ap.get() == nullptr) m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer); return m_diagnostic_consumer_ap.get(); } std::shared_ptr<TargetOptions> & ClangASTContext::getTargetOptions() { if (m_target_options_rp.get() == nullptr && !m_target_triple.empty()) { m_target_options_rp = std::make_shared<TargetOptions>(); if (m_target_options_rp.get() != nullptr) m_target_options_rp->Triple = m_target_triple; } return m_target_options_rp; } TargetInfo * ClangASTContext::getTargetInfo() { // target_triple should be something like "x86_64-apple-macosx" if (m_target_info_ap.get() == nullptr && !m_target_triple.empty()) m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions())); return m_target_info_ap.get(); } #pragma mark Basic Types static inline bool QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type) { uint64_t qual_type_bit_size = ast->getTypeSize(qual_type); if (qual_type_bit_size == bit_size) return true; return false; } ClangASTType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size) { return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (getASTContext(), encoding, bit_size); } ClangASTType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size) { if (!ast) return ClangASTType(); switch (encoding) { case eEncodingInvalid: if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy)) return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr()); break; case eEncodingUint: if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy)) return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy)) return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy)) return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy)) return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy)) return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty)) return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr()); break; case eEncodingSint: if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy)) return ClangASTType (ast, ast->CharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy)) return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy)) return ClangASTType (ast, ast->IntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy)) return ClangASTType (ast, ast->LongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy)) return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty)) return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr()); break; case eEncodingIEEE754: if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy)) return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy)) return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy)) return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr()); break; case eEncodingVector: // Sanity check that bit_size is a multiple of 8's. if (bit_size && !(bit_size & 0x7u)) return ClangASTType (ast, ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr()); break; } return ClangASTType(); } lldb::BasicType ClangASTContext::GetBasicTypeEnumeration (const ConstString &name) { if (name) { typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap; static TypeNameToBasicTypeMap g_type_map; static std::once_flag g_once_flag; std::call_once(g_once_flag, [](){ // "void" g_type_map.Append(ConstString("void").GetCString(), eBasicTypeVoid); // "char" g_type_map.Append(ConstString("char").GetCString(), eBasicTypeChar); g_type_map.Append(ConstString("signed char").GetCString(), eBasicTypeSignedChar); g_type_map.Append(ConstString("unsigned char").GetCString(), eBasicTypeUnsignedChar); g_type_map.Append(ConstString("wchar_t").GetCString(), eBasicTypeWChar); g_type_map.Append(ConstString("signed wchar_t").GetCString(), eBasicTypeSignedWChar); g_type_map.Append(ConstString("unsigned wchar_t").GetCString(), eBasicTypeUnsignedWChar); // "short" g_type_map.Append(ConstString("short").GetCString(), eBasicTypeShort); g_type_map.Append(ConstString("short int").GetCString(), eBasicTypeShort); g_type_map.Append(ConstString("unsigned short").GetCString(), eBasicTypeUnsignedShort); g_type_map.Append(ConstString("unsigned short int").GetCString(), eBasicTypeUnsignedShort); // "int" g_type_map.Append(ConstString("int").GetCString(), eBasicTypeInt); g_type_map.Append(ConstString("signed int").GetCString(), eBasicTypeInt); g_type_map.Append(ConstString("unsigned int").GetCString(), eBasicTypeUnsignedInt); g_type_map.Append(ConstString("unsigned").GetCString(), eBasicTypeUnsignedInt); // "long" g_type_map.Append(ConstString("long").GetCString(), eBasicTypeLong); g_type_map.Append(ConstString("long int").GetCString(), eBasicTypeLong); g_type_map.Append(ConstString("unsigned long").GetCString(), eBasicTypeUnsignedLong); g_type_map.Append(ConstString("unsigned long int").GetCString(), eBasicTypeUnsignedLong); // "long long" g_type_map.Append(ConstString("long long").GetCString(), eBasicTypeLongLong); g_type_map.Append(ConstString("long long int").GetCString(), eBasicTypeLongLong); g_type_map.Append(ConstString("unsigned long long").GetCString(), eBasicTypeUnsignedLongLong); g_type_map.Append(ConstString("unsigned long long int").GetCString(), eBasicTypeUnsignedLongLong); // "int128" g_type_map.Append(ConstString("__int128_t").GetCString(), eBasicTypeInt128); g_type_map.Append(ConstString("__uint128_t").GetCString(), eBasicTypeUnsignedInt128); // Miscellaneous g_type_map.Append(ConstString("bool").GetCString(), eBasicTypeBool); g_type_map.Append(ConstString("float").GetCString(), eBasicTypeFloat); g_type_map.Append(ConstString("double").GetCString(), eBasicTypeDouble); g_type_map.Append(ConstString("long double").GetCString(), eBasicTypeLongDouble); g_type_map.Append(ConstString("id").GetCString(), eBasicTypeObjCID); g_type_map.Append(ConstString("SEL").GetCString(), eBasicTypeObjCSel); g_type_map.Append(ConstString("nullptr").GetCString(), eBasicTypeNullPtr); g_type_map.Sort(); }); return g_type_map.Find(name.GetCString(), eBasicTypeInvalid); } return eBasicTypeInvalid; } ClangASTType ClangASTContext::GetBasicType (ASTContext *ast, const ConstString &name) { if (ast) { lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration (name); return ClangASTContext::GetBasicType (ast, basic_type); } return ClangASTType(); } uint32_t ClangASTContext::GetPointerByteSize () { if (m_pointer_byte_size == 0) m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid).GetPointerType().GetByteSize(nullptr); return m_pointer_byte_size; } ClangASTType ClangASTContext::GetBasicType (lldb::BasicType basic_type) { return GetBasicType (getASTContext(), basic_type); } ClangASTType ClangASTContext::GetBasicType (ASTContext *ast, lldb::BasicType basic_type) { if (ast) { clang_type_t clang_type = nullptr; switch (basic_type) { case eBasicTypeInvalid: case eBasicTypeOther: break; case eBasicTypeVoid: clang_type = ast->VoidTy.getAsOpaquePtr(); break; case eBasicTypeChar: clang_type = ast->CharTy.getAsOpaquePtr(); break; case eBasicTypeSignedChar: clang_type = ast->SignedCharTy.getAsOpaquePtr(); break; case eBasicTypeUnsignedChar: clang_type = ast->UnsignedCharTy.getAsOpaquePtr(); break; case eBasicTypeWChar: clang_type = ast->getWCharType().getAsOpaquePtr(); break; case eBasicTypeSignedWChar: clang_type = ast->getSignedWCharType().getAsOpaquePtr(); break; case eBasicTypeUnsignedWChar: clang_type = ast->getUnsignedWCharType().getAsOpaquePtr(); break; case eBasicTypeChar16: clang_type = ast->Char16Ty.getAsOpaquePtr(); break; case eBasicTypeChar32: clang_type = ast->Char32Ty.getAsOpaquePtr(); break; case eBasicTypeShort: clang_type = ast->ShortTy.getAsOpaquePtr(); break; case eBasicTypeUnsignedShort: clang_type = ast->UnsignedShortTy.getAsOpaquePtr(); break; case eBasicTypeInt: clang_type = ast->IntTy.getAsOpaquePtr(); break; case eBasicTypeUnsignedInt: clang_type = ast->UnsignedIntTy.getAsOpaquePtr(); break; case eBasicTypeLong: clang_type = ast->LongTy.getAsOpaquePtr(); break; case eBasicTypeUnsignedLong: clang_type = ast->UnsignedLongTy.getAsOpaquePtr(); break; case eBasicTypeLongLong: clang_type = ast->LongLongTy.getAsOpaquePtr(); break; case eBasicTypeUnsignedLongLong: clang_type = ast->UnsignedLongLongTy.getAsOpaquePtr(); break; case eBasicTypeInt128: clang_type = ast->Int128Ty.getAsOpaquePtr(); break; case eBasicTypeUnsignedInt128: clang_type = ast->UnsignedInt128Ty.getAsOpaquePtr(); break; case eBasicTypeBool: clang_type = ast->BoolTy.getAsOpaquePtr(); break; case eBasicTypeHalf: clang_type = ast->HalfTy.getAsOpaquePtr(); break; case eBasicTypeFloat: clang_type = ast->FloatTy.getAsOpaquePtr(); break; case eBasicTypeDouble: clang_type = ast->DoubleTy.getAsOpaquePtr(); break; case eBasicTypeLongDouble: clang_type = ast->LongDoubleTy.getAsOpaquePtr(); break; case eBasicTypeFloatComplex: clang_type = ast->FloatComplexTy.getAsOpaquePtr(); break; case eBasicTypeDoubleComplex: clang_type = ast->DoubleComplexTy.getAsOpaquePtr(); break; case eBasicTypeLongDoubleComplex: clang_type = ast->LongDoubleComplexTy.getAsOpaquePtr(); break; case eBasicTypeObjCID: clang_type = ast->getObjCIdType().getAsOpaquePtr(); break; case eBasicTypeObjCClass: clang_type = ast->getObjCClassType().getAsOpaquePtr(); break; case eBasicTypeObjCSel: clang_type = ast->getObjCSelType().getAsOpaquePtr(); break; case eBasicTypeNullPtr: clang_type = ast->NullPtrTy.getAsOpaquePtr(); break; } if (clang_type) return ClangASTType (ast, clang_type); } return ClangASTType(); } ClangASTType ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size) { ASTContext *ast = getASTContext(); #define streq(a,b) strcmp(a,b) == 0 assert (ast != nullptr); if (ast) { switch (dw_ate) { default: break; case DW_ATE_address: if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy)) return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr()); break; case DW_ATE_boolean: if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy)) return ClangASTType (ast, ast->BoolTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy)) return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy)) return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy)) return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr()); break; case DW_ATE_lo_user: // This has been seen to mean DW_AT_complex_integer if (type_name) { if (::strstr(type_name, "complex")) { ClangASTType complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2); return ClangASTType (ast, ast->getComplexType (complex_int_clang_type.GetQualType()).getAsOpaquePtr()); } } break; case DW_ATE_complex_float: if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy)) return ClangASTType (ast, ast->FloatComplexTy.getAsOpaquePtr()); else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy)) return ClangASTType (ast, ast->DoubleComplexTy.getAsOpaquePtr()); else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy)) return ClangASTType (ast, ast->LongDoubleComplexTy.getAsOpaquePtr()); else { ClangASTType complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2); return ClangASTType (ast, ast->getComplexType (complex_float_clang_type.GetQualType()).getAsOpaquePtr()); } break; case DW_ATE_float: if (streq(type_name, "float") && QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy)) return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr()); if (streq(type_name, "double") && QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy)) return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr()); if (streq(type_name, "long double") && QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy)) return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr()); // Fall back to not requring a name match if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy)) return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy)) return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy)) return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr()); break; case DW_ATE_signed: if (type_name) { if (streq(type_name, "wchar_t") && QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy) && (getTargetInfo() && TargetInfo::isTypeSigned (getTargetInfo()->getWCharType()))) return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr()); if (streq(type_name, "void") && QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy)) return ClangASTType (ast, ast->VoidTy.getAsOpaquePtr()); if (strstr(type_name, "long long") && QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy)) return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr()); if (strstr(type_name, "long") && QualTypeMatchesBitSize (bit_size, ast, ast->LongTy)) return ClangASTType (ast, ast->LongTy.getAsOpaquePtr()); if (strstr(type_name, "short") && QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy)) return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr()); if (strstr(type_name, "char")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy)) return ClangASTType (ast, ast->CharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy)) return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr()); } if (strstr(type_name, "int")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy)) return ClangASTType (ast, ast->IntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty)) return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr()); } } // We weren't able to match up a type name, just search by size if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy)) return ClangASTType (ast, ast->CharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy)) return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy)) return ClangASTType (ast, ast->IntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy)) return ClangASTType (ast, ast->LongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy)) return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty)) return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr()); break; case DW_ATE_signed_char: if (ast->getLangOpts().CharIsSigned && type_name && streq(type_name, "char")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy)) return ClangASTType (ast, ast->CharTy.getAsOpaquePtr()); } if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy)) return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr()); break; case DW_ATE_unsigned: if (type_name) { if (streq(type_name, "wchar_t")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy)) { if (!(getTargetInfo() && TargetInfo::isTypeSigned (getTargetInfo()->getWCharType()))) return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr()); } } if (strstr(type_name, "long long")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy)) return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr()); } else if (strstr(type_name, "long")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy)) return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr()); } else if (strstr(type_name, "short")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy)) return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr()); } else if (strstr(type_name, "char")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy)) return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr()); } else if (strstr(type_name, "int")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy)) return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty)) return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr()); } } // We weren't able to match up a type name, just search by size if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy)) return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy)) return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy)) return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy)) return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy)) return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty)) return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr()); break; case DW_ATE_unsigned_char: if (!ast->getLangOpts().CharIsSigned && type_name && streq(type_name, "char")) { if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy)) return ClangASTType (ast, ast->CharTy.getAsOpaquePtr()); } if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy)) return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr()); if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy)) return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr()); break; case DW_ATE_imaginary_float: break; case DW_ATE_UTF: if (type_name) { if (streq(type_name, "char16_t")) { return ClangASTType (ast, ast->Char16Ty.getAsOpaquePtr()); } else if (streq(type_name, "char32_t")) { return ClangASTType (ast, ast->Char32Ty.getAsOpaquePtr()); } } break; } } // This assert should fire for anything that we don't catch above so we know // to fix any issues we run into. if (type_name) { Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type '%s' encoded with DW_ATE = 0x%x, bit_size = %u\n", type_name, dw_ate, bit_size); } else { Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type encoded with DW_ATE = 0x%x, bit_size = %u\n", dw_ate, bit_size); } return ClangASTType (); } ClangASTType ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast) { if (ast) return ClangASTType (ast, ast->UnknownAnyTy.getAsOpaquePtr()); return ClangASTType(); } ClangASTType ClangASTContext::GetCStringType (bool is_const) { ASTContext *ast = getASTContext(); QualType char_type(ast->CharTy); if (is_const) char_type.addConst(); return ClangASTType (ast, ast->getPointerType(char_type).getAsOpaquePtr()); } clang::DeclContext * ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast) { return ast->getTranslationUnitDecl(); } ClangASTType ClangASTContext::CopyType (ASTContext *dst_ast, ClangASTType src) { FileSystemOptions file_system_options; ASTContext *src_ast = src.GetASTContext(); FileManager file_manager (file_system_options); ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false); QualType dst (importer.Import(src.GetQualType())); return ClangASTType (dst_ast, dst.getAsOpaquePtr()); } clang::Decl * ClangASTContext::CopyDecl (ASTContext *dst_ast, ASTContext *src_ast, clang::Decl *source_decl) { FileSystemOptions file_system_options; FileManager file_manager (file_system_options); ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false); return importer.Import(source_decl); } bool ClangASTContext::AreTypesSame (ClangASTType type1, ClangASTType type2, bool ignore_qualifiers) { ASTContext *ast = type1.GetASTContext(); if (ast != type2.GetASTContext()) return false; if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType()) return true; QualType type1_qual = type1.GetQualType(); QualType type2_qual = type2.GetQualType(); if (ignore_qualifiers) { type1_qual = type1_qual.getUnqualifiedType(); type2_qual = type2_qual.getUnqualifiedType(); } return ast->hasSameType (type1_qual, type2_qual); } ClangASTType ClangASTContext::GetTypeForDecl (clang::NamedDecl *decl) { if (clang::ObjCInterfaceDecl *interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) return GetTypeForDecl(interface_decl); if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) return GetTypeForDecl(tag_decl); return ClangASTType(); } ClangASTType ClangASTContext::GetTypeForDecl (TagDecl *decl) { // No need to call the getASTContext() accessor (which can create the AST // if it isn't created yet, because we can't have created a decl in this // AST if our AST didn't already exist... ASTContext *ast = &decl->getASTContext(); if (ast) return ClangASTType (ast, ast->getTagDeclType(decl).getAsOpaquePtr()); return ClangASTType(); } ClangASTType ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl) { // No need to call the getASTContext() accessor (which can create the AST // if it isn't created yet, because we can't have created a decl in this // AST if our AST didn't already exist... ASTContext *ast = &decl->getASTContext(); if (ast) return ClangASTType (ast, ast->getObjCInterfaceType(decl).getAsOpaquePtr()); return ClangASTType(); } #pragma mark Structure, Unions, Classes ClangASTType ClangASTContext::CreateRecordType (DeclContext *decl_ctx, AccessType access_type, const char *name, int kind, LanguageType language, ClangASTMetadata *metadata) { ASTContext *ast = getASTContext(); assert (ast != nullptr); if (decl_ctx == nullptr) decl_ctx = ast->getTranslationUnitDecl(); if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus) { bool isForwardDecl = true; bool isInternal = false; return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata); } // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and // we will need to update this code. I was told to currently always use // the CXXRecordDecl class since we often don't know from debug information // if something is struct or a class, so we default to always use the more // complete definition just in case. bool is_anonymous = (!name) || (!name[0]); CXXRecordDecl *decl = CXXRecordDecl::Create (*ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(), SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name)); if (is_anonymous) decl->setAnonymousStructOrUnion(true); if (decl) { if (metadata) SetMetadata(ast, decl, *metadata); if (access_type != eAccessNone) decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type)); if (decl_ctx) decl_ctx->addDecl (decl); return ClangASTType(ast, ast->getTagDeclType(decl).getAsOpaquePtr()); } return ClangASTType(); } static TemplateParameterList * CreateTemplateParameterList (ASTContext *ast, const ClangASTContext::TemplateParameterInfos &template_param_infos, llvm::SmallVector<NamedDecl *, 8> &template_param_decls) { const bool parameter_pack = false; const bool is_typename = false; const unsigned depth = 0; const size_t num_template_params = template_param_infos.GetSize(); for (size_t i=0; i<num_template_params; ++i) { const char *name = template_param_infos.names[i]; IdentifierInfo *identifier_info = nullptr; if (name && name[0]) identifier_info = &ast->Idents.get(name); if (template_param_infos.args[i].getKind() == TemplateArgument::Integral) { template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast, ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc, SourceLocation(), SourceLocation(), depth, i, identifier_info, template_param_infos.args[i].getIntegralType(), parameter_pack, nullptr)); } else { template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast, ast->getTranslationUnitDecl(), // Is this the right decl context? SourceLocation(), SourceLocation(), depth, i, identifier_info, is_typename, parameter_pack)); } } TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast, SourceLocation(), SourceLocation(), &template_param_decls.front(), template_param_decls.size(), SourceLocation()); return template_param_list; } clang::FunctionTemplateDecl * ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx, clang::FunctionDecl *func_decl, const char *name, const TemplateParameterInfos &template_param_infos) { // /// \brief Create a function template node. ASTContext *ast = getASTContext(); llvm::SmallVector<NamedDecl *, 8> template_param_decls; TemplateParameterList *template_param_list = CreateTemplateParameterList (ast, template_param_infos, template_param_decls); FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast, decl_ctx, func_decl->getLocation(), func_decl->getDeclName(), template_param_list, func_decl); for (size_t i=0, template_param_decl_count = template_param_decls.size(); i < template_param_decl_count; ++i) { // TODO: verify which decl context we should put template_param_decls into.. template_param_decls[i]->setDeclContext (func_decl); } return func_tmpl_decl; } void ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl, const TemplateParameterInfos &infos) { TemplateArgumentList template_args (TemplateArgumentList::OnStack, infos.args.data(), infos.args.size()); func_decl->setFunctionTemplateSpecialization (func_tmpl_decl, &template_args, nullptr); } ClassTemplateDecl * ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx, lldb::AccessType access_type, const char *class_name, int kind, const TemplateParameterInfos &template_param_infos) { ASTContext *ast = getASTContext(); ClassTemplateDecl *class_template_decl = nullptr; if (decl_ctx == nullptr) decl_ctx = ast->getTranslationUnitDecl(); IdentifierInfo &identifier_info = ast->Idents.get(class_name); DeclarationName decl_name (&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); for (NamedDecl *decl : result) { class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl); if (class_template_decl) return class_template_decl; } llvm::SmallVector<NamedDecl *, 8> template_param_decls; TemplateParameterList *template_param_list = CreateTemplateParameterList (ast, template_param_infos, template_param_decls); CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast, (TagDecl::TagKind)kind, decl_ctx, // What decl context do we use here? TU? The actual decl context? SourceLocation(), SourceLocation(), &identifier_info); for (size_t i=0, template_param_decl_count = template_param_decls.size(); i < template_param_decl_count; ++i) { template_param_decls[i]->setDeclContext (template_cxx_decl); } // With templated classes, we say that a class is templated with // specializations, but that the bare class has no functions. //template_cxx_decl->startDefinition(); //template_cxx_decl->completeDefinition(); class_template_decl = ClassTemplateDecl::Create (*ast, decl_ctx, // What decl context do we use here? TU? The actual decl context? SourceLocation(), decl_name, template_param_list, template_cxx_decl, nullptr); if (class_template_decl) { if (access_type != eAccessNone) class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type)); //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx)) // CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl)); decl_ctx->addDecl (class_template_decl); #ifdef LLDB_CONFIGURATION_DEBUG VerifyDecl(class_template_decl); #endif } return class_template_decl; } ClassTemplateSpecializationDecl * ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind, const TemplateParameterInfos &template_param_infos) { ASTContext *ast = getASTContext(); ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(), SourceLocation(), class_template_decl, &template_param_infos.args.front(), template_param_infos.args.size(), nullptr); class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization); return class_template_specialization_decl; } ClangASTType ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl) { if (class_template_specialization_decl) { ASTContext *ast = getASTContext(); if (ast) return ClangASTType(ast, ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr()); } return ClangASTType(); } static inline bool check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params) { // Special-case call since it can take any number of operands if(op_kind == OO_Call) return true; // The parameter count doesn't include "this" if (num_params == 0) return unary; if (num_params == 1) return binary; else return false; } bool ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params) { switch (op_kind) { default: break; // C++ standard allows any number of arguments to new/delete case OO_New: case OO_Array_New: case OO_Delete: case OO_Array_Delete: return true; } #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params); switch (op_kind) { #include "clang/Basic/OperatorKinds.def" default: break; } return false; } clang::AccessSpecifier ClangASTContext::UnifyAccessSpecifiers (clang::AccessSpecifier lhs, clang::AccessSpecifier rhs) { clang::AccessSpecifier ret = lhs; // Make the access equal to the stricter of the field and the nested field's access switch (ret) { case clang::AS_none: break; case clang::AS_private: break; case clang::AS_protected: if (rhs == AS_private) ret = AS_private; break; case clang::AS_public: ret = rhs; break; } return ret; } bool ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size) { return FieldIsBitfield(getASTContext(), field, bitfield_bit_size); } bool ClangASTContext::FieldIsBitfield ( ASTContext *ast, FieldDecl* field, uint32_t& bitfield_bit_size ) { if (ast == nullptr || field == nullptr) return false; if (field->isBitField()) { Expr* bit_width_expr = field->getBitWidth(); if (bit_width_expr) { llvm::APSInt bit_width_apsint; if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast)) { bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX); return true; } } } return false; } bool ClangASTContext::RecordHasFields (const RecordDecl *record_decl) { if (record_decl == nullptr) return false; if (!record_decl->field_empty()) return true; // No fields, lets check this is a CXX record and check the base classes const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl); if (cxx_record_decl) { CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl()); if (RecordHasFields(base_class_decl)) return true; } } return false; } #pragma mark Objective C Classes ClangASTType ClangASTContext::CreateObjCClass ( const char *name, DeclContext *decl_ctx, bool isForwardDecl, bool isInternal, ClangASTMetadata *metadata ) { ASTContext *ast = getASTContext(); assert (ast != nullptr); assert (name && name[0]); if (decl_ctx == nullptr) decl_ctx = ast->getTranslationUnitDecl(); ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr, nullptr, SourceLocation(), /*isForwardDecl,*/ isInternal); if (decl && metadata) SetMetadata(ast, decl, *metadata); return ClangASTType (ast, ast->getObjCInterfaceType(decl)); } static inline bool BaseSpecifierIsEmpty (const CXXBaseSpecifier *b) { return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false; } uint32_t ClangASTContext::GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes) { uint32_t num_bases = 0; if (cxx_record_decl) { if (omit_empty_base_classes) { CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { // Skip empty base classes if (omit_empty_base_classes) { if (BaseSpecifierIsEmpty (base_class)) continue; } ++num_bases; } } else num_bases = cxx_record_decl->getNumBases(); } return num_bases; } #pragma mark Namespace Declarations NamespaceDecl * ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx) { NamespaceDecl *namespace_decl = nullptr; ASTContext *ast = getASTContext(); TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl (); if (decl_ctx == nullptr) decl_ctx = translation_unit_decl; if (name) { IdentifierInfo &identifier_info = ast->Idents.get(name); DeclarationName decl_name (&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); for (NamedDecl *decl : result) { namespace_decl = dyn_cast<clang::NamespaceDecl>(decl); if (namespace_decl) return namespace_decl; } namespace_decl = NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(), SourceLocation(), &identifier_info, nullptr); decl_ctx->addDecl (namespace_decl); } else { if (decl_ctx == translation_unit_decl) { namespace_decl = translation_unit_decl->getAnonymousNamespace(); if (namespace_decl) return namespace_decl; namespace_decl = NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(), SourceLocation(), nullptr, nullptr); translation_unit_decl->setAnonymousNamespace (namespace_decl); translation_unit_decl->addDecl (namespace_decl); assert (namespace_decl == translation_unit_decl->getAnonymousNamespace()); } else { NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx); if (parent_namespace_decl) { namespace_decl = parent_namespace_decl->getAnonymousNamespace(); if (namespace_decl) return namespace_decl; namespace_decl = NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(), SourceLocation(), nullptr, nullptr); parent_namespace_decl->setAnonymousNamespace (namespace_decl); parent_namespace_decl->addDecl (namespace_decl); assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace()); } else { // BAD!!! } } if (namespace_decl) { // If we make it here, we are creating the anonymous namespace decl // for the first time, so we need to do the using directive magic // like SEMA does UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast, decl_ctx, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), SourceLocation(), namespace_decl, decl_ctx); using_directive_decl->setImplicit(); decl_ctx->addDecl(using_directive_decl); } } #ifdef LLDB_CONFIGURATION_DEBUG VerifyDecl(namespace_decl); #endif return namespace_decl; } #pragma mark Function Types FunctionDecl * ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, const ClangASTType &function_clang_type, int storage, bool is_inline) { FunctionDecl *func_decl = nullptr; ASTContext *ast = getASTContext(); if (decl_ctx == nullptr) decl_ctx = ast->getTranslationUnitDecl(); const bool hasWrittenPrototype = true; const bool isConstexprSpecified = false; if (name && name[0]) { func_decl = FunctionDecl::Create (*ast, decl_ctx, SourceLocation(), SourceLocation(), DeclarationName (&ast->Idents.get(name)), function_clang_type.GetQualType(), nullptr, (clang::StorageClass)storage, is_inline, hasWrittenPrototype, isConstexprSpecified); } else { func_decl = FunctionDecl::Create (*ast, decl_ctx, SourceLocation(), SourceLocation(), DeclarationName (), function_clang_type.GetQualType(), nullptr, (clang::StorageClass)storage, is_inline, hasWrittenPrototype, isConstexprSpecified); } if (func_decl) decl_ctx->addDecl (func_decl); #ifdef LLDB_CONFIGURATION_DEBUG VerifyDecl(func_decl); #endif return func_decl; } ClangASTType ClangASTContext::CreateFunctionType (ASTContext *ast, const ClangASTType& result_type, const ClangASTType *args, unsigned num_args, bool is_variadic, unsigned type_quals) { assert (ast != nullptr); std::vector<QualType> qual_type_args; for (unsigned i=0; i<num_args; ++i) qual_type_args.push_back (args[i].GetQualType()); // TODO: Detect calling convention in DWARF? FunctionProtoType::ExtProtoInfo proto_info; proto_info.Variadic = is_variadic; proto_info.ExceptionSpec = EST_None; proto_info.TypeQuals = type_quals; proto_info.RefQualifier = RQ_None; return ClangASTType (ast, ast->getFunctionType (result_type.GetQualType(), qual_type_args, proto_info).getAsOpaquePtr()); } ParmVarDecl * ClangASTContext::CreateParameterDeclaration (const char *name, const ClangASTType &param_type, int storage) { ASTContext *ast = getASTContext(); assert (ast != nullptr); return ParmVarDecl::Create(*ast, ast->getTranslationUnitDecl(), SourceLocation(), SourceLocation(), name && name[0] ? &ast->Idents.get(name) : nullptr, param_type.GetQualType(), nullptr, (clang::StorageClass)storage, nullptr); } void ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params) { if (function_decl) function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params)); } #pragma mark Array Types ClangASTType ClangASTContext::CreateArrayType (const ClangASTType &element_type, size_t element_count, bool is_vector) { if (element_type.IsValid()) { ASTContext *ast = getASTContext(); assert (ast != nullptr); if (is_vector) { return ClangASTType (ast, ast->getExtVectorType(element_type.GetQualType(), element_count).getAsOpaquePtr()); } else { llvm::APInt ap_element_count (64, element_count); if (element_count == 0) { return ClangASTType (ast, ast->getIncompleteArrayType (element_type.GetQualType(), ArrayType::Normal, 0).getAsOpaquePtr()); } else { return ClangASTType (ast, ast->getConstantArrayType (element_type.GetQualType(), ap_element_count, ArrayType::Normal, 0).getAsOpaquePtr()); } } } return ClangASTType(); } ClangASTType ClangASTContext::GetOrCreateStructForIdentifier (const ConstString &type_name, const std::initializer_list< std::pair < const char *, ClangASTType > >& type_fields, bool packed) { ClangASTType type; if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid()) return type; type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(), clang::TTK_Struct, lldb::eLanguageTypeC); type.StartTagDeclarationDefinition(); for (const auto& field : type_fields) type.AddFieldToRecordType(field.first, field.second, lldb::eAccessPublic, 0); if (packed) type.SetIsPacked(); type.CompleteTagDeclarationDefinition(); return type; } #pragma mark Enumeration Types ClangASTType ClangASTContext::CreateEnumerationType ( const char *name, DeclContext *decl_ctx, const Declaration &decl, const ClangASTType &integer_clang_type ) { // TODO: Do something intelligent with the Declaration object passed in // like maybe filling in the SourceLocation with it... ASTContext *ast = getASTContext(); // TODO: ask about these... // const bool IsScoped = false; // const bool IsFixed = false; EnumDecl *enum_decl = EnumDecl::Create (*ast, decl_ctx, SourceLocation(), SourceLocation(), name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr, false, // IsScoped false, // IsScopedUsingClassTag false); // IsFixed if (enum_decl) { // TODO: check if we should be setting the promotion type too? enum_decl->setIntegerType(integer_clang_type.GetQualType()); enum_decl->setAccess(AS_public); // TODO respect what's in the debug info return ClangASTType (ast, ast->getTagDeclType(enum_decl).getAsOpaquePtr()); } return ClangASTType(); } // Disable this for now since I can't seem to get a nicely formatted float // out of the APFloat class without just getting the float, double or quad // and then using a formatted print on it which defeats the purpose. We ideally // would like to get perfect string values for any kind of float semantics // so we can support remote targets. The code below also requires a patch to // llvm::APInt. //bool //ClangASTContext::ConvertFloatValueToString (ASTContext *ast, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str) //{ // uint32_t count = 0; // bool is_complex = false; // if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex)) // { // unsigned num_bytes_per_float = byte_size / count; // unsigned num_bits_per_float = num_bytes_per_float * 8; // // float_str.clear(); // uint32_t i; // for (i=0; i<count; i++) // { // APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order); // bool is_ieee = false; // APFloat ap_float(ap_int, is_ieee); // char s[1024]; // unsigned int hex_digits = 0; // bool upper_case = false; // // if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0) // { // if (i > 0) // float_str.append(", "); // float_str.append(s); // if (i == 1 && is_complex) // float_str.append(1, 'i'); // } // } // return !float_str.empty(); // } // return false; //} ClangASTType ClangASTContext::GetIntTypeFromBitSize (clang::ASTContext *ast, size_t bit_size, bool is_signed) { if (ast) { if (is_signed) { if (bit_size == ast->getTypeSize(ast->SignedCharTy)) return ClangASTType(ast, ast->SignedCharTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->ShortTy)) return ClangASTType(ast, ast->ShortTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->IntTy)) return ClangASTType(ast, ast->IntTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->LongTy)) return ClangASTType(ast, ast->LongTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->LongLongTy)) return ClangASTType(ast, ast->LongLongTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->Int128Ty)) return ClangASTType(ast, ast->Int128Ty.getAsOpaquePtr()); } else { if (bit_size == ast->getTypeSize(ast->UnsignedCharTy)) return ClangASTType(ast, ast->UnsignedCharTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->UnsignedShortTy)) return ClangASTType(ast, ast->UnsignedShortTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->UnsignedIntTy)) return ClangASTType(ast, ast->UnsignedIntTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->UnsignedLongTy)) return ClangASTType(ast, ast->UnsignedLongTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy)) return ClangASTType(ast, ast->UnsignedLongLongTy.getAsOpaquePtr()); if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty)) return ClangASTType(ast, ast->UnsignedInt128Ty.getAsOpaquePtr()); } } return ClangASTType(); } ClangASTType ClangASTContext::GetPointerSizedIntType (clang::ASTContext *ast, bool is_signed) { if (ast) return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy), is_signed); return ClangASTType(); } ClangASTType ClangASTContext::GetFloatTypeFromBitSize (clang::ASTContext *ast, size_t bit_size) { if (ast) { if (bit_size == ast->getTypeSize(ast->FloatTy)) return ClangASTType(ast, ast->FloatTy.getAsOpaquePtr()); else if (bit_size == ast->getTypeSize(ast->DoubleTy)) return ClangASTType(ast, ast->DoubleTy.getAsOpaquePtr()); else if (bit_size == ast->getTypeSize(ast->LongDoubleTy)) return ClangASTType(ast, ast->LongDoubleTy.getAsOpaquePtr()); else if (bit_size == ast->getTypeSize(ast->HalfTy)) return ClangASTType(ast, ast->HalfTy.getAsOpaquePtr()); } return ClangASTType(); } bool ClangASTContext::GetCompleteDecl (clang::ASTContext *ast, clang::Decl *decl) { if (!decl) return false; ExternalASTSource *ast_source = ast->getExternalSource(); if (!ast_source) return false; if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) { if (tag_decl->isCompleteDefinition()) return true; if (!tag_decl->hasExternalLexicalStorage()) return false; ast_source->CompleteType(tag_decl); return !tag_decl->getTypeForDecl()->isIncompleteType(); } else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) { if (objc_interface_decl->getDefinition()) return true; if (!objc_interface_decl->hasExternalLexicalStorage()) return false; ast_source->CompleteType(objc_interface_decl); return !objc_interface_decl->getTypeForDecl()->isIncompleteType(); } else { return false; } } void ClangASTContext::SetMetadataAsUserID (const void *object, user_id_t user_id) { ClangASTMetadata meta_data; meta_data.SetUserID (user_id); SetMetadata (object, meta_data); } void ClangASTContext::SetMetadata (clang::ASTContext *ast, const void *object, ClangASTMetadata &metadata) { ClangExternalASTSourceCommon *external_source = ClangExternalASTSourceCommon::Lookup(ast->getExternalSource()); if (external_source) external_source->SetMetadata(object, metadata); } ClangASTMetadata * ClangASTContext::GetMetadata (clang::ASTContext *ast, const void *object) { ClangExternalASTSourceCommon *external_source = ClangExternalASTSourceCommon::Lookup(ast->getExternalSource()); if (external_source && external_source->HasMetadata(object)) return external_source->GetMetadata(object); else return nullptr; } clang::DeclContext * ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl) { return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl); } clang::DeclContext * ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl) { return llvm::dyn_cast<clang::DeclContext>(objc_method_decl); } bool ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx, lldb::LanguageType &language, bool &is_instance_method, ConstString &language_object_name) { language_object_name.Clear(); language = eLanguageTypeUnknown; is_instance_method = false; if (decl_ctx) { if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) { if (method_decl->isStatic()) { is_instance_method = false; } else { language_object_name.SetCString("this"); is_instance_method = true; } language = eLanguageTypeC_plus_plus; return true; } else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) { // Both static and instance methods have a "self" object in objective C language_object_name.SetCString("self"); if (method_decl->isInstanceMethod()) { is_instance_method = true; } else { is_instance_method = false; } language = eLanguageTypeObjC; return true; } else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) { ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl); if (metadata && metadata->HasObjectPtr()) { language_object_name.SetCString (metadata->GetObjectPtrName()); language = eLanguageTypeObjC; is_instance_method = true; } return true; } } return false; }
39.094656
177
0.562088
[ "object", "vector" ]
68bd7e28ec3b228c8e2599ac9932facd1d2cbb6e
2,635
cpp
C++
Core/Beamlet.cpp
mpslxz/LDH_classifier
45f938ae670cf3c67deea6a411048e7e64c23efd
[ "MIT" ]
null
null
null
Core/Beamlet.cpp
mpslxz/LDH_classifier
45f938ae670cf3c67deea6a411048e7e64c23efd
[ "MIT" ]
null
null
null
Core/Beamlet.cpp
mpslxz/LDH_classifier
45f938ae670cf3c67deea6a411048e7e64c23efd
[ "MIT" ]
null
null
null
#include "Beamlet.h" Mat Beamlet(Mat img, int s, Point& beamBase) { int dim = 4*s - 4; vector<Point> border; // initialize the matrix border so that elements in border are the ones //lying along the edges of the dyadic square initialize(border, s); //parameters double ratio = 0.1; double delta = s * sqrt((double)2) * ratio; // end of parameters double Max = 0; Mat result = Mat::zeros(Size(s,s),CV_8U); vector<Point> Beamlet; vector<Point> bestPath; Point start, target; //points that the function calculates //the beamlet coefficient along the //line passing through them //Point cCntr; for(int i = 0; i < dim ; i++){ for(int j = 0; j < dim ; j++){ start = border[i]; target = border[j]; // function that returns the Euclidean distance between two points double D = dist(start, target); auto slope = (target.y - start.y) / (target.x - start.x + 0.00001); if(D > delta && target.x != start.x && slope < 0 && abs(slope) > 0.5){ // vertical beams have been discarded //function that returns the vector of points lying on the path //between start and target in image vector<Point> path = FindPointsInPath(start,target); double res = 0; for(int l = 0; l < path.size(); l++) res += img.at<uchar>(path[l].x , path[l].y); double measure = res / D; //SUM(path,img); if(Max < measure && res>(64*D)){ //cout<<i<<" "<<j<<endl; /*Beamlet.clear(); Beamlet.push_back(start); Beamlet.push_back(target);*/ Max = measure; bestPath.clear(); bestPath = path; //cCntr = start; beamBase = bestPath[0]; } } } } /*for (int i = 0; i < bestPath.size(); i++){ result.at<uchar>(bestPath[i].x, bestPath[i].y) = 255; }*/ /*namedWindow("IT", 0); imshow("IT", result); waitKey();*/ if (bestPath.size() != 0){ Point A(bestPath[0].y, bestPath[0].x); if (A.x > A.y){ A.x = bestPath[bestPath.size() - 1].y; A.y = bestPath[bestPath.size() - 1].x; } beamBase = A; //circle(result, A, 5, Scalar(255, 255, 255)); } /*namedWindow("IT", 0); imshow("IT", result); waitKey();*/ return result; }
32.530864
122
0.488046
[ "vector" ]
68c6c7f6f9da4abbeee688222fb64a8f17b9d37d
1,260
cpp
C++
Program/Graph/Graph_ConnectedComponents.cpp
anurag-singh2001/Algo_Engineering
58345da47378213c3b383ac3cdfdd5e829faee63
[ "MIT" ]
4
2020-12-21T18:33:46.000Z
2022-02-14T19:57:01.000Z
Program/Graph/Graph_ConnectedComponents.cpp
anurag-singh2001/Algo_Engineering
58345da47378213c3b383ac3cdfdd5e829faee63
[ "MIT" ]
5
2021-08-13T08:52:43.000Z
2021-10-08T06:28:21.000Z
Program/Graph/Graph_ConnectedComponents.cpp
anurag-singh2001/Algo_Engineering
58345da47378213c3b383ac3cdfdd5e829faee63
[ "MIT" ]
7
2021-09-30T18:23:36.000Z
2021-10-08T05:19:18.000Z
#include<iostream> #include<vector> #include<bits/stdc++.h> //IMPORTANT using namespace std; #define ll long long int #define ff first #define st(x) cout<< #x<<": "; #define deb(x) cout << #x << " " << x << endl; #define ss second #define pa pair<int,int> #define vi vector<int> #define vii vector<vector<int>> #define vpi vector<pa> int node, edge; vii adl; vector<bool> vis; vi component; int connected(int idx) { cout<<idx<<" "; vis[idx]=true; int ans=1; for(auto i: adl[idx]){ if(!vis[i]){ ans+=connected(i); vis[i]=true; } } return ans; } int main() { cout<<"Enter Number of Nodes and Edges: "; cin>>node>>edge; adl=vector<vector<int>>(node); vis=vector<bool>(node, 0); cout<<"Enter Edge"<<endl; for(int i=0; i<edge; i++){ int x,y; cin>>x>>y; adl[x].push_back(y); adl[y].push_back(x); } cout<<endl; for(int i=0; i<node; i++){ if(!vis[i]){ cout<<"Connected components are: "; component.push_back(connected(i)); cout<<endl; } } cout<<"Elements in connected components are: "; for(auto i: component){ cout<<i<<" "; } cout<<endl; return 0; }
18.529412
51
0.538889
[ "vector" ]
68cf2b4a817f6def991feb23f6762cfd1b5ab746
11,042
cpp
C++
Slimetasia/Camera.cpp
JasonWyx/Slimetasia
5f69deb68da740d326c8514b881583f1e608e5d5
[ "MIT" ]
null
null
null
Slimetasia/Camera.cpp
JasonWyx/Slimetasia
5f69deb68da740d326c8514b881583f1e608e5d5
[ "MIT" ]
null
null
null
Slimetasia/Camera.cpp
JasonWyx/Slimetasia
5f69deb68da740d326c8514b881583f1e608e5d5
[ "MIT" ]
null
null
null
#include "Camera.h" #include "EditorCamera.h" #include "GameObject.h" #include "Renderer.h" #include "ResourceManager.h" Camera::Camera(GameObject* parentObject, char const* componentName) : IComponent(parentObject, componentName) , m_IsMainCamera(true) , m_IsUICamera(false) , m_ProjectionMode(eCameraProjectionMode_Perspective) , m_ViewportSize(0) , m_ViewportOffset(0, 0) , m_OrthoVerticalSize(10.0f) , m_FieldOfView(45.0f) , m_NearPlane(1) , m_FarPlane(1000) , m_FogColor(0.1f, 0.1f, 0.1f) , m_FogAttenuation(20.0f, 100.0f) , m_AmbientColor(0.0f, 0.0f, 0.0f) , m_LightAttenuation(1.0f, 0.0f, 0.0f) , m_Gamma(1.0f) , m_Exposure(1.0f) , m_SkyboxTexture() , m_SkyboxColor(1.0f) , m_EnablePostProcessing(true) , m_Transform(parentObject->GetComponent<Transform>()) , m_LookAtDirection(0.0f, -1.0f, -1.0f) , m_CameraUp(0.0f, 1.0f, 0.0f) , m_EnableBloom(false) , m_EnableSSAO(false) , m_RenderTarget(0) , m_IsReflectionView(false) , m_ReflectionHeight(0.0f) { ASSERT(m_Transform); SetViewportSize(iVector2(1, 1), true); } Camera::~Camera() { glDeleteTextures(1, &m_RenderTarget); } Transform* Camera::GetTransform() { return m_Transform; } void Camera::OnActive() { if (!dynamic_cast<EditorCamera*>(this)) m_OwnerObject->GetParentLayer()->GetRenderLayer().AddCamera(this); } void Camera::OnInactive() { if (!dynamic_cast<EditorCamera*>(this)) { auto parent_layer = m_OwnerObject->GetParentLayer(); if (parent_layer != nullptr) { parent_layer->GetRenderLayer().RemoveCamera(this); } // m_OwnerObject->GetParentLayer()->GetRenderLayer().RemoveCamera(this); } } void Camera::RevalidateResources() { // m_SkyboxTexture.Validate(); } bool Camera::IsMainCamera() const { return m_IsMainCamera; } bool Camera::IsUICamera() const { return m_IsUICamera; } iVector2 Camera::GetViewportOffset() const { return m_ViewportOffset; } void Camera::SetViewportOffset(iVector2 const& viewportOffset) { m_ViewportOffset = viewportOffset; } iVector2 Camera::GetViewportSize() const { return m_ViewportSize; } void Camera::SetViewportSize(iVector2 const& viewportSize, bool rebuildTextures) { if (m_ViewportSize != viewportSize) { m_ViewportSize = viewportSize; if (rebuildTextures) { glDeleteTextures(1, &m_RenderTarget); glCreateTextures(GL_TEXTURE_2D, 1, &m_RenderTarget); glTextureStorage2D(m_RenderTarget, 1, GL_RGBA16F, m_ViewportSize.x, m_ViewportSize.y); glTextureParameteri(m_RenderTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteri(m_RenderTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } } } float Camera::GetFieldOfView() const { return m_FieldOfView; } void Camera::SetFieldOfView(float const& fieldOfView) { m_FieldOfView = fieldOfView; } float Camera::GetNearPlane() const { return m_NearPlane; } void Camera::SetNearPlane(float const& nearPlane) { m_NearPlane = nearPlane; } float Camera::GetFarPlane() const { return m_FarPlane; } void Camera::SetFarPlane(float const& farPlane) { m_FarPlane = farPlane; } Color3 Camera::GetFogColor() const { return m_FogColor; } void Camera::SetFogColor(Color3 const& clearColor) { m_FogColor = clearColor; } Color3 Camera::GetAmbientColor() const { return m_AmbientColor; } void Camera::SetAmbientColor(Color3 const& ambientColor) { m_AmbientColor = ambientColor; } Vector3 Camera::GetLightAttenuation() const { return m_LightAttenuation; } void Camera::SetLightAttenuation(Vector3 const& attenuation) { m_LightAttenuation = attenuation; } Vector2 Camera::GetFogAttenuation() const { return m_FogAttenuation; } void Camera::SetFogAttenuation(Vector2 const& attenuation) { m_FogAttenuation = attenuation; } HTexture Camera::GetSkyboxTexture() const { return m_SkyboxTexture; } void Camera::SetSkyboxTexture(HTexture const& skyboxTexture) { m_SkyboxTexture = skyboxTexture; } Color4 Camera::GetSkyboxColor() const { return m_SkyboxColor; } float Camera::GetGamma() const { return m_Gamma; } float Camera::GetExposure() const { return m_Exposure; } bool Camera::IsPostProcessingEnabled() const { return m_EnablePostProcessing; } bool Camera::IsBloomEnabled() const { return m_EnableBloom; } bool Camera::IsSSAOEnabled() const { return m_EnableSSAO; } GLuint Camera::GetRenderTarget() { if (m_ViewportSize != m_PrevViewportSize) { m_PrevViewportSize = m_ViewportSize; glDeleteTextures(1, &m_RenderTarget); glCreateTextures(GL_TEXTURE_2D, 1, &m_RenderTarget); glTextureStorage2D(m_RenderTarget, 1, GL_RGBA16F, m_ViewportSize.x, m_ViewportSize.y); glTextureParameteri(m_RenderTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteri(m_RenderTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } return m_RenderTarget; } Vector3 Camera::GetLookAtDirection() const { return m_IsReflectionView ? Vector3(m_LookAtDirection.x, -m_LookAtDirection.y, m_LookAtDirection.z) : m_LookAtDirection; } void Camera::SetLookAtDirection(Vector3 const& direction) { m_LookAtDirection = direction; } void Camera::SetIsReflectionView(const bool& isReflectionView) { m_IsReflectionView = isReflectionView; } void Camera::SetReflectionHeight(const float& height) { m_ReflectionHeight = height; } Vector2 Camera::WorldToScreen(Vector3 const& worldPosition) { Matrix4 viewProjectionMatrix = GetViewProjTransform(); // transform world to clipping coordinates Vector4 clipPosition = viewProjectionMatrix * Vector4(worldPosition, 1.0f); clipPosition /= clipPosition.w; float winX = ((clipPosition.x + 1) / 2.0f) * m_ViewportSize.x; // we calculate -point3D.getY() because the screen Y axis is oriented top->down float winY = ((clipPosition.y + 1) / 2.0f) * m_ViewportSize.y; return Vector2(winX, winY); } Vector3 Camera::ScreenToWorld(Vector2 const& screenPosition) { Vector3 pointPlane = m_Transform->m_WorldPosition + m_LookAtDirection; Vector3 right = m_LookAtDirection.Cross(m_CameraUp).Normalized(); Vector3 up = right.Cross(m_LookAtDirection).Normalized(); float t = tanf(Math::ToRadians(m_FieldOfView) / 2); float h = m_NearPlane * t; float w = h * ((float)m_ViewportSize.y / m_ViewportSize.x); Vector2 screenOffset = screenPosition / Vector2((float)m_ViewportSize.x, (float)m_ViewportSize.y); screenOffset *= 2.0f; screenOffset -= Vector2(1.0f); screenOffset *= Vector2(w, h); pointPlane += right * screenOffset.x + up * screenOffset.y; return pointPlane; } std::vector<Vector3> Camera::GetFrustumPoints() const { std::vector<Vector3> results(8); Vector3 zAxis = m_IsReflectionView ? m_LookAtDirection * Vector3(1, -1, 1) : m_LookAtDirection; zAxis.Normalize(); Vector3 cameraUp = zAxis.y >= 0.99999f ? Vector3(0.0f, 0.0f, -1.0f) : zAxis.y <= -0.99999f ? Vector3(0.0f, 0.0f, 1.0f) : m_CameraUp; Vector3 xAxis = zAxis.Cross(cameraUp).Normalized(); Vector3 yAxis = xAxis.Cross(zAxis).Normalized(); // Near/far plane center points Vector3 camPosition = m_Transform->m_WorldPosition; if (m_IsReflectionView) { camPosition.y = camPosition.y - 2 * (camPosition.y - m_ReflectionHeight); } Vector3 nearCenter = camPosition + zAxis * m_NearPlane; Vector3 farCenter = camPosition + zAxis * m_FarPlane; // Get projected viewport extents on near/far planes float e = tanf(m_FieldOfView * 0.5f); float nearExtY = e * m_NearPlane; float nearExtX = nearExtY * ((float)m_ViewportSize.x / m_ViewportSize.y); float farExtY = m_ProjectionMode == CameraProjectionMode::eCameraProjectionMode_Orthographic ? nearExtY : e * m_FarPlane; float farExtX = m_ProjectionMode == CameraProjectionMode::eCameraProjectionMode_Orthographic ? nearExtX : farExtY * ((float)m_ViewportSize.x / m_ViewportSize.y); // Points are just offset from the center points along camera basis // lbn, rbn, rtn, ltn, lbf, rbf, rtf, ltf results[0] = nearCenter - xAxis * nearExtX - yAxis * nearExtY; // lbn results[1] = nearCenter + xAxis * nearExtX - yAxis * nearExtY; // rbn results[2] = nearCenter + xAxis * nearExtX + yAxis * nearExtY; // rtn results[3] = nearCenter - xAxis * nearExtX + yAxis * nearExtY; // ltn results[4] = farCenter - xAxis * farExtX - yAxis * farExtY; // lbf results[5] = farCenter + xAxis * farExtX - yAxis * farExtY; // rbf results[6] = farCenter + xAxis * farExtX + yAxis * farExtY; // rtf results[7] = farCenter - xAxis * farExtX + yAxis * farExtY; // ltf return results; } Matrix4 Camera::GetViewProjTransform() const { return GetProjTransform() * GetViewTransform(); } Matrix4 Camera::GetViewTransform() const { if (m_IsReflectionView) { Vector3 invertView = m_LookAtDirection; invertView.y = -invertView.y; Vector3 invertPosition = m_Transform->GetWorldPosition(); invertPosition.y += (m_ReflectionHeight - invertPosition.y) * 2; return Matrix4::LookAt(invertPosition, invertPosition + invertView, m_CameraUp); } else { return Matrix4::LookAt(m_Transform->GetWorldPosition(), m_Transform->GetWorldPosition() + m_LookAtDirection, m_CameraUp); } } Matrix4 Camera::GetProjTransform() const { float aspectRatio = static_cast<float>(m_ViewportSize.x) / m_ViewportSize.y; switch (m_ProjectionMode) { case CameraProjectionMode::eCameraProjectionMode_Perspective: return Matrix4::Perspective(m_FieldOfView, aspectRatio, m_NearPlane, m_FarPlane); case CameraProjectionMode::eCameraProjectionMode_Orthographic: float halfHeight = m_OrthoVerticalSize / 2; float halfWidth = halfHeight * aspectRatio; return Matrix4::SetFrustumOrtho(-halfWidth, halfWidth, -halfHeight, halfHeight, m_NearPlane, m_FarPlane); } // Should not reach here return Matrix4(); } void Camera::SetUpDirection(Vector3 const& direction) { m_CameraUp = direction; } REFLECT_INIT(Camera) REFLECT_PARENT(IComponent) REFLECT_PROPERTY(m_ProjectionMode) REFLECT_PROPERTY(m_IsMainCamera) REFLECT_PROPERTY(m_IsUICamera) REFLECT_PROPERTY(m_ViewportSize) REFLECT_PROPERTY(m_ViewportOffset) REFLECT_PROPERTY(m_OrthoVerticalSize) REFLECT_PROPERTY(m_FieldOfView) REFLECT_PROPERTY(m_NearPlane) REFLECT_PROPERTY(m_FarPlane) REFLECT_PROPERTY(m_FogColor) REFLECT_PROPERTY(m_FogAttenuation) REFLECT_PROPERTY(m_Gamma) REFLECT_PROPERTY(m_Exposure) REFLECT_PROPERTY(m_EnablePostProcessing) REFLECT_PROPERTY(m_SkyboxTexture) REFLECT_PROPERTY(m_SkyboxColor) REFLECT_PROPERTY(m_AmbientColor) REFLECT_PROPERTY(m_LightAttenuation) REFLECT_PROPERTY(m_LookAtDirection) REFLECT_PROPERTY(m_CameraUp) REFLECT_PROPERTY(m_EnableBloom) REFLECT_PROPERTY(m_EnableSSAO) REFLECT_END()
26.931707
165
0.717805
[ "vector", "transform" ]
68d158fcafc65c96ca19bdef7fba81b59603a4b3
8,059
hpp
C++
core/src/higanbana/core/system/heap_allocator.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
15
2020-01-15T13:04:36.000Z
2022-02-18T17:08:25.000Z
core/src/higanbana/core/system/heap_allocator.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
3
2015-09-09T08:16:30.000Z
2015-11-24T16:22:48.000Z
core/src/higanbana/core/system/heap_allocator.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
1
2021-12-06T07:19:05.000Z
2021-12-06T07:19:05.000Z
#pragma once #include <optional> #include <algorithm> #include "higanbana/core/datastructures/vector.hpp" #include "higanbana/core/global_debug.hpp" namespace higanbana { struct RangeBlock { uint64_t offset; uint64_t size; operator bool() const { return size != 0; } }; class HeapAllocator { struct TLSFSizeClass { size_t sizeClass; uint64_t slBitmap; vector<vector<RangeBlock>> freeBlocks; }; struct TLSFControl { uint64_t flBitmap; vector<TLSFSizeClass> sizeclasses; }; RangeBlock m_baseBlock; uint64_t fli; // first level index uint64_t sli; // second level index, typically 5 unsigned sli_count; // second level index, typically 5 uint64_t mbs; // minimum block size uint64_t min_fli; TLSFControl control; size_t m_usedSize; inline int fls(uint64_t size) const noexcept { if (size == 0) return -1; #ifdef HIGANBANA_PLATFORM_WINDOWS unsigned long index; return _BitScanReverse64(&index, size) ? index : -1; #else return 63 - __builtin_clzll(size); #endif } inline int ffs(uint64_t size) const noexcept { if (size == 0) return -1; #ifdef HIGANBANA_PLATFORM_WINDOWS unsigned long index; return _BitScanForward64(&index, size) ? index : -1; #else return __builtin_ctzll(size); #endif } inline void mapping(size_t size, int& fl, int& sl) noexcept { fl = fls(size); sl = ((size ^ (1ull << fl)) >> (fl - sli)); fl = first_level_index(fl); // printf("%zu -> fl %u sl %u\n", size, fl, sl); } inline int first_level_index(int fli) noexcept { if (fli < min_fli ) return 0; return fli - min_fli; } inline void initialize() noexcept { fli = fls(m_baseBlock.size); mbs = std::min(m_baseBlock.size, mbs); min_fli = fls(mbs); control.flBitmap = 0; for (int i = min_fli; i <= fli; ++i) { size_t sizeClass = 1 << i; vector<vector<RangeBlock>> vectors; for (int k = 0; k < sli_count; ++k) { vectors.push_back(vector<RangeBlock>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } } inline void remove_bit(uint64_t& value, int index) noexcept { value = value ^ (1 << index); } inline void set_bit(uint64_t& value, int index) noexcept { value |= (1 << index); } inline void insert(RangeBlock block, int fl, int sl) noexcept { HIGAN_ASSERT(fl < control.sizeclasses.size() && fl >= 0, "fl should be valid, was fl:%d, sizeclasses %zu", fl, control.sizeclasses.size()); auto& sizeClass = control.sizeclasses[fl]; HIGAN_ASSERT(sl < sizeClass.freeBlocks.size() && sl >= 0, "sl should be valid, was fl:%d sl:%d freeBlocks %zu", fl, sl, sizeClass.freeBlocks.size()); auto& secondLv = sizeClass.freeBlocks[sl]; secondLv.push_back(block); set_bit(sizeClass.slBitmap, sl); set_bit(control.flBitmap, fl); } inline int findLargeEnoughBlockWithinFree(const vector<RangeBlock>& freeblocks, size_t size) { for (int i = 0; i < freeblocks.size(); ++i) if (freeblocks[i].size > size) return i; return 0; } inline RangeBlock search_suitable_block(size_t size, int fl, int sl) noexcept { // first step, assume we got something at fl / sl location if (control.sizeclasses.size() <= fl) return {}; auto& secondLevel = control.sizeclasses[fl]; auto& freeblocks = secondLevel.freeBlocks[sl]; auto candidate = findLargeEnoughBlockWithinFree(freeblocks, size); if (!freeblocks.empty() && freeblocks[candidate].size >= size) { auto block = freeblocks[candidate]; freeblocks.erase(freeblocks.begin() + candidate); // remove bitmap bit if (freeblocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { sl = ffs(secondLevel.slBitmap); candidate = 0; if (sl >= 0) candidate = findLargeEnoughBlockWithinFree(secondLevel.freeBlocks[sl], size); if (sl >= 0 && secondLevel.freeBlocks[sl][candidate].size >= size) { // somethings still in this size class auto& freeblocks2 = secondLevel.freeBlocks[sl]; auto block = freeblocks2[candidate]; freeblocks2.erase(freeblocks2.begin() + candidate); // remove bitmap bit if (freeblocks2.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { // second step, scan bitmaps for empty slots // create mask to ignore first bits, could be wrong auto mask = ~((1 << (fl+1)) - 1); auto fl2 = ffs(control.flBitmap & mask); if (fl2 >= 0) { auto& secondLevel2 = control.sizeclasses[fl2]; HIGAN_ASSERT(secondLevel2.sizeClass >= size && secondLevel2.slBitmap != 0, "bitmap expected to have something"); auto sl2 = ffs(secondLevel2.slBitmap); HIGAN_ASSERT(!secondLevel2.freeBlocks[sl2].empty(), "freeblocks expected to contain something"); candidate = (sl2 >= 0) ? findLargeEnoughBlockWithinFree(secondLevel2.freeBlocks[sl2], size) : 0; if (sl2 >= 0 && secondLevel2.freeBlocks[sl2][candidate].size >= size) { auto& freeblocks3 = secondLevel2.freeBlocks[sl2]; auto block = freeblocks3[candidate]; freeblocks3.erase(freeblocks3.begin() + candidate); // remove bitmap bit if (freeblocks3.empty()) remove_bit(secondLevel2.slBitmap, sl2); if (secondLevel2.slBitmap == 0) remove_bit(control.flBitmap, fl2); return block; } } } } return {}; } inline RangeBlock split(RangeBlock& block, size_t size) noexcept { auto new_size = block.size - size; RangeBlock new_block = {block.offset + size, new_size}; block.size = size; return new_block; } inline RangeBlock merge(RangeBlock block) noexcept { auto otf = block.offset; auto otf2 = block.offset + block.size; // oh no, nail in the coffin. BRUTEFORCE, we got not boundary tagging // possible sped up by using bitmaps to avoid checking empty vectors auto fl = 0; // scan through only the memory where blocks reside using bitfields auto flBM = control.flBitmap; while (flBM != 0) { auto fl = ffs(flBM); remove_bit(flBM, fl); auto& secondLevel = control.sizeclasses[fl]; // use the bitmap to only check relevant vectors auto slBM = secondLevel.slBitmap; while (slBM != 0) { auto sl = ffs(slBM); remove_bit(slBM, sl); auto& freeBlocks = secondLevel.freeBlocks[sl]; auto iter = std::find_if( freeBlocks.begin(), freeBlocks.end(), [otf, otf2](RangeBlock b) { return (b.offset + b.size == otf) || (b.offset == otf2); }); if (iter != freeBlocks.end()) { auto rb = *iter; freeBlocks.erase(iter); if (freeBlocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); if (rb.offset + rb.size == otf) { rb.size += block.size; return rb; } else if (rb.offset == otf2) { block.size += rb.size; return block; } } } } return block; } public: HeapAllocator(); HeapAllocator(RangeBlock initialBlock, size_t minimumBlockSize = 16, int sli = 3); HeapAllocator(size_t size, size_t minimumBlockSize = 16, int sli = 3); std::optional<RangeBlock> allocate(size_t size, size_t alignment = 1) noexcept; void free(RangeBlock block) noexcept; void resize(size_t size) noexcept; size_t findLargestAllocation() const noexcept; inline size_t size() const noexcept { return m_baseBlock.size - m_usedSize; } inline size_t max_size() const noexcept { return m_baseBlock.size; } inline size_t size_allocated() const noexcept { return m_usedSize; } }; }
34.148305
153
0.636307
[ "vector" ]
68dc4f7a943362a4bce158390f4c0345c3dfdb72
1,303
hpp
C++
find_distinct_pairs/find_distinct_pairs.hpp
DoumanAsh/c--test-exe
2b82c0d7082428e71cd0c20f11c4f13ce350fa0d
[ "Apache-2.0" ]
null
null
null
find_distinct_pairs/find_distinct_pairs.hpp
DoumanAsh/c--test-exe
2b82c0d7082428e71cd0c20f11c4f13ce350fa0d
[ "Apache-2.0" ]
null
null
null
find_distinct_pairs/find_distinct_pairs.hpp
DoumanAsh/c--test-exe
2b82c0d7082428e71cd0c20f11c4f13ce350fa0d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <unordered_map> #include <set> #include <vector> #include <algorithm> #include <utility> template <typename T> struct distinct_compare { bool operator() (const std::pair<T, T>& left, const std::pair<T, T>& right) const { //Re-arrange pairs to be in the same order auto ordered_left = left.first < left.second ? left : std::make_pair(left.second, left.first); auto ordered_right = right.first < right.second ? right : std::make_pair(right.second, right.first); return ordered_left < ordered_right; } }; int find_distinct_pairs(std::vector<int>& nums, long target) { const size_t nums_len = nums.size(); if (nums_len < 2) return 0; std::unordered_map<int, int> map; //Store unique pairs //Do not use hashes for ints //as it is implementation defined //and GCC just returns numbers themself std::set<std::pair<int, int>, distinct_compare<int>> distinct_pairs; for (size_t idx = 0; idx < nums_len; idx++) { int diff = target - nums[idx]; auto find = map.find(diff); if (find != map.end()) { distinct_pairs.emplace(find->first, nums[idx]); } map.emplace(nums[idx], static_cast<int>(idx)); } return static_cast<int>(distinct_pairs.size()); }
29.613636
108
0.643131
[ "vector" ]
68dfc916d3481484744f7289dfa64ba74f3d5513
6,598
cpp
C++
HeyoEngine/Heyo/h_Map.cpp
Daniel521/Heyo-Engine
bc303f46ddbacf7de2ba97051e84316be3e9f5c2
[ "MIT" ]
null
null
null
HeyoEngine/Heyo/h_Map.cpp
Daniel521/Heyo-Engine
bc303f46ddbacf7de2ba97051e84316be3e9f5c2
[ "MIT" ]
1
2018-11-21T00:52:16.000Z
2018-11-21T00:52:16.000Z
HeyoEngine/Heyo/h_Map.cpp
Daniel521/Heyo-Engine
bc303f46ddbacf7de2ba97051e84316be3e9f5c2
[ "MIT" ]
null
null
null
//#include "h_Map.h" //#include "h_heyo.h" //#include <fstream> //#include <iostream> // //namespace Heyo_Platform //{ // // Map::Map() // { // main_character = NULL; // point_main_character = { 0,0 }; // point_prev_main_xy = { 0,0 }; // sensor_width = 0; // sensor_rect = { 0,0,0,0 }; // // background = NULL; // mainground = NULL; // // rect_background.x = 0; // rect_background.y = 0; // rect_background.w = Heyo::Engine->graphics->getScreenWidth(); // rect_background.h = Heyo::Engine->graphics->getScreenHeight(); // // rect_mainground.x = 0; // rect_mainground.y = 0; // rect_mainground.w = Heyo::Engine->graphics->getScreenWidth(); // rect_mainground.h = Heyo::Engine->graphics->getScreenHeight(); // // rect_map = { 0,0,0,0 }; // x_offset = 0; // } // // Map::~Map() // { // if (background != NULL) // { // delete background; // } // if (mainground != NULL) // { // delete mainground; // } // } // // bool Map::loadMainCharacter(Character & main_character, unsigned int sensor_width) // { // this->main_character = &main_character; // point_main_character.x = Heyo::Engine->graphics->getScreenWidth()/2 - (this->main_character->getWidth() / 2); // point_main_character.y = Heyo::Engine->graphics->getScreenHeight() - this->main_character->getHeight() - static_cast<int>(this->main_character->getY()); // point_prev_main_xy = { static_cast<int>(this->main_character->getX()), static_cast<int>(this->main_character->getY()) }; // // // // this->sensor_width = sensor_width; // // sensor_rect.x = (Heyo::Engine->graphics->getScreenWidth() / 2) - (sensor_width / 2); // sensor_rect.y = 0; // sensor_rect.w = this->sensor_width; // sensor_rect.h = Heyo::Engine->graphics->getScreenHeight(); // this->main_character->sensor_rect = sensor_rect; // // return true; // } // // bool Map::loadBackground(std::string address) // { // if (background != NULL) // { // delete background; // background = NULL; // } // background = new Heyo::Sprite(Heyo::Engine->graphics); // return background->loadSprite(address); // } // // bool Map::loadCollision(std::string address) // { // Heyo::Rect rect; // std::ifstream read; // read.open(address); // if (read.eof() == true) // { // return false; // } // // char end_line; // while (read.eof() == false && read.peek() != EOF) // { // read >> rect.x >> rect.y >> rect.w >> rect.h; // read.get(end_line); // coll_rect.push_back(rect); // } // // read.close(); // return true; // } // // bool Map::loadMainground(std::string address, int width, int height) // { // if (mainground != NULL) // { // delete mainground; // mainground = NULL; // } // mainground = new Heyo::Sprite(Heyo::Engine->graphics); // rect_mainground.w = width; // rect_mainground.h = height; // rect_mainground.y = height - Heyo::Engine->graphics->getScreenHeight(); // Shouldn't this be ScreenHeight - height? 10/7/2018 // return mainground->loadSprite(address); // } // // void Map::update() // { // // This does not work for negative values in main_character->getX() // // If the x coord of the character is negative, then the code slightly flips and has the collision move instead of the player at slower speeds, at faster speeds, the player moves & the collision // // May need to an a condition statement to check if the user has a negative value for his x coordinate // // OR ---- May make it so the player cannot go into negative values, may do that for now. // // 10/8/18 // if (main_character != NULL) { // if (point_prev_main_xy.x < static_cast<int>(main_character->getX())) { // Going Right // if (point_main_character.x + main_character->getX() - point_prev_main_xy.x + main_character->getWidth() >= sensor_rect.x + sensor_rect.w) { // point_main_character.x = sensor_rect.x + sensor_width - main_character->getWidth(); // //std::cout << "RStuck" << std::endl; // } // else { // point_main_character.x = point_main_character.x + main_character->getX() - point_prev_main_xy.x; // //std::cout << "RNot" << std::endl; // } // } // else if (point_prev_main_xy.x >static_cast<int>(main_character->getX())) { // Going left // if (point_main_character.x - (point_prev_main_xy.x - main_character->getX()) <= sensor_rect.x) { // point_main_character.x = sensor_rect.x; // //std::cout << "LStuck" << std::endl; // } // else { // point_main_character.x = point_main_character.x - point_prev_main_xy.x + main_character->getX(); // //std::cout << "LNot" << std::endl; // } // } // // point_main_character.y = Heyo::Engine->graphics->getScreenHeight() - this->main_character->getHeight() - static_cast<int>(this->main_character->getY()); // // point_prev_main_xy.x = main_character->getX(); // point_prev_main_xy.y = Heyo::Engine->graphics->getScreenHeight() - this->main_character->getHeight() - static_cast<int>(this->main_character->getY()); // // } // // } // // void Map::draw(bool drawSensor) // { // if (background != NULL) // Heyo::Engine->graphics->update(*background, rect_background); // if (mainground != NULL) // Heyo::Engine->graphics->update(*mainground, rect_mainground); // // if (drawSensor == true) // Heyo::Engine->graphics->drawRect(sensor_rect, true, 100, 100, 200); // // if (main_character != NULL) { // //Heyo::Rect temp = { 0,0,0,0 }; // //temp.x = point_main_character.x; // //temp.y = point_main_character.y; // //temp.w = main_character->getWidth(); // //temp.h = main_character->getHeight(); // Heyo::Engine->graphics->update(*main_character->sprite, Heyo::Rect({ point_main_character.x, point_main_character.y, main_character->getWidth(), main_character->getHeight() })); // } // } // // void Map::drawCollision() // { // for (std::vector<Heyo::Rect>::iterator it = coll_rect.begin(); it != coll_rect.end(); ++it) { // Heyo::Rect t = { point_main_character.x + it->x - static_cast<int>(main_character->getX()), it->y, it->w, it->h }; // //std::cout << "x: " << t.x << std::endl; // //std::cout << "y: " << t.y << std::endl; // Heyo::Engine->graphics->drawRect(t, true, 0, 255, 0); // } // } // // void Map::setMaingoundHeight(int height) // { // rect_mainground.h = height; // } // // void Map::setMaingroundWidth(int width) // { // rect_mainground.w = width; // } // // int Map::getMaingroundHeight() // { // return rect_mainground.h; // } // // int Map::getMaingroundWidth() // { // return rect_mainground.w; // } // // void Map::setMapSize(unsigned int x, unsigned int y) // { // rect_map.x = 0; // rect_map.y = 0; // rect_map.w = x; // rect_map.h = y; // } // //}
31.569378
198
0.63201
[ "vector" ]
68ed55f63b3f52d0e31dd31df5fa39abf610bb3c
5,212
cpp
C++
Code/include/igl/unproject_in_mesh.cpp
FabianRepository/SinusProject
48d68902ccd83f08c4d208ba8e0739a8a1252338
[ "BSD-3-Clause" ]
null
null
null
Code/include/igl/unproject_in_mesh.cpp
FabianRepository/SinusProject
48d68902ccd83f08c4d208ba8e0739a8a1252338
[ "BSD-3-Clause" ]
null
null
null
Code/include/igl/unproject_in_mesh.cpp
FabianRepository/SinusProject
48d68902ccd83f08c4d208ba8e0739a8a1252338
[ "BSD-3-Clause" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com> // // 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/. #include "unproject_in_mesh.h" #include "unproject_ray.h" template < typename Derivedobj> IGL_INLINE int igl::unproject_in_mesh( const Eigen::Vector2f& pos, const Eigen::Matrix4f& model, const Eigen::Matrix4f& proj, const Eigen::Vector4f& viewport, const std::function< void( const Eigen::Vector3f&, const Eigen::Vector3f&, std::vector<igl::Hit> &) > & shoot_ray, Eigen::PlainObjectBase<Derivedobj> & obj, std::vector<igl::Hit > & hits) { using namespace igl; using namespace std; using namespace Eigen; Vector3f s,dir; unproject_ray(pos,model,proj,viewport,s,dir); shoot_ray(s,dir,hits); switch(hits.size()) { case 0: break; case 1: { obj = (s + dir*hits[0].t).cast<typename Derivedobj::Scalar>(); break; } case 2: default: { obj = 0.5*((s + dir*hits[0].t) + (s + dir*hits[1].t)).cast<typename Derivedobj::Scalar>(); break; } } return hits.size(); } extern "C" { #include "raytri.c" } template < typename DerivedV, typename DerivedF, typename Derivedobj> IGL_INLINE int igl::unproject_in_mesh( const Eigen::Vector2f& pos, const Eigen::Matrix4f& model, const Eigen::Matrix4f& proj, const Eigen::Vector4f& viewport, const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, Eigen::PlainObjectBase<Derivedobj> & obj, std::vector<igl::Hit > & hits) { using namespace igl; using namespace std; using namespace Eigen; const auto & shoot_ray = [&V,&F]( const Eigen::Vector3f& s, const Eigen::Vector3f& dir, std::vector<igl::Hit> & hits) { // Should be but can't be const Vector3d s_d = s.template cast<double>(); Vector3d dir_d = dir.template cast<double>(); hits.clear(); // loop over all triangles for(int f = 0;f<F.rows();f++) { // Should be but can't be const RowVector3d v0 = V.row(F(f,0)).template cast<double>(); RowVector3d v1 = V.row(F(f,1)).template cast<double>(); RowVector3d v2 = V.row(F(f,2)).template cast<double>(); // shoot ray, record hit double t,u,v; if(intersect_triangle1( s_d.data(), dir_d.data(), v0.data(), v1.data(), v2.data(), &t, &u, &v)) { hits.push_back({(int)f,(int)-1,(float)u,(float)v,(float)t}); } } // Sort hits based on distance std::sort( hits.begin(), hits.end(), [](const Hit & a, const Hit & b)->bool{ return a.t < b.t;}); }; return unproject_in_mesh(pos,model,proj,viewport,shoot_ray,obj,hits); } template < typename DerivedV, typename DerivedF, typename Derivedobj> IGL_INLINE int igl::unproject_in_mesh( const Eigen::Vector2f& pos, const Eigen::Matrix4f& model, const Eigen::Matrix4f& proj, const Eigen::Vector4f& viewport, const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, Eigen::PlainObjectBase<Derivedobj> & obj) { std::vector<igl::Hit> hits; return unproject_in_mesh(pos,model,proj,viewport,V,F,obj,hits); } #ifdef IGL_STATIC_LIBRARY template int igl::unproject_in_mesh<Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 1, 0, 4, 1> const&, std::__1::function<void (Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&)> const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&); template int igl::unproject_in_mesh<Eigen::Matrix<double, 3, 1, 0, 3, 1> >(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 1, 0, 4, 1> const&, std::__1::function<void (Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&)> const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> >&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&); template int igl::unproject_in_mesh<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 4, 0, 4, 4> const&, Eigen::Matrix<float, 4, 1, 0, 4, 1> const&, std::__1::function<void (Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&)> const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, std::__1::vector<igl::Hit, std::__1::allocator<igl::Hit> >&); #endif
43.07438
567
0.628166
[ "geometry", "vector", "model" ]
68f1e747c0cb23c0628b86ccdc677c57ccaee1a0
1,056
cpp
C++
src/atta/uiSystem/layers/editor/systemWindows/physicsSystemWindow.cpp
brenocq/atta
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
5
2021-11-18T02:44:45.000Z
2021-12-21T17:46:10.000Z
src/atta/uiSystem/layers/editor/systemWindows/physicsSystemWindow.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
1
2021-11-18T02:56:14.000Z
2021-12-04T15:09:16.000Z
src/atta/uiSystem/layers/editor/systemWindows/physicsSystemWindow.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
3
2020-09-10T07:17:00.000Z
2020-11-05T10:24:41.000Z
//-------------------------------------------------- // Atta UI System // physicsSystemWindow.cpp // Date: 2021-12-01 // By Breno Cunha Queiroz //-------------------------------------------------- #include <atta/uiSystem/layers/editor/systemWindows/physicsSystemWindow.h> #include <atta/physicsSystem/physicsManager.h> namespace atta::ui { PhysicsSystemWindow::PhysicsSystemWindow() { setName("Physics System"); } void PhysicsSystemWindow::renderImpl() { ImGui::Text("Physics Engine"); std::vector<std::string> physicsEngines = { "Null", "Box2D", "Bullet" }; PhysicsEngine::Type selected = PhysicsManager::getSelectedEngine(); if(ImGui::BeginCombo(("##"+_name+"SelectEngine").c_str(), physicsEngines[selected].c_str())) { for(unsigned i = 0; i < physicsEngines.size(); i++) { if(ImGui::Selectable(physicsEngines[i].c_str(), i == selected)) PhysicsManager::setSelectedEngine((PhysicsEngine::Type)i); if(i == selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } ImGui::Separator(); } }
27.789474
94
0.620265
[ "vector" ]
d0ff5ddd81bfd93f55e5f520f8873e5a74e6369f
1,514
cpp
C++
C++/roombooking.cpp
dwarana/Multi-lang-repo
099622e1ad28037aa2feae1b95b2d337a8979056
[ "MIT" ]
null
null
null
C++/roombooking.cpp
dwarana/Multi-lang-repo
099622e1ad28037aa2feae1b95b2d337a8979056
[ "MIT" ]
null
null
null
C++/roombooking.cpp
dwarana/Multi-lang-repo
099622e1ad28037aa2feae1b95b2d337a8979056
[ "MIT" ]
null
null
null
#include "bookroomdialog.h" #include "ui_bookroomdialog.h" BookRoomDialog::BookRoomDialog(QWidget *parent) : QDialog(parent), ui(new Ui::BookRoomDialog) { ui->setupUi(this); this->setFixedSize(320,240); } void BookRoomDialog:: readData() { qDebug()<<"BookRoomDialog:readData"; std::vector<int>rooms = Hotel::getInstance()->getRoomList("y"); this->ui->cmbRoomList->clear(); for(std::vector<int>::iterator it = rooms.begin(); it!=rooms.end(); it++ ) { this->ui->cmbRoomList->addItem(QString::number(*it)); } } BookRoomDialog::~BookRoomDialog() { delete ui; } void BookRoomDialog::on_btnCancel_clicked() { this->hide(); } void BookRoomDialog::on_btnSubmit_clicked() { //call hotel's book room int roomno = ui->cmbRoomList->currentText().toInt(); QString name = ui->txtName->text(); QString contactno = ui->txtContactNumber->text(); QString address = ui->txtAddress->toPlainText(); QString govtid = ui->txtIdProof->text(); if(roomno < 1) { QMessageBox::information( this, tr("Warning!"), tr("We are sold out. No room is available") ); return; } int ret = Hotel::getInstance()->BookRoom(roomno, name, contactno, govtid, address); QString msg = ""; ret==0?msg="Success!":"Failure!"; this->hide(); if(ret == 0) { QMessageBox::information( this, tr("Success!"), tr("Room has been booked!") ); } }
22.597015
87
0.601057
[ "vector" ]
190c746d1373015f4698736e449ebc65ee5dbc04
1,572
cpp
C++
planning/rtc_auto_approver/src/node.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
planning/rtc_auto_approver/src/node.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
planning/rtc_auto_approver/src/node.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2022 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 "rtc_auto_approver/node.hpp" #include <algorithm> namespace rtc_auto_approver { RTCAutoApproverNode::RTCAutoApproverNode(const rclcpp::NodeOptions & node_options) : Node("rtc_auto_approver_node", node_options) { const std::vector<std::string> module_list = declare_parameter("module_list", std::vector<std::string>()); const std::vector<std::string> default_enable_list = declare_parameter("default_enable_list", std::vector<std::string>()); for (const auto & module_name : module_list) { const std::string name_space = BEHAVIOR_PLANNING_NAMESPACE + "/" + module_name; const bool enabled = std::count(default_enable_list.begin(), default_enable_list.end(), module_name) != 0; approvers_.push_back(std::make_shared<RTCAutoApproverInterface>(this, name_space, enabled)); } } } // namespace rtc_auto_approver #include <rclcpp_components/register_node_macro.hpp> RCLCPP_COMPONENTS_REGISTER_NODE(rtc_auto_approver::RTCAutoApproverNode)
37.428571
96
0.75827
[ "vector" ]
19147218efbc0f64727349171549955039991430
9,149
cpp
C++
Camera/Camera.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
1
2016-02-17T17:03:37.000Z
2016-02-17T17:03:37.000Z
Camera/Camera.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
null
null
null
Camera/Camera.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
null
null
null
#include "Camera.h" #include "Frustum.h" #include <iostream> namespace CameraLib { void Camera::CalculateFrustumPlanes() { // Initialize the camera space plane array. float halfViewingAngle = cameraYFOV * 0.5f; float yOpposite = nearClipPlaneDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)); float xOpposite = nearClipPlaneDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)) * aspectRatio; MathLib::vector4 cameraSpacePlanes[6]; cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_NEAR].setXYZW(0.0f, 0.0f, -1.0f, 0.0f); cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_FAR].setXYZW(0.0f, 0.0f, 1.0f, 0.0f); cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_LEFT].setXYZW(nearClipPlaneDistance, 0.0f, -xOpposite, 0.0f); cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_RIGHT].setXYZW(-nearClipPlaneDistance, 0.0f, -xOpposite, 0.0f); cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_BOTTOM].setXYZW(0.0f, nearClipPlaneDistance, -yOpposite, 0.0f); cameraSpacePlanes[FrustumConstants::FRUSTUM_PLANE_TOP].setXYZW(0.0f, -nearClipPlaneDistance, -yOpposite, 0.0f); MathLib::matrix4x4 worldToCameraSpaceMatrixTransposed; MathLib::matrix4x4_copy(worldToCameraSpaceMatrixTransposed, worldToCameraSpaceMatrix); MathLib::matrix4x4_transpose(worldToCameraSpaceMatrixTransposed); // Transform each of the planes. MathLib::matrix4x4_vectorBatchMul(worldToCameraSpaceMatrixTransposed, cameraSpacePlanes, 6, cameraSpacePlanes); // Assign the normal values to the furstum array (the plane takes care of normalizing them). for (unsigned int i = 0; i < 6; i++) { frustumPlanes[i].setNormal(cameraSpacePlanes[i]); } // Now we must calculate the points on the plane. // For the left, right, top and bottom planes, this is trivially the camera's world space position. But for the // near and far planes it's a little more complicated. frustumPlanes[FrustumConstants::FRUSTUM_PLANE_LEFT].setPointOnPlane(position); frustumPlanes[FrustumConstants::FRUSTUM_PLANE_RIGHT].setPointOnPlane(position); frustumPlanes[FrustumConstants::FRUSTUM_PLANE_BOTTOM].setPointOnPlane(position); frustumPlanes[FrustumConstants::FRUSTUM_PLANE_TOP].setPointOnPlane(position); MathLib::vector4 nearClipPlanePoint; MathLib::vector4 farClipPlanePoint; MathLib::vector4_addScaledVector(position, zAxis, -nearClipPlaneDistance, nearClipPlanePoint); MathLib::vector4_addScaledVector(position, zAxis, -farClipPlaneDistance, farClipPlanePoint); frustumPlanes[FrustumConstants::FRUSTUM_PLANE_NEAR].setPointOnPlane(nearClipPlanePoint); frustumPlanes[FrustumConstants::FRUSTUM_PLANE_FAR].setPointOnPlane(farClipPlanePoint); } MathLib::vector4* Camera::GetFrustumPoints(float startDistance, float endDistance) { float halfViewingAngle = cameraYFOV * 0.5f; // Create frustum near plane. float yOppositeNear = startDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)); float xOppositeNear = startDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)) * aspectRatio; frustumPoints[FrustumConstants::FRUSTUM_POINT_LTN].setXYZW(-xOppositeNear, yOppositeNear, -startDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_RTN].setXYZW(xOppositeNear, yOppositeNear, -startDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_RBN].setXYZW(xOppositeNear, -yOppositeNear, -startDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_LBN].setXYZW(-xOppositeNear, -yOppositeNear, -startDistance, 1.0f); // Create frustum far plane. float yOppositeFar = endDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)); float xOppositeFar = endDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)) * aspectRatio; frustumPoints[FrustumConstants::FRUSTUM_POINT_LTF].setXYZW(-xOppositeFar, yOppositeFar, -endDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_RTF].setXYZW(xOppositeFar, yOppositeFar, -endDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_RBF].setXYZW(xOppositeFar, -yOppositeFar, -endDistance, 1.0f); frustumPoints[FrustumConstants::FRUSTUM_POINT_LBF].setXYZW(-xOppositeFar, -yOppositeFar, -endDistance, 1.0f); // Transform into world space. MathLib::matrix4x4_vectorBatchMul(cameraToWorldSpaceMatrix, frustumPoints, 8, frustumPoints); return frustumPoints; } void Camera::GetFrustumSliceBoundingSphere(float startDistance, float endDistance, float& sphereRadius, MathLib::vector4& spherePosition) { float halfViewingAngle = cameraYFOV * 0.5f; MathLib::vector4 frustumPoint; // Create frustum far plane. float yOppositeFar = endDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)); float xOppositeFar = endDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)) * aspectRatio; frustumPoint.setXYZW(-xOppositeFar, yOppositeFar, -endDistance, 1.0f); MathLib::vector4 frustumMidpoint(0.0f, 0.0f, -(startDistance + (endDistance - startDistance) * 0.5f), 1.0f); sphereRadius = MathLib::vector4_distance(frustumMidpoint, frustumPoint); MathLib::matrix4x4_vectorMul(cameraToWorldSpaceMatrix, frustumMidpoint, spherePosition); } MathLib::plane* Camera::GetFrustumPlanes() { return frustumPlanes; } void Camera::Update() { UpdateBasis(); MathLib::vector4& camera_xAxis = GetXAxis(); MathLib::vector4& camera_yAxis = GetYAxis(); MathLib::vector4& camera_zAxis = GetZAxis(); MathLib::vector4& camera_position = GetPosition(); // Create world to camera space transform. { MathLib::matrix4x4 worldToCameraTransform_basisComponent ( camera_xAxis.extractX(), camera_xAxis.extractY(), camera_xAxis.extractZ(), 0.0f, camera_yAxis.extractX(), camera_yAxis.extractY(), camera_yAxis.extractZ(), 0.0f, camera_zAxis.extractX(), camera_zAxis.extractY(), camera_zAxis.extractZ(), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); MathLib::matrix4x4 worldToCameraTransform_translationComponent ( 1.0f, 0.0f, 0.0f, -camera_position.extractX(), 0.0f, 1.0f, 0.0f, -camera_position.extractY(), 0.0f, 0.0f, 1.0f, -camera_position.extractZ(), 0.0f, 0.0f, 0.0f, 1.0f ); MathLib::matrix4x4 worldToCameraTransform; MathLib::matrix4x4_mul(worldToCameraTransform_basisComponent, worldToCameraTransform_translationComponent, worldToCameraTransform); MathLib::matrix4x4_copy(worldToCameraSpaceMatrix, worldToCameraTransform); } // Create camera to world space transform. { MathLib::matrix4x4 orientation ( camera_xAxis.extractX(), camera_yAxis.extractX(), camera_zAxis.extractX(), 0.0f, camera_xAxis.extractY(), camera_yAxis.extractY(), camera_zAxis.extractY(), 0.0f, camera_xAxis.extractZ(), camera_yAxis.extractZ(), camera_zAxis.extractZ(), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); MathLib::matrix4x4 translation ( 1.0f, 0.0f, 0.0f, camera_position.extractX(), 0.0f, 1.0f, 0.0f, camera_position.extractY(), 0.0f, 0.0f, 1.0f, camera_position.extractZ(), 0.0f, 0.0f, 0.0f, 1.0f ); MathLib::matrix4x4_mul(translation, orientation, cameraToWorldSpaceMatrix); } } void Camera::UpdateBasis() { // Reset the basis vectors, and recalculate the rotations from scratch. // This is to avoid accumulative loss of orthogonality over time. xAxis.setXYZW(1.0f, 0.0f, 0.0f, 0.0f); yAxis.setXYZW(0.0f, 1.0f, 0.0f, 0.0f); zAxis.setXYZW(0.0f, 0.0f, 1.0f, 0.0f); PerformRotationXAxis(rotationAngleX); MathLib::matrix4x4 rotateAroundY; rotateAroundY.loadRotationY(rotationAngleY); MathLib::matrix4x4_vectorMul(rotateAroundY, xAxis, xAxis); MathLib::matrix4x4_vectorMul(rotateAroundY, yAxis, yAxis); MathLib::matrix4x4_vectorMul(rotateAroundY, zAxis, zAxis); PerformRotationZAxis(rotationAngleZ); } const MathLib::matrix4x4& Camera::GetPerspectiveProjectionMatrix(uint32_t displayWidth, uint32_t displayHeight) { aspectRatio = (float)displayWidth / (float)displayHeight; float top = nearClipPlaneDistance * tan(MATHLIB_DEG_TO_RAD(cameraYFOV * 0.5f)); float right = top * aspectRatio; MathLib::matrix4x4 projectionMatrix; projectionMatrix.loadIdentity(); projectionMatrix._00 = nearClipPlaneDistance / right; projectionMatrix._11 = nearClipPlaneDistance / top; projectionMatrix._22 = -(farClipPlaneDistance + nearClipPlaneDistance) / (farClipPlaneDistance - nearClipPlaneDistance); projectionMatrix._23 = (-2.0f * nearClipPlaneDistance * farClipPlaneDistance) / (farClipPlaneDistance - nearClipPlaneDistance); projectionMatrix._32 = -1.0f; projectionMatrix._33 = 0.0f; // Cache results MathLib::matrix4x4_copy(this->projectionMatrix, projectionMatrix); return this->projectionMatrix; } void Camera::GetNearPlaneExtents(float& xExtent, float& yExtent) const { float halfViewingAngle = cameraYFOV * 0.5f; xExtent = nearClipPlaneDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)) * aspectRatio; yExtent = nearClipPlaneDistance * tanf(MATHLIB_DEG_TO_RAD(halfViewingAngle)); } Camera& Camera::operator=(const Camera& rhs) { rotationAngleX = rhs.rotationAngleX; rotationAngleY = rhs.rotationAngleY; rotationAngleZ = rhs.rotationAngleZ; nearClipPlaneDistance = rhs.nearClipPlaneDistance; farClipPlaneDistance = rhs.farClipPlaneDistance; MathLib::vector4_copy(position, rhs.position); cameraYFOV = rhs.cameraYFOV; aspectRatio = rhs.aspectRatio; return *this; } }
39.951965
137
0.785441
[ "transform" ]
191d411e4e0997dfa5ef53a2a8929cd248e4648a
19,199
cpp
C++
nfc/src/DOOM/neo/renderer/Image_load.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/neo/renderer/Image_load.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/neo/renderer/Image_load.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition Source Code 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. Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #pragma hdrstop #include "../idlib/precompiled.h" #include "tr_local.h" /* ================ BitsForFormat ================ */ int BitsForFormat( textureFormat_t format ) { switch ( format ) { case FMT_NONE: return 0; case FMT_RGBA8: return 32; case FMT_XRGB8: return 32; case FMT_RGB565: return 16; case FMT_L8A8: return 16; case FMT_ALPHA: return 8; case FMT_LUM8: return 8; case FMT_INT8: return 8; case FMT_DXT1: return 4; case FMT_DXT5: return 8; case FMT_DEPTH: return 32; case FMT_X16: return 16; case FMT_Y16_X16: return 32; default: assert( 0 ); return 0; } } /* ======================== idImage::DeriveOpts ======================== */ ID_INLINE void idImage::DeriveOpts() { if ( opts.format == FMT_NONE ) { opts.colorFormat = CFM_DEFAULT; switch ( usage ) { case TD_COVERAGE: opts.format = FMT_DXT1; opts.colorFormat = CFM_GREEN_ALPHA; break; case TD_DEPTH: opts.format = FMT_DEPTH; break; case TD_DIFFUSE: // TD_DIFFUSE gets only set to when its a diffuse texture for an interaction opts.gammaMips = true; opts.format = FMT_DXT5; opts.colorFormat = CFM_YCOCG_DXT5; break; case TD_SPECULAR: opts.gammaMips = true; opts.format = FMT_DXT1; opts.colorFormat = CFM_DEFAULT; break; case TD_DEFAULT: opts.gammaMips = true; opts.format = FMT_DXT5; opts.colorFormat = CFM_DEFAULT; break; case TD_BUMP: opts.format = FMT_DXT5; opts.colorFormat = CFM_NORMAL_DXT5; break; case TD_FONT: opts.format = FMT_DXT1; opts.colorFormat = CFM_GREEN_ALPHA; opts.numLevels = 4; // We only support 4 levels because we align to 16 in the exporter opts.gammaMips = true; break; case TD_LIGHT: opts.format = FMT_RGB565; opts.gammaMips = true; break; case TD_LOOKUP_TABLE_MONO: opts.format = FMT_INT8; break; case TD_LOOKUP_TABLE_ALPHA: opts.format = FMT_ALPHA; break; case TD_LOOKUP_TABLE_RGB1: case TD_LOOKUP_TABLE_RGBA: opts.format = FMT_RGBA8; break; default: assert( false ); opts.format = FMT_RGBA8; } } if ( opts.numLevels == 0 ) { opts.numLevels = 1; if ( filter == TF_LINEAR || filter == TF_NEAREST ) { // don't create mip maps if we aren't going to be using them } else { int temp_width = opts.width; int temp_height = opts.height; while ( temp_width > 1 || temp_height > 1 ) { temp_width >>= 1; temp_height >>= 1; if ( ( opts.format == FMT_DXT1 || opts.format == FMT_DXT5 ) && ( ( temp_width & 0x3 ) != 0 || ( temp_height & 0x3 ) != 0 ) ) { break; } opts.numLevels++; } } } } /* ======================== idImage::AllocImage ======================== */ void idImage::AllocImage( const idImageOpts &imgOpts, textureFilter_t tf, textureRepeat_t tr ) { filter = tf; repeat = tr; opts = imgOpts; DeriveOpts(); AllocImage(); } /* ================ GenerateImage ================ */ void idImage::GenerateImage( const byte *pic, int width, int height, textureFilter_t filterParm, textureRepeat_t repeatParm, textureUsage_t usageParm ) { PurgeImage(); filter = filterParm; repeat = repeatParm; usage = usageParm; cubeFiles = CF_2D; opts.textureType = TT_2D; opts.width = width; opts.height = height; opts.numLevels = 0; DeriveOpts(); // if we don't have a rendering context, just return after we // have filled in the parms. We must have the values set, or // an image match from a shader before the render starts would miss // the generated texture if ( !R_IsInitialized() ) { return; } idBinaryImage im( GetName() ); im.Load2DFromMemory( width, height, pic, opts.numLevels, opts.format, opts.colorFormat, opts.gammaMips ); AllocImage(); for ( int i = 0; i < im.NumImages(); i++ ) { const bimageImage_t & img = im.GetImageHeader( i ); const byte * data = im.GetImageData( i ); SubImageUpload( img.level, 0, 0, img.destZ, img.width, img.height, data ); } } /* ==================== GenerateCubeImage Non-square cube sides are not allowed ==================== */ void idImage::GenerateCubeImage( const byte *pic[6], int size, textureFilter_t filterParm, textureUsage_t usageParm ) { PurgeImage(); filter = filterParm; repeat = TR_CLAMP; usage = usageParm; cubeFiles = CF_NATIVE; opts.textureType = TT_CUBIC; opts.width = size; opts.height = size; opts.numLevels = 0; DeriveOpts(); // if we don't have a rendering context, just return after we // have filled in the parms. We must have the values set, or // an image match from a shader before the render starts would miss // the generated texture if ( !R_IsInitialized() ) { return; } idBinaryImage im( GetName() ); im.LoadCubeFromMemory( size, pic, opts.numLevels, opts.format, opts.gammaMips ); AllocImage(); for ( int i = 0; i < im.NumImages(); i++ ) { const bimageImage_t & img = im.GetImageHeader( i ); const byte * data = im.GetImageData( i ); SubImageUpload( img.level, 0, 0, img.destZ, img.width, img.height, data ); } } /* =============== GetGeneratedName name contains GetName() upon entry =============== */ void idImage::GetGeneratedName( idStr &_name, const textureUsage_t &_usage, const cubeFiles_t &_cube ) { idStrStatic< 64 > extension; _name.ExtractFileExtension( extension ); _name.StripFileExtension(); _name += va( "#__%02d%02d", (int)_usage, (int)_cube ); if ( extension.Length() > 0 ) { _name.SetFileExtension( extension ); } } /* =============== ActuallyLoadImage Absolutely every image goes through this path On exit, the idImage will have a valid OpenGL texture number that can be bound =============== */ void idImage::ActuallyLoadImage( bool fromBackEnd ) { // if we don't have a rendering context yet, just return if ( !R_IsInitialized() ) { return; } // this is the ONLY place generatorFunction will ever be called if ( generatorFunction ) { generatorFunction( this ); return; } if ( com_productionMode.GetInteger() != 0 ) { sourceFileTime = FILE_NOT_FOUND_TIMESTAMP; if ( cubeFiles != CF_2D ) { opts.textureType = TT_CUBIC; repeat = TR_CLAMP; } } else { if ( cubeFiles != CF_2D ) { opts.textureType = TT_CUBIC; repeat = TR_CLAMP; R_LoadCubeImages( GetName(), cubeFiles, NULL, NULL, &sourceFileTime ); } else { opts.textureType = TT_2D; R_LoadImageProgram( GetName(), NULL, NULL, NULL, &sourceFileTime, &usage ); } } // Figure out opts.colorFormat and opts.format so we can make sure the binary image is up to date DeriveOpts(); idStrStatic< MAX_OSPATH > generatedName = GetName(); GetGeneratedName( generatedName, usage, cubeFiles ); idBinaryImage im( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); // BFHACK, do not want to tweak on buildgame so catch these images here if ( binaryFileTime == FILE_NOT_FOUND_TIMESTAMP && fileSystem->UsingResourceFiles() ) { int c = 1; while ( c-- > 0 ) { if ( generatedName.Find( "guis/assets/white#__0000", false ) >= 0 ) { generatedName.Replace( "white#__0000", "white#__0200" ); im.SetName( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); break; } if ( generatedName.Find( "guis/assets/white#__0100", false ) >= 0 ) { generatedName.Replace( "white#__0100", "white#__0200" ); im.SetName( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); break; } if ( generatedName.Find( "textures/black#__0100", false ) >= 0 ) { generatedName.Replace( "black#__0100", "black#__0200" ); im.SetName( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); break; } if ( generatedName.Find( "textures/decals/bulletglass1_d#__0100", false ) >= 0 ) { generatedName.Replace( "bulletglass1_d#__0100", "bulletglass1_d#__0200" ); im.SetName( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); break; } if ( generatedName.Find( "models/monsters/skeleton/skeleton01_d#__1000", false ) >= 0 ) { generatedName.Replace( "skeleton01_d#__1000", "skeleton01_d#__0100" ); im.SetName( generatedName ); binaryFileTime = im.LoadFromGeneratedFile( sourceFileTime ); break; } } } const bimageFile_t & header = im.GetFileHeader(); if ( ( fileSystem->InProductionMode() && binaryFileTime != FILE_NOT_FOUND_TIMESTAMP ) || ( ( binaryFileTime != FILE_NOT_FOUND_TIMESTAMP ) && ( header.colorFormat == opts.colorFormat ) && ( header.format == opts.format ) && ( header.textureType == opts.textureType ) ) ) { opts.width = header.width; opts.height = header.height; opts.numLevels = header.numLevels; opts.colorFormat = (textureColor_t)header.colorFormat; opts.format = (textureFormat_t)header.format; opts.textureType = (textureType_t)header.textureType; if ( cvarSystem->GetCVarBool( "fs_buildresources" ) ) { // for resource gathering write this image to the preload file for this map fileSystem->AddImagePreload( GetName(), filter, repeat, usage, cubeFiles ); } } else { if ( cubeFiles != CF_2D ) { int size; byte * pics[6]; if ( !R_LoadCubeImages( GetName(), cubeFiles, pics, &size, &sourceFileTime ) || size == 0 ) { idLib::Warning( "Couldn't load cube image: %s", GetName() ); return; } opts.textureType = TT_CUBIC; repeat = TR_CLAMP; opts.width = size; opts.height = size; opts.numLevels = 0; DeriveOpts(); im.LoadCubeFromMemory( size, (const byte **)pics, opts.numLevels, opts.format, opts.gammaMips ); repeat = TR_CLAMP; for ( int i = 0; i < 6; i++ ) { if ( pics[i] ) { Mem_Free( pics[i] ); } } } else { int width, height; byte * pic; // load the full specification, and perform any image program calculations R_LoadImageProgram( GetName(), &pic, &width, &height, &sourceFileTime, &usage ); if ( pic == NULL ) { idLib::Warning( "Couldn't load image: %s : %s", GetName(), generatedName.c_str() ); // create a default so it doesn't get continuously reloaded opts.width = 8; opts.height = 8; opts.numLevels = 1; DeriveOpts(); AllocImage(); // clear the data so it's not left uninitialized idTempArray<byte> clear( opts.width * opts.height * 4 ); memset( clear.Ptr(), 0, clear.Size() ); for ( int level = 0; level < opts.numLevels; level++ ) { SubImageUpload( level, 0, 0, 0, opts.width >> level, opts.height >> level, clear.Ptr() ); } return; } opts.width = width; opts.height = height; opts.numLevels = 0; DeriveOpts(); im.Load2DFromMemory( opts.width, opts.height, pic, opts.numLevels, opts.format, opts.colorFormat, opts.gammaMips ); Mem_Free( pic ); } binaryFileTime = im.WriteGeneratedFile( sourceFileTime ); } AllocImage(); for ( int i = 0; i < im.NumImages(); i++ ) { const bimageImage_t & img = im.GetImageHeader( i ); const byte * data = im.GetImageData( i ); SubImageUpload( img.level, 0, 0, img.destZ, img.width, img.height, data ); } } /* ============== Bind Automatically enables 2D mapping or cube mapping if needed ============== */ void idImage::Bind() { RENDERLOG_PRINTF( "idImage::Bind( %s )\n", GetName() ); // load the image if necessary (FIXME: not SMP safe!) if ( !IsLoaded() ) { // load the image on demand here, which isn't our normal game operating mode ActuallyLoadImage( true ); } const int texUnit = backEnd.glState.currenttmu; tmu_t * tmu = &backEnd.glState.tmu[texUnit]; // bind the texture if ( opts.textureType == TT_2D ) { if ( tmu->current2DMap != texnum ) { tmu->current2DMap = texnum; qglBindMultiTextureEXT( GL_TEXTURE0_ARB + texUnit, GL_TEXTURE_2D, texnum ); } } else if ( opts.textureType == TT_CUBIC ) { if ( tmu->currentCubeMap != texnum ) { tmu->currentCubeMap = texnum; qglBindMultiTextureEXT( GL_TEXTURE0_ARB + texUnit, GL_TEXTURE_CUBE_MAP_EXT, texnum ); } } } /* ================ MakePowerOfTwo ================ */ int MakePowerOfTwo( int num ) { int pot; for ( pot = 1; pot < num; pot <<= 1 ) { } return pot; } /* ==================== CopyFramebuffer ==================== */ void idImage::CopyFramebuffer( int x, int y, int imageWidth, int imageHeight ) { qglBindTexture( ( opts.textureType == TT_CUBIC ) ? GL_TEXTURE_CUBE_MAP_EXT : GL_TEXTURE_2D, texnum ); qglReadBuffer( GL_BACK ); opts.width = imageWidth; opts.height = imageHeight; qglCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, x, y, imageWidth, imageHeight, 0 ); // these shouldn't be necessary if the image was initialized properly qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); backEnd.pc.c_copyFrameBuffer++; } /* ==================== CopyDepthbuffer ==================== */ void idImage::CopyDepthbuffer( int x, int y, int imageWidth, int imageHeight ) { qglBindTexture( ( opts.textureType == TT_CUBIC ) ? GL_TEXTURE_CUBE_MAP_EXT : GL_TEXTURE_2D, texnum ); opts.width = imageWidth; opts.height = imageHeight; qglCopyTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, x, y, imageWidth, imageHeight, 0 ); backEnd.pc.c_copyFrameBuffer++; } /* ============= RB_UploadScratchImage if rows = cols * 6, assume it is a cube map animation ============= */ void idImage::UploadScratch( const byte * data, int cols, int rows ) { // if rows = cols * 6, assume it is a cube map animation if ( rows == cols * 6 ) { rows /= 6; const byte * pic[6]; for ( int i = 0; i < 6; i++ ) { pic[i] = data + cols * rows * 4 * i; } if ( opts.textureType != TT_CUBIC || usage != TD_LOOKUP_TABLE_RGBA ) { GenerateCubeImage( pic, cols, TF_LINEAR, TD_LOOKUP_TABLE_RGBA ); return; } if ( opts.width != cols || opts.height != rows ) { opts.width = cols; opts.height = rows; AllocImage(); } SetSamplerState( TF_LINEAR, TR_CLAMP ); for ( int i = 0; i < 6; i++ ) { SubImageUpload( 0, 0, 0, i, opts.width, opts.height, pic[i] ); } } else { if ( opts.textureType != TT_2D || usage != TD_LOOKUP_TABLE_RGBA ) { GenerateImage( data, cols, rows, TF_LINEAR, TR_REPEAT, TD_LOOKUP_TABLE_RGBA ); return; } if ( opts.width != cols || opts.height != rows ) { opts.width = cols; opts.height = rows; AllocImage(); } SetSamplerState( TF_LINEAR, TR_REPEAT ); SubImageUpload( 0, 0, 0, 0, opts.width, opts.height, data ); } } /* ================== StorageSize ================== */ int idImage::StorageSize() const { if ( !IsLoaded() ) { return 0; } int baseSize = opts.width * opts.height; if ( opts.numLevels > 1 ) { baseSize *= 4; baseSize /= 3; } baseSize *= BitsForFormat( opts.format ); baseSize /= 8; return baseSize; } /* ================== Print ================== */ void idImage::Print() const { if ( generatorFunction ) { common->Printf( "F" ); } else { common->Printf( " " ); } switch ( opts.textureType ) { case TT_2D: common->Printf( " " ); break; case TT_CUBIC: common->Printf( "C" ); break; default: common->Printf( "<BAD TYPE:%i>", opts.textureType ); break; } common->Printf( "%4i %4i ", opts.width, opts.height ); switch ( opts.format ) { #define NAME_FORMAT( x ) case FMT_##x: common->Printf( "%-6s ", #x ); break; NAME_FORMAT( NONE ); NAME_FORMAT( RGBA8 ); NAME_FORMAT( XRGB8 ); NAME_FORMAT( RGB565 ); NAME_FORMAT( L8A8 ); NAME_FORMAT( ALPHA ); NAME_FORMAT( LUM8 ); NAME_FORMAT( INT8 ); NAME_FORMAT( DXT1 ); NAME_FORMAT( DXT5 ); NAME_FORMAT( DEPTH ); NAME_FORMAT( X16 ); NAME_FORMAT( Y16_X16 ); default: common->Printf( "<%3i>", opts.format ); break; } switch( filter ) { case TF_DEFAULT: common->Printf( "mip " ); break; case TF_LINEAR: common->Printf( "linr " ); break; case TF_NEAREST: common->Printf( "nrst " ); break; default: common->Printf( "<BAD FILTER:%i>", filter ); break; } switch ( repeat ) { case TR_REPEAT: common->Printf( "rept " ); break; case TR_CLAMP_TO_ZERO: common->Printf( "zero " ); break; case TR_CLAMP_TO_ZERO_ALPHA: common->Printf( "azro " ); break; case TR_CLAMP: common->Printf( "clmp " ); break; default: common->Printf( "<BAD REPEAT:%i>", repeat ); break; } common->Printf( "%4ik ", StorageSize() / 1024 ); common->Printf( " %s\n", GetName() ); } /* =============== idImage::Reload =============== */ void idImage::Reload( bool force ) { // always regenerate functional images if ( generatorFunction ) { common->DPrintf( "regenerating %s.\n", GetName() ); generatorFunction( this ); return; } // check file times if ( !force ) { ID_TIME_T current; if ( cubeFiles != CF_2D ) { R_LoadCubeImages( imgName, cubeFiles, NULL, NULL, &current ); } else { // get the current values R_LoadImageProgram( imgName, NULL, NULL, NULL, &current ); } if ( current <= sourceFileTime ) { return; } } common->DPrintf( "reloading %s.\n", GetName() ); PurgeImage(); // Load is from the front end, so the back end must be synced ActuallyLoadImage( false ); } /* ======================== idImage::SetSamplerState ======================== */ void idImage::SetSamplerState( textureFilter_t tf, textureRepeat_t tr ) { if ( tf == filter && tr == repeat ) { return; } filter = tf; repeat = tr; qglBindTexture( ( opts.textureType == TT_CUBIC ) ? GL_TEXTURE_CUBE_MAP_EXT : GL_TEXTURE_2D, texnum ); SetTexParameters(); }
26.814246
366
0.648784
[ "render" ]
192804508bfb9124e3817c786e3ea8e8da4e841a
15,237
cpp
C++
src/GameEngineLib/src/sdlgui/imageview.cpp
hugetto/2DGame
833c6596df8c2f9daf14cb9ebfffa36b77f96218
[ "Apache-2.0" ]
null
null
null
src/GameEngineLib/src/sdlgui/imageview.cpp
hugetto/2DGame
833c6596df8c2f9daf14cb9ebfffa36b77f96218
[ "Apache-2.0" ]
null
null
null
src/GameEngineLib/src/sdlgui/imageview.cpp
hugetto/2DGame
833c6596df8c2f9daf14cb9ebfffa36b77f96218
[ "Apache-2.0" ]
null
null
null
/* sdl_gui/imageview.cpp -- Widget used to display images. The image view widget was contributed by Stefan Ivanov. Based on NanoGUI by Wenzel Jakob <wenzel@inf.ethz.ch>. Adaptation for SDL by Dalerank <dalerankn8@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 "pch.h" #include <sdlgui/imageview.h> #include <sdlgui/window.h> #include <sdlgui/screen.h> #include <SDL.h> #include <sdlgui/theme.h> #include <cmath> NAMESPACE_BEGIN(sdlgui) namespace { std::vector<std::string> splitString(const std::string& text, const std::string& delimiter) { using std::string; using std::vector; vector<string> strings; string::size_type current = 0; string::size_type previous = 0; while ((current = text.find(delimiter, previous)) != string::npos) { strings.push_back(text.substr(previous, current - previous)); previous = current + 1; } strings.push_back(text.substr(previous)); return strings; } } ImageView::ImageView(Widget* parent, SDL_Texture* texture) : Widget(parent), mTexture(texture), mScale(1.0f), mOffset(Vector2f::Zero()), mFixedScale(false), mFixedOffset(false), mPixelInfoCallback(nullptr) { updateImageParameters(); } ImageView::~ImageView() {} void ImageView::bindImage(SDL_Texture* texture) { mTexture = texture; updateImageParameters(); fit(); } Vector2f ImageView::imageCoordinateAt(const Vector2f& position) const { auto imagePosition = position - mOffset; return imagePosition / mScale; } Vector2f ImageView::clampedImageCoordinateAt(const Vector2f& position) const { Vector2f imageCoordinate = imageCoordinateAt(position); return imageCoordinate.cmax({ 0,0 }).cmin(imageSizeF()); } Vector2f ImageView::positionForCoordinate(const Vector2f& imageCoordinate) const { return imageCoordinate*mScale + mOffset; } void ImageView::setImageCoordinateAt(const Vector2f& position, const Vector2f& imageCoordinate) { // Calculate where the new offset must be in order to satisfy the image position equation. // Round the floating point values to balance out the floating point to integer conversions. mOffset = position - (imageCoordinate * mScale); // .unaryExpr([](float x) { return std::round(x); }); // Clamp offset so that the image remains near the screen. mOffset = mOffset.cmin(sizeF()).cmax(-scaledImageSizeF()); } void ImageView::center() { mOffset = (sizeF() - scaledImageSizeF()) / 2; } void ImageView::fit() { // Calculate the appropriate scaling factor. mScale = (sizeF().cquotient(imageSizeF())).minCoeff(); center(); } void ImageView::setScaleCentered(float scale) { auto centerPosition = sizeF() / 2; auto p = imageCoordinateAt(centerPosition); mScale = scale; setImageCoordinateAt(centerPosition, p); } void ImageView::moveOffset(const Vector2f& delta) { // Apply the delta to the offset. mOffset += delta; // Prevent the image from going out of bounds. auto scaledSize = scaledImageSizeF(); if (mOffset.x + scaledSize.x < 0) mOffset.x = -scaledSize.x; if (mOffset.x > sizeF().x) mOffset.x = sizeF().x; if (mOffset.y + scaledSize.y < 0) mOffset.y = -scaledSize.y; if (mOffset.y > sizeF().y) mOffset.y = sizeF().y; } void ImageView::zoom(int amount, const Vector2f& focusPosition) { auto focusedCoordinate = imageCoordinateAt(focusPosition); float scaleFactor = std::pow(mZoomSensitivity, amount); mScale = std::max(0.01f, scaleFactor * mScale); setImageCoordinateAt(focusPosition, focusedCoordinate); } bool ImageView::mouseDragEvent(const Vector2i& p, const Vector2i& rel, int button, int /*modifiers*/) { if ((button & (1 << SDL_BUTTON_LEFT)) != 0 && !mFixedOffset) { setImageCoordinateAt((p + rel).tofloat(), imageCoordinateAt(p.cast<float>())); return true; } return false; } bool ImageView::gridVisible() const { return (mGridThreshold != -1) && (mScale > mGridThreshold); } bool ImageView::pixelInfoVisible() const { return mPixelInfoCallback && (mPixelInfoThreshold != -1) && (mScale > mPixelInfoThreshold); } bool ImageView::helpersVisible() const { return gridVisible() || pixelInfoVisible(); } bool ImageView::scrollEvent(const Vector2i& p, const Vector2f& rel) { if (mFixedScale) return false; float v = rel.y; if (std::abs(v) < 1) v = std::copysign(1.f, v); zoom(v, (p -position()).tofloat()); return true; } bool ImageView::keyboardEvent(int key, int /*scancode*/, int action, int modifiers) { if (action) { switch (key) { case SDLK_LEFT: if (!mFixedOffset) { if (SDLK_LCTRL & modifiers) moveOffset(Vector2f(30, 0)); else moveOffset(Vector2f(10, 0)); return true; } break; case SDLK_RIGHT: if (!mFixedOffset) { if (SDLK_LCTRL & modifiers) moveOffset(Vector2f(-30, 0)); else moveOffset(Vector2f(-10, 0)); return true; } break; case SDLK_DOWN: if (!mFixedOffset) { if (SDLK_LCTRL & modifiers) moveOffset(Vector2f(0, -30)); else moveOffset(Vector2f(0, -10)); return true; } break; case SDLK_UP: if (!mFixedOffset) { if ( SDLK_LCTRL & modifiers) moveOffset(Vector2f(0, 30)); else moveOffset(Vector2f(0, 10)); return true; } break; } } return false; } bool ImageView::keyboardCharacterEvent(unsigned int codepoint) { switch (codepoint) { case '-': if (!mFixedScale) { zoom(-1, sizeF() / 2); return true; } break; case '+': if (!mFixedScale) { zoom(1, sizeF() / 2); return true; } break; case 'c': if (!mFixedOffset) { center(); return true; } break; case 'f': if (!mFixedOffset && !mFixedScale) { fit(); return true; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!mFixedScale) { setScaleCentered(1 << (codepoint - '1')); return true; } break; default: return false; } return false; } Vector2i ImageView::preferredSize(SDL_Renderer* /*ctx*/) const { return mImageSize; } void ImageView::performLayout(SDL_Renderer* ctx) { Widget::performLayout(ctx); center(); } void ImageView::draw(SDL_Renderer* renderer) { Widget::draw(renderer); SDL_Point ap = getAbsolutePos(); const Screen* screen = dynamic_cast<const Screen*>(this->window()->parent()); assert(screen); Vector2f screenSize = screen->size().tofloat(); Vector2f scaleFactor = imageSizeF().cquotient(screenSize) * mScale; Vector2f positionInScreen = absolutePosition().tofloat(); Vector2f positionAfterOffset = positionInScreen + mOffset; Vector2f imagePosition = positionAfterOffset.cquotient(screenSize); if (mTexture) { Vector2i borderPosition = Vector2i{ ap.x, ap.y } + mOffset.toint(); Vector2i borderSize = scaledImageSizeF().toint(); SDL_Rect br{ borderPosition.x + 1, borderPosition.y + 1, borderSize.x - 2, borderSize.y - 2 }; PntRect r = srect2pntrect(br); PntRect wr = { ap.x, ap.y, ap.x + width(), ap.y + height() }; if (r.x1 <= wr.x1) r.x1 = wr.x1; if (r.x2 >= wr.x2) r.x2 = wr.x2; if (r.y1 <= wr.y1) r.y1 = wr.y1; if (r.y2 >= wr.y2) r.y2 = wr.y2; int ix = 0, iy = 0; int iw = r.x2 - r.x1; int ih = r.y2 - r.y1; if (positionAfterOffset.x <= ap.x) { ix = ap.x - positionAfterOffset.x; iw = mImageSize.x- ix; positionAfterOffset.x = absolutePosition().x; } if (positionAfterOffset.y <= ap.y) { iy = ap.y - positionAfterOffset.y; ih = mImageSize.y - iy; positionAfterOffset.y = absolutePosition().y; } SDL_Rect imgrect{ix, iy, iw, ih}; SDL_Rect rect{ positionAfterOffset.x, positionAfterOffset.y, imgrect.w, imgrect.h}; SDL_RenderCopy(renderer, mTexture, &imgrect, &rect); } drawWidgetBorder(renderer, ap); drawImageBorder(renderer, ap); if (helpersVisible()) drawHelpers(renderer); } void ImageView::updateImageParameters() { int w, h; SDL_QueryTexture(mTexture, nullptr, nullptr, &w, &h); mImageSize = Vector2i(w, h); } void ImageView::drawWidgetBorder(SDL_Renderer* renderer, const SDL_Point& ap) const { SDL_Color lc = mTheme->mBorderLight.toSdlColor(); SDL_Rect lr{ ap.x - 1, ap.y - 1, mSize.x + 2, mSize.y + 2 }; SDL_SetRenderDrawColor(renderer, lc.r, lc.g, lc.b, lc.a); SDL_RenderDrawRect(renderer, &lr); SDL_Color dc = mTheme->mBorderDark.toSdlColor(); SDL_Rect dr{ ap.x - 1, ap.y - 1, mSize.x + 2, mSize.y + 2 }; SDL_SetRenderDrawColor(renderer, dc.r, dc.g, dc.b, dc.a); SDL_RenderDrawRect(renderer, &dr); } void ImageView::drawImageBorder(SDL_Renderer* renderer, const SDL_Point& ap) const { Vector2i borderPosition = Vector2i{ ap.x, ap.y } + mOffset.toint(); Vector2i borderSize = scaledImageSizeF().toint(); SDL_Rect br{ borderPosition.x + 1, borderPosition.y + 1, borderSize.x - 2, borderSize.y - 2 }; PntRect r = srect2pntrect(br); PntRect wr = { ap.x, ap.y, ap.x + width(), ap.y + height() }; if (r.x1 <= wr.x1) r.x1 = wr.x1; if (r.x2 >= wr.x2) r.x2 = wr.x2; if (r.y1 <= wr.y1) r.y1 = wr.y1; if (r.y2 >= wr.y2) r.y2 = wr.y2; SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); if (r.x1 > wr.x1) SDL_RenderDrawLine(renderer, r.x1, r.y1, r.x1, r.y2 - 1 ); if (r.y1 > wr.y1) SDL_RenderDrawLine(renderer, r.x1, r.y1, r.x2-1, r.y1 ); if (r.x2 < wr.x2) SDL_RenderDrawLine(renderer, r.x2, r.y1, r.x2, r.y2 - 1); if (r.y2 < wr.y2) SDL_RenderDrawLine(renderer, r.x1, r.y2, r.x2-1, r.y2); } void ImageView::drawHelpers(SDL_Renderer* renderer) const { Vector2f upperLeftCorner = positionForCoordinate(Vector2f{ 0, 0 }) + positionF(); Vector2f lowerRightCorner = positionForCoordinate(imageSizeF()) + positionF(); // Use the scissor method in NanoVG to display only the correct part of the grid. Vector2f scissorPosition = upperLeftCorner.cmax(positionF()); Vector2f sizeOffsetDifference = sizeF() - mOffset; Vector2f scissorSize = sizeOffsetDifference.cmin(sizeF()); SDL_Rect r{ scissorPosition.x, scissorPosition.y, scissorSize.x, scissorSize.y }; if (gridVisible()) drawPixelGrid(renderer, upperLeftCorner, lowerRightCorner, mScale); if (pixelInfoVisible()) drawPixelInfo(renderer, mScale); } void ImageView::drawPixelGrid(SDL_Renderer* renderer, const Vector2f& upperLeftCorner, const Vector2f& lowerRightCorner, const float stride) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // Draw the vertical lines for the grid float currentX = std::floor(upperLeftCorner.x); while (currentX <= lowerRightCorner.x) { SDL_RenderDrawLine(renderer, std::floor(currentX), std::floor(upperLeftCorner.y), std::floor(currentX), std::floor(lowerRightCorner.y)); currentX += stride; } // Draw the horizontal lines for the grid. float currentY = std::floor(upperLeftCorner.y); while (currentY <= lowerRightCorner.y) { SDL_RenderDrawLine(renderer, std::floor(upperLeftCorner.x), std::floor(currentY), std::floor(lowerRightCorner.x), std::floor(currentY)); currentY += stride; } } void ImageView::drawPixelInfo(SDL_Renderer* renderer, const float stride) const { // Extract the image coordinates at the two corners of the widget. Vector2f currentPixelF = clampedImageCoordinateAt({ 0,0 }); Vector2f lastPixelF = clampedImageCoordinateAt(sizeF()); // Round the top left coordinates down and bottom down coordinates up. // This is done so that the edge information does not pop up suddenly when it gets in range. currentPixelF = currentPixelF.floor(); lastPixelF = lastPixelF.ceil(); Vector2i currentPixel = currentPixelF.cast<int>(); Vector2i lastPixel = lastPixelF.cast<int>(); // Extract the positions for where to draw the text. Vector2f currentCellPosition = (positionF() + positionForCoordinate(currentPixelF)); float xInitialPosition = currentCellPosition.x; int xInitialIndex = currentPixel.x; // Properly scale the pixel information for the given stride. auto fontSize = stride * mFontScaleFactor; static constexpr float maxFontSize = 30.0f; fontSize = fontSize > maxFontSize ? maxFontSize : fontSize; /* nvgSave(ctx); nvgBeginPath(ctx); nvgFontSize(ctx, fontSize); nvgTextAlign(ctx, NVG_ALIGN_CENTER | NVG_ALIGN_TOP); nvgFontFace(ctx, "sans"); while (currentPixel.y() != lastPixel.y()) { while (currentPixel.x() != lastPixel.x()) { writePixelInfo(ctx, currentCellPosition, currentPixel, stride); currentCellPosition.x() += stride; ++currentPixel.x(); } currentCellPosition.x() = xInitialPosition; currentCellPosition.y() += stride; ++currentPixel.y(); currentPixel.x() = xInitialIndex; } nvgRestore(ctx);*/ } void ImageView::writePixelInfo(SDL_Renderer* renderer, const Vector2f& cellPosition, const Vector2i& pixel, const float stride) const { /* auto pixelData = mPixelInfoCallback(pixel); auto pixelDataRows = splitString(pixelData.first, "\n"); // If no data is provided for this pixel then simply return. if (pixelDataRows.empty()) return; nvgFillColor(ctx, pixelData.second); auto padding = stride / 10; auto maxSize = stride - 2 * padding; // Measure the size of a single line of text. float bounds[4]; nvgTextBoxBounds(ctx, 0.0f, 0.0f, maxSize, pixelDataRows.front().data(), nullptr, bounds); auto rowHeight = bounds[3] - bounds[1]; auto totalRowsHeight = rowHeight * pixelDataRows.size(); // Choose the initial y offset and the index for the past the last visible row. auto yOffset = 0.0f; auto lastIndex = 0; if (totalRowsHeight > maxSize) { yOffset = padding; lastIndex = (int) (maxSize / rowHeight); } else { yOffset = (stride - totalRowsHeight) / 2; lastIndex = (int) pixelDataRows.size(); } for (int i = 0; i != lastIndex; ++i) { nvgText(ctx, cellPosition.x() + stride / 2, cellPosition.y() + yOffset, pixelDataRows[i].data(), nullptr); yOffset += rowHeight; } */ } NAMESPACE_END(sdlgui)
31.612033
106
0.627289
[ "vector" ]
192dce1600d7f146cb6ef030e55f7fead7834ec7
101,919
cc
C++
src/couch-kvstore/couch-kvstore.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
src/couch-kvstore/couch-kvstore.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
src/couch-kvstore/couch-kvstore.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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 "config.h" #ifdef _MSC_VER #define PATH_MAX MAX_PATH #endif #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <list> #include <map> #include <platform/checked_snprintf.h> #include <string> #include <utility> #include <vector> #include <cJSON.h> #include <platform/dirutils.h> #include "common.h" #include "couch-kvstore/couch-kvstore.h" #define STATWRITER_NAMESPACE couchstore_engine #include "statwriter.h" #undef STATWRITER_NAMESPACE #include "vbucket.h" #include <JSON_checker.h> #include <snappy-c.h> using namespace CouchbaseDirectoryUtilities; static const int MAX_OPEN_DB_RETRY = 10; static const uint32_t DEFAULT_META_LEN = 16; extern "C" { static int recordDbDumpC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::recordDbDump(db, docinfo, ctx); } } extern "C" { static int getMultiCbC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::getMultiCb(db, docinfo, ctx); } } static std::string getStrError(Db *db) { const size_t max_msg_len = 256; char msg[max_msg_len]; couchstore_last_os_error(db, msg, max_msg_len); std::string errorStr(msg); return errorStr; } static uint8_t determine_datatype(const unsigned char* value, size_t length) { if (checkUTF8JSON(value, length)) { return PROTOCOL_BINARY_DATATYPE_JSON; } else { return PROTOCOL_BINARY_RAW_BYTES; } } static bool endWithCompact(const std::string &filename) { size_t pos = filename.find(".compact"); if (pos == std::string::npos || (filename.size() - sizeof(".compact")) != pos) { return false; } return true; } static void discoverDbFiles(const std::string &dir, std::vector<std::string> &v) { std::vector<std::string> files = findFilesContaining(dir, ".couch"); std::vector<std::string>::iterator ii; for (ii = files.begin(); ii != files.end(); ++ii) { if (!endWithCompact(*ii)) { v.push_back(*ii); } } } static int getMutationStatus(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return MUTATION_SUCCESS; case COUCHSTORE_ERROR_NO_HEADER: case COUCHSTORE_ERROR_NO_SUCH_FILE: case COUCHSTORE_ERROR_DOC_NOT_FOUND: // this return causes ep engine to drop the failed flush // of an item since it does not know about the itme any longer return DOC_NOT_FOUND; default: // this return causes ep engine to keep requeuing the failed // flush of an item return MUTATION_FAILED; } } static bool allDigit(std::string &input) { size_t numchar = input.length(); for(size_t i = 0; i < numchar; ++i) { if (!isdigit(input[i])) { return false; } } return true; } static std::string couchkvstore_strerrno(Db *db, couchstore_error_t err) { return (err == COUCHSTORE_ERROR_OPEN_FILE || err == COUCHSTORE_ERROR_READ || err == COUCHSTORE_ERROR_WRITE || err == COUCHSTORE_ERROR_FILE_CLOSE) ? getStrError(db) : "none"; } struct GetMultiCbCtx { GetMultiCbCtx(CouchKVStore &c, uint16_t v, vb_bgfetch_queue_t &f) : cks(c), vbId(v), fetches(f) {} CouchKVStore &cks; uint16_t vbId; vb_bgfetch_queue_t &fetches; }; struct StatResponseCtx { public: StatResponseCtx(std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &sm, uint16_t vb) : statMap(sm), vbId(vb) { /* EMPTY */ } std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &statMap; uint16_t vbId; }; struct AllKeysCtx { AllKeysCtx(std::shared_ptr<Callback<uint16_t&, char*&> > callback, uint32_t cnt) : cb(callback), count(cnt) { } std::shared_ptr<Callback<uint16_t&, char*&> > cb; uint32_t count; }; CouchRequest::CouchRequest(const Item &it, uint64_t rev, MutationRequestCallback &cb, bool del) : IORequest(it.getVBucketId(), cb, del, it.getKey()), value(it.getValue()), fileRevNum(rev) { uint64_t cas = htonll(it.getCas()); uint32_t flags = it.getFlags(); uint32_t vlen = it.getNBytes(); uint32_t exptime = it.getExptime(); uint8_t confresmode = static_cast<uint8_t>(it.getConflictResMode()); // Datatype used to determine whether document requires compression or not uint8_t datatype; // Save time of deletion in expiry time field of deleted item's metadata. if (del) { exptime = ep_real_time(); } exptime = htonl(exptime); dbDoc.id.buf = const_cast<char *>(key.c_str()); dbDoc.id.size = it.getNKey(); if (vlen) { dbDoc.data.buf = const_cast<char *>(value->getData()); dbDoc.data.size = vlen; datatype = it.getDataType(); } else { dbDoc.data.buf = NULL; dbDoc.data.size = 0; datatype = 0x00; } memset(meta, 0, sizeof(meta)); memcpy(meta, &cas, 8); memcpy(meta + 8, &exptime, 4); memcpy(meta + 12, &flags, 4); *(meta + DEFAULT_META_LEN) = FLEX_META_CODE; //For a deleted item, there is no extended meta data available //as part of the item object, hence by default populate the //data type to PROTOCOL_BINARY_RAW_BYTES if (del) { uint8_t del_datatype = PROTOCOL_BINARY_RAW_BYTES; memcpy(meta + DEFAULT_META_LEN + FLEX_DATA_OFFSET, &del_datatype, sizeof(uint8_t)); } else { memcpy(meta + DEFAULT_META_LEN + FLEX_DATA_OFFSET, it.getExtMeta(), it.getExtMetaLen()); } memcpy(meta + DEFAULT_META_LEN + FLEX_DATA_OFFSET + EXT_META_LEN, &confresmode, CONFLICT_RES_META_LEN); dbDocInfo.db_seq = it.getBySeqno(); dbDocInfo.rev_meta.buf = reinterpret_cast<char *>(meta); dbDocInfo.rev_meta.size = COUCHSTORE_METADATA_SIZE; dbDocInfo.rev_seq = it.getRevSeqno(); dbDocInfo.size = dbDoc.data.size; if (del) { dbDocInfo.deleted = 1; } else { dbDocInfo.deleted = 0; } dbDocInfo.id = dbDoc.id; dbDocInfo.content_meta = (datatype == PROTOCOL_BINARY_DATATYPE_JSON) ? COUCH_DOC_IS_JSON : COUCH_DOC_NON_JSON_MODE; //Compress only those documents that aren't already compressed. if (dbDoc.data.size > 0 && !deleteItem) { if (datatype == PROTOCOL_BINARY_RAW_BYTES || datatype == PROTOCOL_BINARY_DATATYPE_JSON) { dbDocInfo.content_meta |= COUCH_DOC_IS_COMPRESSED; } } } CouchKVStore::CouchKVStore(KVStoreConfig &config, bool read_only) : CouchKVStore(config, *couchstore_get_default_file_ops(), read_only) { } CouchKVStore::CouchKVStore(KVStoreConfig &config, FileOpsInterface& ops, bool read_only) : KVStore(config, read_only), dbname(config.getDBName()), intransaction(false), backfillCounter(0), logger(config.getLogger()), base_ops(ops) { createDataDir(dbname); statCollectingFileOps = getCouchstoreStatsOps(st.fsStats, base_ops); statCollectingFileOpsCompaction = getCouchstoreStatsOps( st.fsStatsCompaction, base_ops); // init db file map with default revision number, 1 numDbFiles = configuration.getMaxVBuckets(); cachedVBStates.reserve(numDbFiles); // pre-allocate lookup maps (vectors) given we have a relatively // small, fixed number of vBuckets. dbFileRevMap.assign(numDbFiles, Couchbase::RelaxedAtomic<uint64_t>(1)); cachedDocCount.assign(numDbFiles, Couchbase::RelaxedAtomic<size_t>(0)); cachedDeleteCount.assign(numDbFiles, Couchbase::RelaxedAtomic<size_t>(-1)); cachedFileSize.assign(numDbFiles, Couchbase::RelaxedAtomic<uint64_t>(0)); cachedSpaceUsed.assign(numDbFiles, Couchbase::RelaxedAtomic<uint64_t>(0)); cachedVBStates.assign(numDbFiles, nullptr); initialize(); } CouchKVStore::CouchKVStore(const CouchKVStore &copyFrom) : KVStore(copyFrom), dbname(copyFrom.dbname), dbFileRevMap(copyFrom.dbFileRevMap), numDbFiles(copyFrom.numDbFiles), intransaction(false), logger(copyFrom.logger), base_ops(copyFrom.base_ops) { createDataDir(dbname); statCollectingFileOps = getCouchstoreStatsOps(st.fsStats, base_ops); statCollectingFileOpsCompaction = getCouchstoreStatsOps( st.fsStatsCompaction, base_ops); } void CouchKVStore::initialize() { std::vector<uint16_t> vbids; std::vector<std::string> files; discoverDbFiles(dbname, files); populateFileNameMap(files, &vbids); Db *db = NULL; couchstore_error_t errorCode; std::vector<uint16_t>::iterator itr = vbids.begin(); for (; itr != vbids.end(); ++itr) { uint16_t id = *itr; uint64_t rev = dbFileRevMap[id]; errorCode = openDB(id, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errorCode == COUCHSTORE_SUCCESS) { readVBState(db, id); /* update stat */ ++st.numLoadedVb; closeDatabaseHandle(db); } else { logger.log(EXTENSION_LOG_WARNING, "Failed to open database file " "%s/%" PRIu16 ".couch.%" PRIu64, dbname.c_str(), id, rev); remVBucketFromDbFileMap(id); cachedVBStates[id] = NULL; } db = NULL; if (!isReadOnly()) { removeCompactFile(dbname, id, rev); } } } CouchKVStore::~CouchKVStore() { close(); for (std::vector<vbucket_state *>::iterator it = cachedVBStates.begin(); it != cachedVBStates.end(); it++) { vbucket_state *vbstate = *it; if (vbstate) { delete vbstate; *it = NULL; } } } void CouchKVStore::reset(uint16_t vbucketId) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::reset: Not valid on a read-only " "object."); } vbucket_state *state = cachedVBStates[vbucketId]; if (state) { state->reset(); cachedDocCount[vbucketId] = 0; cachedDeleteCount[vbucketId] = 0; cachedFileSize[vbucketId] = 0; cachedSpaceUsed[vbucketId] = 0; //Unlink the couchstore file upon reset unlinkCouchFile(vbucketId, dbFileRevMap[vbucketId]); setVBucketState(vbucketId, *state, VBStatePersist::VBSTATE_PERSIST_WITH_COMMIT, true); updateDbFileMap(vbucketId, 1); } else { throw std::invalid_argument("CouchKVStore::reset: No entry in cached " "states for vbucket " + std::to_string(vbucketId)); } } void CouchKVStore::set(const Item &itm, Callback<mutation_result> &cb) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::set: Not valid on a read-only " "object."); } if (!intransaction) { throw std::invalid_argument("CouchKVStore::set: intransaction must be " "true to perform a set operation."); } bool deleteItem = false; MutationRequestCallback requestcb; uint64_t fileRev = dbFileRevMap[itm.getVBucketId()]; // each req will be de-allocated after commit requestcb.setCb = &cb; CouchRequest *req = new CouchRequest(itm, fileRev, requestcb, deleteItem); pendingReqsQ.push_back(req); } void CouchKVStore::get(const std::string &key, uint16_t vb, Callback<GetValue> &cb, bool fetchDelete) { Db *db = NULL; GetValue rv; uint64_t fileRev = dbFileRevMap[vb]; couchstore_error_t errCode = openDB(vb, fileRev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; logger.log(EXTENSION_LOG_WARNING, "Failed to open database to retrieve data " "from vBucketId = %d, key = %s\n", vb, key.c_str()); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); return; } getWithHeader(db, key, vb, cb, fetchDelete); closeDatabaseHandle(db); } void CouchKVStore::getWithHeader(void *dbHandle, const std::string &key, uint16_t vb, Callback<GetValue> &cb, bool fetchDelete) { Db *db = (Db *)dbHandle; hrtime_t start = gethrtime(); RememberingCallback<GetValue> *rc = dynamic_cast<RememberingCallback<GetValue> *>(&cb); bool getMetaOnly = rc && rc->val.isPartial(); DocInfo *docInfo = NULL; sized_buf id; GetValue rv; id.size = key.size(); id.buf = const_cast<char *>(key.c_str()); couchstore_error_t errCode = couchstore_docinfo_by_id(db, (uint8_t *)id.buf, id.size, &docInfo); if (errCode != COUCHSTORE_SUCCESS) { if (!getMetaOnly) { // log error only if this is non-xdcr case logger.log(EXTENSION_LOG_WARNING, "Failed to retrieve doc info from " "database, vbucketId=%d, key=%s error=%s [%s]\n", vb, id.buf, couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); } } else { if (docInfo == nullptr) { throw std::logic_error("CouchKVStore::getWithHeader: " "couchstore_docinfo_by_id returned success but docInfo " "is NULL"); } errCode = fetchDoc(db, docInfo, rv, vb, getMetaOnly, fetchDelete); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to retrieve key value from " "database, vbucketId=%d key=%s error=%s [%s] " "deleted=%s", vb, id.buf, couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str(), docInfo->deleted ? "yes" : "no"); } // record stats st.readTimeHisto.add((gethrtime() - start) / 1000); if (errCode == COUCHSTORE_SUCCESS) { st.readSizeHisto.add(key.length() + rv.getValue()->getNBytes()); } } if(errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; } couchstore_free_docinfo(docInfo); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); } void CouchKVStore::getMulti(uint16_t vb, vb_bgfetch_queue_t &itms) { int numItems = itms.size(); uint64_t fileRev = dbFileRevMap[vb]; Db *db = NULL; couchstore_error_t errCode = openDB(vb, fileRev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open database for data fetch, " "vBucketId = %" PRIu16 ", numDocs = %d\n", vb, numItems); st.numGetFailure.fetch_add(numItems); vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); ++itr) { vb_bgfetch_item_ctx_t &bg_itm_ctx = (*itr).second; std::list<VBucketBGFetchItem *> &fetches = bg_itm_ctx.bgfetched_list; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); ++fitr) { (*fitr)->value.setStatus(ENGINE_NOT_MY_VBUCKET); } } return; } size_t idx = 0; sized_buf *ids = new sized_buf[itms.size()]; vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); ++itr) { ids[idx].size = itr->first.size(); ids[idx].buf = const_cast<char *>(itr->first.c_str()); ++idx; } GetMultiCbCtx ctx(*this, vb, itms); errCode = couchstore_docinfos_by_id(db, ids, itms.size(), 0, getMultiCbC, &ctx); if (errCode != COUCHSTORE_SUCCESS) { st.numGetFailure.fetch_add(numItems); for (itr = itms.begin(); itr != itms.end(); ++itr) { logger.log(EXTENSION_LOG_WARNING, "Failed to read database by" " vBucketId = %" PRIu16 " key = %s error = %s [%s]\n", vb, (*itr).first.c_str(), couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); vb_bgfetch_item_ctx_t &bg_itm_ctx = (*itr).second; std::list<VBucketBGFetchItem *> &fetches = bg_itm_ctx.bgfetched_list; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); ++fitr) { (*fitr)->value.setStatus(couchErr2EngineErr(errCode)); } } } closeDatabaseHandle(db); delete []ids; } void CouchKVStore::del(const Item &itm, Callback<int> &cb) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::del: Not valid on a read-only " "object."); } if (!intransaction) { throw std::invalid_argument("CouchKVStore::del: intransaction must be " "true to perform a delete operation."); } uint64_t fileRev = dbFileRevMap[itm.getVBucketId()]; MutationRequestCallback requestcb; requestcb.delCb = &cb; CouchRequest *req = new CouchRequest(itm, fileRev, requestcb, true); pendingReqsQ.push_back(req); } void CouchKVStore::delVBucket(uint16_t vbucket) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::delVBucket: Not valid on a " "read-only object."); } unlinkCouchFile(vbucket, dbFileRevMap[vbucket]); if (cachedVBStates[vbucket]) { delete cachedVBStates[vbucket]; } cachedDocCount[vbucket] = 0; cachedDeleteCount[vbucket] = 0; cachedFileSize[vbucket] = 0; cachedSpaceUsed[vbucket] = 0; std::string failovers("[{\"id\":0, \"seq\":0}]"); cachedVBStates[vbucket] = new vbucket_state(vbucket_state_dead, 0, 0, 0, 0, 0, 0, 0, INITIAL_DRIFT, failovers); updateDbFileMap(vbucket, 1); } std::vector<vbucket_state *> CouchKVStore::listPersistedVbuckets() { return cachedVBStates; } void CouchKVStore::getPersistedStats(std::map<std::string, std::string> &stats) { char *buffer = NULL; std::string fname = dbname + "/stats.json"; if (access(fname.c_str(), R_OK) == -1) { return ; } std::ifstream session_stats; session_stats.exceptions (session_stats.failbit | session_stats.badbit); try { session_stats.open(fname.c_str(), std::ios::binary); session_stats.seekg(0, std::ios::end); int flen = session_stats.tellg(); if (flen < 0) { logger.log(EXTENSION_LOG_WARNING, "Error in session stats ifstream!!!"); session_stats.close(); return; } session_stats.seekg(0, std::ios::beg); buffer = new char[flen + 1]; session_stats.read(buffer, flen); session_stats.close(); buffer[flen] = '\0'; cJSON *json_obj = cJSON_Parse(buffer); if (!json_obj) { logger.log(EXTENSION_LOG_WARNING, "Failed to parse the session stats json doc!!!"); delete[] buffer; return; } int json_arr_size = cJSON_GetArraySize(json_obj); for (int i = 0; i < json_arr_size; ++i) { cJSON *obj = cJSON_GetArrayItem(json_obj, i); if (obj) { stats[obj->string] = obj->valuestring ? obj->valuestring : ""; } } cJSON_Delete(json_obj); } catch (const std::ifstream::failure &e) { logger.log(EXTENSION_LOG_WARNING, "Failed to load the engine session stats " "due to IO exception \"%s\"", e.what()); } catch (...) { logger.log(EXTENSION_LOG_WARNING, "Failed to load the engine session stats " "due to IO exception"); } delete[] buffer; } static std::string getDBFileName(const std::string &dbname, uint16_t vbid, uint64_t rev) { std::stringstream ss; ss << dbname << "/" << vbid << ".couch." << rev; return ss.str(); } static int edit_docinfo_hook(DocInfo **info, const sized_buf *item) { if ((*info)->rev_meta.size == DEFAULT_META_LEN) { // Metadata doesn't have flex_meta_code, datatype and // conflict_resolution_mode, provision space for // these paramenters. const unsigned char* data; bool ret; if (((*info)->content_meta | COUCH_DOC_IS_COMPRESSED) == (*info)->content_meta) { size_t uncompr_len; snappy_uncompressed_length(item->buf, item->size, &uncompr_len); char *dbuf = (char *) malloc(uncompr_len); snappy_uncompress(item->buf, item->size, dbuf, &uncompr_len); data = (const unsigned char*)dbuf; ret = checkUTF8JSON(data, uncompr_len); free(dbuf); } else { data = (const unsigned char*)item->buf; ret = checkUTF8JSON(data, item->size); } uint8_t flex_code = FLEX_META_CODE; uint8_t datatype; if (ret) { datatype = PROTOCOL_BINARY_DATATYPE_JSON; } else { datatype = PROTOCOL_BINARY_RAW_BYTES; } DocInfo *docinfo = (DocInfo *) calloc (1, sizeof(DocInfo) + (*info)->id.size + (*info)->rev_meta.size + FLEX_DATA_OFFSET + EXT_META_LEN + sizeof(uint8_t)); if (!docinfo) { LOG(EXTENSION_LOG_WARNING, "Failed to allocate docInfo, " "while editing docinfo in the compaction's docinfo_hook"); return 0; } char *extra = (char *)docinfo + sizeof(DocInfo); memcpy(extra, (*info)->id.buf, (*info)->id.size); docinfo->id.buf = extra; docinfo->id.size = (*info)->id.size; extra += (*info)->id.size; memcpy(extra, (*info)->rev_meta.buf, (*info)->rev_meta.size); memcpy(extra + (*info)->rev_meta.size, &flex_code, FLEX_DATA_OFFSET); memcpy(extra + (*info)->rev_meta.size + FLEX_DATA_OFFSET, &datatype, sizeof(uint8_t)); uint8_t conflict_resolution_mode = revision_seqno; memcpy(extra + (*info)->rev_meta.size + FLEX_DATA_OFFSET + EXT_META_LEN, &conflict_resolution_mode, sizeof(uint8_t)); docinfo->rev_meta.buf = extra; docinfo->rev_meta.size = (*info)->rev_meta.size + FLEX_DATA_OFFSET + EXT_META_LEN + sizeof(uint8_t); docinfo->db_seq = (*info)->db_seq; docinfo->rev_seq = (*info)->rev_seq; docinfo->deleted = (*info)->deleted; docinfo->content_meta = (*info)->content_meta; docinfo->bp = (*info)->bp; docinfo->size = (*info)->size; couchstore_free_docinfo(*info); *info = docinfo; return 1; } else if ((*info)->rev_meta.size == DEFAULT_META_LEN + 2) { // Metadata doesn't have conflict_resolution_mode, // provision space for this flag. DocInfo *docinfo = (DocInfo *) calloc (1, sizeof(DocInfo) + (*info)->id.size + (*info)->rev_meta.size + sizeof(uint8_t)); if (!docinfo) { LOG(EXTENSION_LOG_WARNING, "Failed to allocate docInfo, " "while editing docinfo in the compaction's docinfo_hook"); return 0; } char *extra = (char *)docinfo + sizeof(DocInfo); memcpy(extra, (*info)->id.buf, (*info)->id.size); docinfo->id.buf = extra; docinfo->id.size = (*info)->id.size; extra += (*info)->id.size; memcpy(extra, (*info)->rev_meta.buf, (*info)->rev_meta.size); uint8_t conflict_resolution_mode = revision_seqno; memcpy(extra + (*info)->rev_meta.size, &conflict_resolution_mode, sizeof(uint8_t)); docinfo->rev_meta.buf = extra; docinfo->rev_meta.size = (*info)->rev_meta.size + sizeof(uint8_t); docinfo->db_seq = (*info)->db_seq; docinfo->rev_seq = (*info)->rev_seq; docinfo->deleted = (*info)->deleted; docinfo->content_meta = (*info)->content_meta; docinfo->bp = (*info)->bp; docinfo->size = (*info)->size; couchstore_free_docinfo(*info); *info = docinfo; return 1; } return 0; } static int time_purge_hook(Db* d, DocInfo* info, void* ctx_p) { compaction_ctx* ctx = (compaction_ctx*) ctx_p; DbInfo infoDb; const uint16_t vbid = ctx->db_file_id; couchstore_db_info(d, &infoDb); //Compaction finished if (info == NULL) { return couchstore_set_purge_seq(d, ctx->max_purged_seq[vbid]); } uint64_t max_purge_seq = 0; auto it = ctx->max_purged_seq.find(vbid); if (it == ctx->max_purged_seq.end()) { ctx->max_purged_seq[vbid] = 0; } else { max_purge_seq = it->second; } if (info->rev_meta.size >= DEFAULT_META_LEN) { uint32_t exptime; memcpy(&exptime, info->rev_meta.buf + 8, 4); exptime = ntohl(exptime); if (info->deleted) { if (info->db_seq != infoDb.last_sequence) { if (ctx->drop_deletes) { // all deleted items must be dropped ... if (max_purge_seq < info->db_seq) { ctx->max_purged_seq[vbid] = info->db_seq; // track max_purged_seq } return COUCHSTORE_COMPACT_DROP_ITEM; // ...unconditionally } if (exptime < ctx->purge_before_ts && (!ctx->purge_before_seq || info->db_seq <= ctx->purge_before_seq)) { if (max_purge_seq < info->db_seq) { ctx->max_purged_seq[vbid] = info->db_seq; } return COUCHSTORE_COMPACT_DROP_ITEM; } } } else { time_t currtime = ep_real_time(); if (exptime && exptime < currtime) { std::string key(info->id.buf, info->id.size); ctx->expiryCallback->callback(ctx->db_file_id, key, info->rev_seq, currtime); } } } if (ctx->bloomFilterCallback) { bool deleted = info->deleted; std::string key((const char *)info->id.buf, info->id.size); ctx->bloomFilterCallback->callback(ctx->db_file_id, key, deleted); } return COUCHSTORE_COMPACT_KEEP_ITEM; } bool CouchKVStore::compactDB(compaction_ctx *hook_ctx) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::compactDB: Cannot perform " "on a read-only instance."); } couchstore_compact_hook hook = time_purge_hook; couchstore_docinfo_hook dhook = edit_docinfo_hook; FileOpsInterface *def_iops = statCollectingFileOpsCompaction.get(); Db *compactdb = NULL; Db *targetDb = NULL; couchstore_error_t errCode = COUCHSTORE_SUCCESS; hrtime_t start = gethrtime(); std::string dbfile; std::string compact_file; std::string new_file; kvstats_ctx kvctx; DbInfo info; uint16_t vbid = hook_ctx->db_file_id; uint64_t fileRev = dbFileRevMap[vbid]; uint64_t new_rev = fileRev + 1; // Open the source VBucket database file ... errCode = openDB(vbid, fileRev, &compactdb, (uint64_t)COUCHSTORE_OPEN_FLAG_RDONLY, nullptr, false, def_iops); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open database, vbucketId = %d " "fileRev = %" PRIu64, vbid, fileRev); return false; } // Build the temporary vbucket.compact file name dbfile = getDBFileName(dbname, vbid, fileRev); compact_file = dbfile + ".compact"; couchstore_open_flags flags(COUCHSTORE_COMPACT_FLAG_UPGRADE_DB); /** * This flag disables IO buffering in couchstore which means * file operations will trigger syscalls immediately. This has * a detrimental impact on performance and is only intended * for testing. */ if(!configuration.getBuffered()) { flags |= COUCHSTORE_OPEN_FLAG_UNBUFFERED; } // Perform COMPACTION of vbucket.couch.rev into vbucket.couch.rev.compact errCode = couchstore_compact_db_ex(compactdb, compact_file.c_str(), flags, hook, dhook, hook_ctx, def_iops); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to compact database with name=%s " "error=%s errno=%s", dbfile.c_str(), couchstore_strerror(errCode), couchkvstore_strerrno(compactdb, errCode).c_str()); closeDatabaseHandle(compactdb); return false; } // Close the source Database File once compaction is done closeDatabaseHandle(compactdb); // Rename the .compact file to one with the next revision number new_file = getDBFileName(dbname, vbid, new_rev); if (rename(compact_file.c_str(), new_file.c_str()) != 0) { logger.log(EXTENSION_LOG_WARNING, "Failed to rename '%s' to '%s': %s", compact_file.c_str(), new_file.c_str(), cb_strerror().c_str()); removeCompactFile(compact_file); return false; } // Open the newly compacted VBucket database file ... errCode = openDB(vbid, new_rev, &targetDb, (uint64_t)COUCHSTORE_OPEN_FLAG_RDONLY, NULL); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open compacted database file %s " "fileRev = %" PRIu64, new_file.c_str(), new_rev); if (remove(new_file.c_str()) != 0) { logger.log(EXTENSION_LOG_WARNING, "Warning: Failed to remove '%s': %s", new_file.c_str(), cb_strerror().c_str()); } return false; } // Update the global VBucket file map so all operations use the new file updateDbFileMap(vbid, new_rev); logger.log(EXTENSION_LOG_INFO, "INFO: created new couch db file, name=%s rev=%" PRIu64, new_file.c_str(), new_rev); couchstore_db_info(targetDb, &info); cachedFileSize[vbid] = info.file_size; cachedSpaceUsed[vbid] = info.space_used; // also update cached state with dbinfo vbucket_state *state = cachedVBStates[vbid]; if (state) { state->highSeqno = info.last_sequence; state->purgeSeqno = info.purge_seq; cachedDeleteCount[vbid] = info.deleted_count; cachedDocCount[vbid] = info.doc_count; } closeDatabaseHandle(targetDb); // Removing the stale couch file unlinkCouchFile(vbid, fileRev); st.compactHisto.add((gethrtime() - start) / 1000); return true; } vbucket_state * CouchKVStore::getVBucketState(uint16_t vbucketId) { return cachedVBStates[vbucketId]; } bool CouchKVStore::setVBucketState(uint16_t vbucketId, vbucket_state &vbstate, VBStatePersist options, bool reset) { Db *db = NULL; uint64_t fileRev, newFileRev; std::stringstream id, rev; std::string dbFileName; std::map<uint16_t, uint64_t>::iterator mapItr; kvstats_ctx kvctx; kvctx.vbucket = vbucketId; couchstore_error_t errorCode; if (options == VBStatePersist::VBSTATE_PERSIST_WITHOUT_COMMIT || options == VBStatePersist::VBSTATE_PERSIST_WITH_COMMIT) { id << vbucketId; fileRev = dbFileRevMap[vbucketId]; rev << fileRev; dbFileName = dbname + "/" + id.str() + ".couch." + rev.str(); errorCode = openDB(vbucketId, fileRev, &db, (uint64_t)COUCHSTORE_OPEN_FLAG_CREATE, &newFileRev, reset); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::setVBucketState: Failed to open database," "name=%s, error=%s", dbFileName.c_str(), couchstore_strerror(errorCode)); return false; } fileRev = newFileRev; rev << fileRev; dbFileName = dbname + "/" + id.str() + ".couch." + rev.str(); errorCode = saveVBState(db, vbstate); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; logger.log(EXTENSION_LOG_WARNING, "CouchKVStore:setVBucketState: Failed to save local doc," "name=%s, error=%s", dbFileName.c_str(), couchstore_strerror(errorCode)); closeDatabaseHandle(db); return false; } if (options == VBStatePersist::VBSTATE_PERSIST_WITH_COMMIT) { errorCode = couchstore_commit(db); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; logger.log(EXTENSION_LOG_WARNING, "CouchKVStore:setVBucketState:Commit failed, vbid=%u " "rev=%" PRIu64 " error=%s [%s]", vbucketId, fileRev, couchstore_strerror(errorCode), couchkvstore_strerrno(db, errorCode).c_str()); closeDatabaseHandle(db); return false; } } DbInfo info; errorCode = couchstore_db_info(db, &info); if (errorCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::setVBucketState: Retrieving database file" " failed for vbid=%" PRIu16 " with error=%s", vbucketId, couchstore_strerror(errorCode)); } else { cachedSpaceUsed[vbucketId] = info.space_used; cachedFileSize[vbucketId] = info.file_size; } closeDatabaseHandle(db); } else { throw std::invalid_argument("CouchKVStore::setVBucketState: invalid vb state " "persist option specified for vbucket id:" + std::to_string(vbucketId)); } return true; } bool CouchKVStore::snapshotVBucket(uint16_t vbucketId, vbucket_state &vbstate, VBStatePersist options) { if (isReadOnly()) { logger.log(EXTENSION_LOG_WARNING, "Snapshotting a vbucket cannot be performed on a read-only " "KVStore instance"); return false; } hrtime_t start = gethrtime(); if (updateCachedVBState(vbucketId, vbstate) && (options == VBStatePersist::VBSTATE_PERSIST_WITHOUT_COMMIT || options == VBStatePersist::VBSTATE_PERSIST_WITH_COMMIT)) { vbucket_state *vbs = cachedVBStates[vbucketId]; if (!setVBucketState(vbucketId, *vbs, options)) { logger.log(EXTENSION_LOG_WARNING, "Failed to persist new state, %s, for vbucket %d\n", VBucket::toString(vbstate.state), vbucketId); return false; } } st.snapshotHisto.add((gethrtime() - start) / 1000); return true; } StorageProperties CouchKVStore::getStorageProperties() { StorageProperties rv(StorageProperties::EfficientVBDump::Yes, StorageProperties::EfficientVBDeletion::Yes, StorageProperties::PersistedDeletion::Yes, StorageProperties::EfficientGet::Yes, StorageProperties::ConcurrentWriteCompact::No); return rv; } bool CouchKVStore::commit() { if (isReadOnly()) { throw std::logic_error("CouchKVStore::commit: Not valid on a read-only " "object."); } if (intransaction) { if (commit2couchstore()) { intransaction = false; } } return !intransaction; } void CouchKVStore::addStats(const std::string &prefix, ADD_STAT add_stat, const void *c) { const char *prefix_str = prefix.c_str(); /* stats for both read-only and read-write threads */ addStat(prefix_str, "backend_type", "couchstore", add_stat, c); addStat(prefix_str, "open", st.numOpen, add_stat, c); addStat(prefix_str, "close", st.numClose, add_stat, c); addStat(prefix_str, "readTime", st.readTimeHisto, add_stat, c); addStat(prefix_str, "readSize", st.readSizeHisto, add_stat, c); addStat(prefix_str, "numLoadedVb", st.numLoadedVb, add_stat, c); // failure stats addStat(prefix_str, "failure_open", st.numOpenFailure, add_stat, c); addStat(prefix_str, "failure_get", st.numGetFailure, add_stat, c); if (!isReadOnly()) { addStat(prefix_str, "failure_set", st.numSetFailure, add_stat, c); addStat(prefix_str, "failure_del", st.numDelFailure, add_stat, c); addStat(prefix_str, "failure_vbset", st.numVbSetFailure, add_stat, c); addStat(prefix_str, "lastCommDocs", st.docsCommitted, add_stat, c); } addStat(prefix_str, "io_num_read", st.io_num_read, add_stat, c); addStat(prefix_str, "io_num_write", st.io_num_write, add_stat, c); addStat(prefix_str, "io_read_bytes", st.io_read_bytes, add_stat, c); addStat(prefix_str, "io_write_bytes", st.io_write_bytes, add_stat, c); const size_t read = st.fsStats.totalBytesRead.load() + st.fsStatsCompaction.totalBytesRead.load(); addStat(prefix_str, "io_total_read_bytes", read, add_stat, c); const size_t written = st.fsStats.totalBytesWritten.load() + st.fsStatsCompaction.totalBytesWritten.load(); addStat(prefix_str, "io_total_write_bytes", written, add_stat, c); addStat(prefix_str, "io_compaction_read_bytes", st.fsStatsCompaction.totalBytesRead, add_stat, c); addStat(prefix_str, "io_compaction_write_bytes", st.fsStatsCompaction.totalBytesWritten, add_stat, c); } void CouchKVStore::addTimingStats(const std::string &prefix, ADD_STAT add_stat, const void *c) { if (isReadOnly()) { return; } const char *prefix_str = prefix.c_str(); addStat(prefix_str, "commit", st.commitHisto, add_stat, c); addStat(prefix_str, "compact", st.compactHisto, add_stat, c); addStat(prefix_str, "snapshot", st.snapshotHisto, add_stat, c); addStat(prefix_str, "delete", st.delTimeHisto, add_stat, c); addStat(prefix_str, "save_documents", st.saveDocsHisto, add_stat, c); addStat(prefix_str, "writeTime", st.writeTimeHisto, add_stat, c); addStat(prefix_str, "writeSize", st.writeSizeHisto, add_stat, c); addStat(prefix_str, "bulkSize", st.batchSize, add_stat, c); // Couchstore file ops stats addStat(prefix_str, "fsReadTime", st.fsStats.readTimeHisto, add_stat, c); addStat(prefix_str, "fsWriteTime", st.fsStats.writeTimeHisto, add_stat, c); addStat(prefix_str, "fsSyncTime", st.fsStats.syncTimeHisto, add_stat, c); addStat(prefix_str, "fsReadSize", st.fsStats.readSizeHisto, add_stat, c); addStat(prefix_str, "fsWriteSize", st.fsStats.writeSizeHisto, add_stat, c); addStat(prefix_str, "fsReadSeek", st.fsStats.readSeekHisto, add_stat, c); } bool CouchKVStore::getStat(const char* name, size_t& value) { if (strcmp("io_total_read_bytes", name) == 0) { value = st.fsStats.totalBytesRead.load() + st.fsStatsCompaction.totalBytesRead.load(); return true; } else if (strcmp("io_total_write_bytes", name) == 0) { value = st.fsStats.totalBytesWritten.load() + st.fsStatsCompaction.totalBytesWritten.load(); return true; } else if (strcmp("io_compaction_read_bytes", name) == 0) { value = st.fsStatsCompaction.totalBytesRead; return true; } else if (strcmp("io_compaction_write_bytes", name) == 0) { value = st.fsStatsCompaction.totalBytesWritten; return true; } return false; } template <typename T> void CouchKVStore::addStat(const std::string &prefix, const char *stat, T &val, ADD_STAT add_stat, const void *c) { std::stringstream fullstat; fullstat << prefix << ":" << stat; add_casted_stat(fullstat.str().c_str(), val, add_stat, c); } void CouchKVStore::pendingTasks() { if (isReadOnly()) { throw std::logic_error("CouchKVStore::pendingTasks: Not valid on a " "read-only object."); } if (!pendingFileDeletions.empty()) { std::queue<std::string> queue; pendingFileDeletions.getAll(queue); while (!queue.empty()) { std::string filename_str = queue.front(); if (remove(filename_str.c_str()) == -1) { logger.log(EXTENSION_LOG_WARNING, "Failed to remove file '%s' " "with error code: %d", filename_str.c_str(), errno); if (errno != ENOENT) { pendingFileDeletions.push(filename_str); } } queue.pop(); } } } ScanContext* CouchKVStore::initScanContext(std::shared_ptr<Callback<GetValue> > cb, std::shared_ptr<Callback<CacheLookup> > cl, uint16_t vbid, uint64_t startSeqno, DocumentFilter options, ValueFilter valOptions) { Db *db = NULL; uint64_t rev = dbFileRevMap[vbid]; couchstore_error_t errorCode = openDB(vbid, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errorCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open database, " "name=%s/%" PRIu16 ".couch.%" PRIu64, dbname.c_str(), vbid, rev); remVBucketFromDbFileMap(vbid); return NULL; } DbInfo info; errorCode = couchstore_db_info(db, &info); if (errorCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to read DB info for backfill"); closeDatabaseHandle(db); abort(); } uint64_t count = 0; errorCode = couchstore_changes_count(db, startSeqno, std::numeric_limits<uint64_t>::max(), &count); if (errorCode != COUCHSTORE_SUCCESS) { std::string err("CouchKVStore::initScanContext:Failed to obtain changes " "count with error: " + std::string(couchstore_strerror(errorCode))); closeDatabaseHandle(db); throw std::runtime_error(err); } size_t backfillId = backfillCounter++; LockHolder lh(backfillLock); backfills[backfillId] = db; ScanContext* sctx = new ScanContext(cb, cl, vbid, backfillId, startSeqno, info.last_sequence, options, valOptions, count); sctx->logger = &logger; return sctx; } scan_error_t CouchKVStore::scan(ScanContext* ctx) { if (!ctx) { return scan_failed; } if (ctx->lastReadSeqno == ctx->maxSeqno) { return scan_success; } LockHolder lh(backfillLock); std::map<size_t, Db*>::iterator itr = backfills.find(ctx->scanId); if (itr == backfills.end()) { return scan_failed; } Db* db = itr->second; lh.unlock(); couchstore_docinfos_options options; switch (ctx->docFilter) { case DocumentFilter::NO_DELETES: options = COUCHSTORE_NO_DELETES; break; case DocumentFilter::ALL_ITEMS: options = COUCHSTORE_NO_OPTIONS; break; default: std::string err("CouchKVStore::scan:Illegal document filter!" + std::to_string(static_cast<int>(ctx->docFilter))); throw std::runtime_error(err); } uint64_t start = ctx->startSeqno; if (ctx->lastReadSeqno != 0) { start = ctx->lastReadSeqno + 1; } couchstore_error_t errorCode; errorCode = couchstore_changes_since(db, start, options, recordDbDumpC, static_cast<void*>(ctx)); if (errorCode != COUCHSTORE_SUCCESS) { if (errorCode == COUCHSTORE_ERROR_CANCEL) { return scan_again; } else { logger.log(EXTENSION_LOG_WARNING, "couchstore_changes_since failed, error=%s [%s]", couchstore_strerror(errorCode), couchkvstore_strerrno(db, errorCode).c_str()); remVBucketFromDbFileMap(ctx->vbid); return scan_failed; } } return scan_success; } void CouchKVStore::destroyScanContext(ScanContext* ctx) { if (!ctx) { return; } LockHolder lh(backfillLock); std::map<size_t, Db*>::iterator itr = backfills.find(ctx->scanId); if (itr != backfills.end()) { closeDatabaseHandle(itr->second); backfills.erase(itr); } delete ctx; } DbInfo CouchKVStore::getDbInfo(uint16_t vbid) { Db *db = nullptr; const uint64_t rev = dbFileRevMap.at(vbid); couchstore_error_t errCode = openDB(vbid, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode == COUCHSTORE_SUCCESS) { DbInfo info; errCode = couchstore_db_info(db, &info); closeDatabaseHandle(db); if (errCode == COUCHSTORE_SUCCESS) { return info; } else { throw std::runtime_error("CouchKVStore::getDbInfo: failed " "to read database info for vBucket " + std::to_string(vbid) + " revision " + std::to_string(rev) + " - couchstore returned error: " + couchstore_strerror(errCode)); } } else { // open failed - map couchstore error code to exception. std::errc ec; switch (errCode) { case COUCHSTORE_ERROR_OPEN_FILE: ec = std::errc::no_such_file_or_directory; break; default: ec = std::errc::io_error; break; } throw std::system_error(std::make_error_code(ec), "CouchKVStore::getDbInfo: failed to open database file for " "vBucket = " + std::to_string(vbid) + " rev = " + std::to_string(rev) + " with error:" + couchstore_strerror(errCode)); } } void CouchKVStore::close() { intransaction = false; } uint64_t CouchKVStore::checkNewRevNum(std::string &dbFileName, bool newFile) { uint64_t newrev = 0; std::string nameKey; if (!newFile) { // extract out the file revision number first size_t secondDot = dbFileName.rfind("."); nameKey = dbFileName.substr(0, secondDot); } else { nameKey = dbFileName; } nameKey.append("."); const std::vector<std::string> files = findFilesWithPrefix(nameKey); std::vector<std::string>::const_iterator itor; // found file(s) whoes name has the same key name pair with different // revision number for (itor = files.begin(); itor != files.end(); ++itor) { const std::string &filename = *itor; if (endWithCompact(filename)) { continue; } size_t secondDot = filename.rfind("."); char *ptr = NULL; uint64_t revnum = strtoull(filename.substr(secondDot + 1).c_str(), &ptr, 10); if (newrev < revnum) { newrev = revnum; dbFileName = filename; } } return newrev; } void CouchKVStore::updateDbFileMap(uint16_t vbucketId, uint64_t newFileRev) { if (vbucketId >= numDbFiles) { logger.log(EXTENSION_LOG_WARNING, "Cannot update db file map for an invalid vbucket, " "vbucket id = %d, rev = %" PRIu64, vbucketId, newFileRev); return; } dbFileRevMap[vbucketId] = newFileRev; } couchstore_error_t CouchKVStore::openDB(uint16_t vbucketId, uint64_t fileRev, Db **db, uint64_t options, uint64_t *newFileRev, bool reset, FileOpsInterface* ops) { std::string dbFileName = getDBFileName(dbname, vbucketId, fileRev); if(ops == nullptr) { ops = statCollectingFileOps.get(); } uint64_t newRevNum = fileRev; couchstore_error_t errorCode = COUCHSTORE_SUCCESS; /** * This flag disables IO buffering in couchstore which means * file operations will trigger syscalls immediately. This has * a detrimental impact on performance and is only intended * for testing. */ if(!configuration.getBuffered()) { options |= COUCHSTORE_OPEN_FLAG_UNBUFFERED; } if (reset) { errorCode = couchstore_open_db_ex(dbFileName.c_str(), options, ops, db); if (errorCode == COUCHSTORE_SUCCESS) { newRevNum = 1; updateDbFileMap(vbucketId, fileRev); logger.log(EXTENSION_LOG_INFO, "reset: created new couchstore file, name=%s rev=%" PRIu64, dbFileName.c_str(), fileRev); } else { logger.log(EXTENSION_LOG_WARNING, "reset: creating a new couchstore file, name=%s rev=%" PRIu64 " failed with error=%s", dbFileName.c_str(), fileRev, couchstore_strerror(errorCode)); } } else { if (options & COUCHSTORE_OPEN_FLAG_CREATE) { // first try to open the requested file without the // create option in case it does already exist errorCode = couchstore_open_db_ex(dbFileName.c_str(), 0, ops, db); if (errorCode != COUCHSTORE_SUCCESS) { // open_db failed but still check if the file exists newRevNum = checkNewRevNum(dbFileName); bool fileExists = (newRevNum) ? true : false; if (fileExists) { errorCode = openDB_retry(dbFileName, 0, ops, db, &newRevNum); } else { // requested file doesn't seem to exist, just create one errorCode = couchstore_open_db_ex(dbFileName.c_str(), options, ops, db); if (errorCode == COUCHSTORE_SUCCESS) { newRevNum = 1; updateDbFileMap(vbucketId, fileRev); logger.log(EXTENSION_LOG_INFO, "INFO: created new couch db file, name=%s " "rev=%" PRIu64, dbFileName.c_str(), fileRev); } } } } else { errorCode = openDB_retry(dbFileName, options, ops, db, &newRevNum); } } /* update command statistics */ st.numOpen++; if (errorCode) { st.numOpenFailure++; logger.log(EXTENSION_LOG_WARNING, "couchstore_open_db failed, name=%s" " option=%" PRIX64 " rev=%" PRIu64 " error=%s [%s]", dbFileName.c_str(), options, ((newRevNum > fileRev) ? newRevNum : fileRev), couchstore_strerror(errorCode), cb_strerror().c_str()); } else { if (newRevNum > fileRev) { // new revision number found, update it updateDbFileMap(vbucketId, newRevNum); } } if (newFileRev != NULL) { *newFileRev = (newRevNum > fileRev) ? newRevNum : fileRev; } return errorCode; } couchstore_error_t CouchKVStore::openDB_retry(std::string &dbfile, uint64_t options, FileOpsInterface *ops, Db** db, uint64_t *newFileRev) { int retry = 0; couchstore_error_t errCode = COUCHSTORE_SUCCESS; while (retry < MAX_OPEN_DB_RETRY) { errCode = couchstore_open_db_ex(dbfile.c_str(), options, ops, db); if (errCode == COUCHSTORE_SUCCESS) { return errCode; } logger.log(EXTENSION_LOG_NOTICE, "INFO: couchstore_open_db failed, name=%s options=%" PRIX64 " error=%s [%s], try it again!", dbfile.c_str(), options, couchstore_strerror(errCode), cb_strerror().c_str()); *newFileRev = checkNewRevNum(dbfile); ++retry; if (retry == MAX_OPEN_DB_RETRY - 1 && options == 0 && errCode == COUCHSTORE_ERROR_NO_SUCH_FILE) { options = COUCHSTORE_OPEN_FLAG_CREATE; } } return errCode; } void CouchKVStore::populateFileNameMap(std::vector<std::string> &filenames, std::vector<uint16_t> *vbids) { std::vector<std::string>::iterator fileItr; for (fileItr = filenames.begin(); fileItr != filenames.end(); ++fileItr) { const std::string &filename = *fileItr; size_t secondDot = filename.rfind("."); std::string nameKey = filename.substr(0, secondDot); size_t firstDot = nameKey.rfind("."); #ifdef _MSC_VER size_t firstSlash = nameKey.rfind("\\"); #else size_t firstSlash = nameKey.rfind("/"); #endif std::string revNumStr = filename.substr(secondDot + 1); char *ptr = NULL; uint64_t revNum = strtoull(revNumStr.c_str(), &ptr, 10); std::string vbIdStr = nameKey.substr(firstSlash + 1, (firstDot - firstSlash) - 1); if (allDigit(vbIdStr)) { int vbId = atoi(vbIdStr.c_str()); if (vbids) { vbids->push_back(static_cast<uint16_t>(vbId)); } uint64_t old_rev_num = dbFileRevMap[vbId]; if (old_rev_num == revNum) { continue; } else if (old_rev_num < revNum) { // stale revision found dbFileRevMap[vbId] = revNum; } else { // stale file found (revision id has rolled over) old_rev_num = revNum; } std::stringstream old_file; old_file << dbname << "/" << vbId << ".couch." << old_rev_num; if (access(old_file.str().c_str(), F_OK) == 0) { if (!isReadOnly()) { if (remove(old_file.str().c_str()) == 0) { logger.log(EXTENSION_LOG_INFO, "Removed stale file '%s'", old_file.str().c_str()); } else { logger.log(EXTENSION_LOG_WARNING, "Warning: Failed to remove the stale file '%s': %s", old_file.str().c_str(), cb_strerror().c_str()); } } else { logger.log(EXTENSION_LOG_WARNING, "A read-only instance of the underlying store " "was not allowed to delete a stale file: %s!", old_file.str().c_str()); } } } else { // skip non-vbucket database file, master.couch etc logger.log(EXTENSION_LOG_DEBUG, "Non-vbucket database file, %s, skip adding " "to CouchKVStore dbFileMap\n", filename.c_str()); } } } couchstore_error_t CouchKVStore::fetchDoc(Db *db, DocInfo *docinfo, GetValue &docValue, uint16_t vbId, bool metaOnly, bool fetchDelete) { couchstore_error_t errCode = COUCHSTORE_SUCCESS; sized_buf metadata = docinfo->rev_meta; uint32_t itemFlags; uint64_t cas; time_t exptime; uint8_t ext_meta[EXT_META_LEN]; uint8_t ext_len; uint8_t conf_res_mode = 0; if (metadata.size < DEFAULT_META_LEN) { throw std::invalid_argument("CouchKVStore::fetchDoc: " "docValue->rev_meta.size (which is " + std::to_string(metadata.size) + ") is less than DEFAULT_META_LEN (which is " + std::to_string(DEFAULT_META_LEN) + ")"); } if (metadata.size == DEFAULT_META_LEN) { memcpy(&cas, (metadata.buf), 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemFlags, (metadata.buf) + 12, 4); ext_len = 0; } else { //metadata.size => 19, FLEX_META_CODE at offset 16 memcpy(&cas, (metadata.buf), 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemFlags, (metadata.buf) + 12, 4); memcpy(ext_meta, (metadata.buf) + DEFAULT_META_LEN + FLEX_DATA_OFFSET, EXT_META_LEN); memcpy(&conf_res_mode, (metadata.buf) + DEFAULT_META_LEN + FLEX_DATA_OFFSET + EXT_META_LEN, CONFLICT_RES_META_LEN); ext_len = EXT_META_LEN; } cas = ntohll(cas); exptime = ntohl(exptime); if (metaOnly || (fetchDelete && docinfo->deleted)) { Item *it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, itemFlags, (time_t)exptime, NULL, docinfo->size, ext_meta, ext_len, cas, docinfo->db_seq, vbId); if (docinfo->deleted) { it->setDeleted(); } it->setConflictResMode( static_cast<enum conflict_resolution_mode>(conf_res_mode)); it->setRevSeqno(docinfo->rev_seq); docValue = GetValue(it); // update ep-engine IO stats ++st.io_num_read; st.io_read_bytes.fetch_add(docinfo->id.size); } else { Doc *doc = NULL; errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, DECOMPRESS_DOC_BODIES); if (errCode == COUCHSTORE_SUCCESS) { if (docinfo->deleted) { // do not read a doc that is marked deleted, just return the // error code as not found but still release the document body. errCode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } else { if (doc == nullptr) { throw std::logic_error("CouchKVStore::fetchDoc: doc is NULL"); } if (doc->id.size > UINT16_MAX) { throw std::logic_error("CouchKVStore::fetchDoc: " "doc->id.size (which is" + std::to_string(doc->id.size) + ") is greater than " + std::to_string(UINT16_MAX)); } size_t valuelen = doc->data.size; void *valuePtr = doc->data.buf; /** * Set Datatype correctly if data is being * read from couch files where datatype is * not supported. */ if (metadata.size == DEFAULT_META_LEN) { ext_len = EXT_META_LEN; ext_meta[0] = determine_datatype((const unsigned char*)valuePtr, valuelen); } Item *it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, itemFlags, (time_t)exptime, valuePtr, valuelen, ext_meta, ext_len, cas, docinfo->db_seq, vbId, docinfo->rev_seq); it->setConflictResMode( static_cast<enum conflict_resolution_mode>(conf_res_mode)); docValue = GetValue(it); // update ep-engine IO stats ++st.io_num_read; st.io_read_bytes.fetch_add(docinfo->id.size + valuelen); } couchstore_free_document(doc); } } return errCode; } int CouchKVStore::recordDbDump(Db *db, DocInfo *docinfo, void *ctx) { ScanContext* sctx = static_cast<ScanContext*>(ctx); std::shared_ptr<Callback<GetValue> > cb = sctx->callback; std::shared_ptr<Callback<CacheLookup> > cl = sctx->lookup; Doc *doc = NULL; void *valuePtr = NULL; size_t valuelen = 0; uint64_t byseqno = docinfo->db_seq; sized_buf metadata = docinfo->rev_meta; uint16_t vbucketId = sctx->vbid; sized_buf key = docinfo->id; uint32_t itemflags; uint64_t cas; uint32_t exptime; uint8_t ext_meta[EXT_META_LEN] = {0}; uint8_t ext_len; uint8_t conf_res_mode = 0; if (key.size > UINT16_MAX) { throw std::invalid_argument("CouchKVStore::recordDbDump: " "docinfo->id.size (which is " + std::to_string(key.size) + ") is greater than " + std::to_string(UINT16_MAX)); } if (metadata.size < DEFAULT_META_LEN) { throw std::invalid_argument("CouchKVStore::recordDbDump: " "docinfo->rev_meta.size (which is " + std::to_string(key.size) + ") is less than " + std::to_string(DEFAULT_META_LEN)); } std::string docKey(docinfo->id.buf, docinfo->id.size); CacheLookup lookup(docKey, byseqno, vbucketId); cl->callback(lookup); if (cl->getStatus() == ENGINE_KEY_EEXISTS) { sctx->lastReadSeqno = byseqno; return COUCHSTORE_SUCCESS; } else if (cl->getStatus() == ENGINE_ENOMEM) { return COUCHSTORE_ERROR_CANCEL; } if (metadata.size == DEFAULT_META_LEN) { memcpy(&cas, (metadata.buf), 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemflags, (metadata.buf) + 12, 4); ext_len = 0; } else { //metadata.size > 16, FLEX_META_CODE at offset 16 memcpy(&cas, (metadata.buf), 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemflags, (metadata.buf) + 12, 4); memcpy(ext_meta, (metadata.buf) + DEFAULT_META_LEN + FLEX_DATA_OFFSET, EXT_META_LEN); memcpy(&conf_res_mode, (metadata.buf) + DEFAULT_META_LEN + FLEX_DATA_OFFSET + EXT_META_LEN, CONFLICT_RES_META_LEN); ext_len = EXT_META_LEN; } exptime = ntohl(exptime); cas = ntohll(cas); if (sctx->valFilter != ValueFilter::KEYS_ONLY && !docinfo->deleted) { couchstore_error_t errCode; bool expectCompressed = false; /** * If couch files do not support datatype or no special * request is made to retrieve compressed documents as is, * then DECOMPRESS the document. */ couchstore_open_options openOptions = 0; if (metadata.size == DEFAULT_META_LEN || sctx->valFilter == ValueFilter::VALUES_DECOMPRESSED) { openOptions = DECOMPRESS_DOC_BODIES; } else { // => sctx->valFilter == ValueFilter::VALUES_COMPRESSED expectCompressed = true; } errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, openOptions); if (errCode == COUCHSTORE_SUCCESS) { if (doc->data.size) { valuelen = doc->data.size; valuePtr = doc->data.buf; /** * Set Datatype correctly if data is being * read from couch files where datatype is * not supported. */ if (metadata.size == DEFAULT_META_LEN) { ext_len = EXT_META_LEN; ext_meta[0] = determine_datatype((const unsigned char*)valuePtr, valuelen); } if (expectCompressed) { /** * If a compressed document was retrieved as is, * update the datatype of the document. */ uint8_t datatype = ext_meta[0]; if (datatype == PROTOCOL_BINARY_DATATYPE_JSON) { ext_meta[0] = PROTOCOL_BINARY_DATATYPE_COMPRESSED_JSON; } else if (datatype == PROTOCOL_BINARY_RAW_BYTES) { ext_meta[0] = PROTOCOL_BINARY_DATATYPE_COMPRESSED; } } } } else { sctx->logger->log(EXTENSION_LOG_WARNING, "Failed to retrieve key value from database " "database, vBucket=%d key=%s error=%s [%s]\n", vbucketId, key.buf, couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); return COUCHSTORE_SUCCESS; } } Item *it = new Item((void *)key.buf, key.size, itemflags, (time_t)exptime, valuePtr, valuelen, ext_meta, ext_len, cas, docinfo->db_seq, // return seq number being persisted on disk vbucketId, docinfo->rev_seq); if (docinfo->deleted) { it->setDeleted(); } it->setConflictResMode( static_cast<enum conflict_resolution_mode>(conf_res_mode)); bool onlyKeys = (sctx->valFilter == ValueFilter::KEYS_ONLY) ? true : false; GetValue rv(it, ENGINE_SUCCESS, -1, onlyKeys); cb->callback(rv); couchstore_free_document(doc); if (cb->getStatus() == ENGINE_ENOMEM) { return COUCHSTORE_ERROR_CANCEL; } sctx->lastReadSeqno = byseqno; return COUCHSTORE_SUCCESS; } bool CouchKVStore::commit2couchstore() { bool success = true; size_t pendingCommitCnt = pendingReqsQ.size(); if (pendingCommitCnt == 0) { return success; } Doc **docs = new Doc *[pendingCommitCnt]; DocInfo **docinfos = new DocInfo *[pendingCommitCnt]; if (pendingReqsQ[0] == nullptr) { throw std::logic_error("CouchKVStore::commit2couchstore: " "pendingReqsQ[0] is NULL"); } uint16_t vbucket2flush = pendingReqsQ[0]->getVBucketId(); uint64_t fileRev = pendingReqsQ[0]->getRevNum(); for (size_t i = 0; i < pendingCommitCnt; ++i) { CouchRequest *req = pendingReqsQ[i]; if (req == nullptr) { throw std::logic_error("CouchKVStore::commit2couchstore: " "pendingReqsQ[" + std::to_string(i) + "] is NULL"); } docs[i] = (Doc *)req->getDbDoc(); docinfos[i] = req->getDbDocInfo(); if (vbucket2flush != req->getVBucketId()) { throw std::logic_error( "CouchKVStore::commit2couchstore: " "mismatch between vbucket2flush (which is " + std::to_string(vbucket2flush) + ") and pendingReqsQ[" + std::to_string(i) + "] (which is " + std::to_string(req->getVBucketId()) + ")"); } } kvstats_ctx kvctx; kvctx.vbucket = vbucket2flush; // flush all couchstore_error_t errCode = saveDocs(vbucket2flush, fileRev, docs, docinfos, pendingCommitCnt, kvctx); if (errCode) { logger.log(EXTENSION_LOG_WARNING, "Commit failed, cannot save CouchDB docs " "for vbucket = %d rev = %" PRIu64, vbucket2flush, fileRev); } commitCallback(pendingReqsQ, kvctx, errCode); // clean up for (size_t i = 0; i < pendingCommitCnt; ++i) { delete pendingReqsQ[i]; } pendingReqsQ.clear(); delete [] docs; delete [] docinfos; return success; } static int readDocInfos(Db *db, DocInfo *docinfo, void *ctx) { if (ctx == nullptr) { throw std::invalid_argument("readDocInfos: ctx must be non-NULL"); } kvstats_ctx *cbCtx = static_cast<kvstats_ctx *>(ctx); if(docinfo) { // An item exists in the VB DB file. if (!docinfo->deleted) { std::string key(docinfo->id.buf, docinfo->id.size); std::unordered_map<std::string, kstat_entry_t>::iterator itr = cbCtx->keyStats.find(key); if (itr != cbCtx->keyStats.end()) { itr->second.first = true; } } } return 0; } couchstore_error_t CouchKVStore::saveDocs(uint16_t vbid, uint64_t rev, Doc **docs, DocInfo **docinfos, size_t docCount, kvstats_ctx &kvctx) { couchstore_error_t errCode; uint64_t fileRev = rev; DbInfo info; if (rev == 0) { throw std::invalid_argument("CouchKVStore::saveDocs: rev must be non-zero"); } Db *db = NULL; uint64_t newFileRev; errCode = openDB(vbid, fileRev, &db, 0, &newFileRev); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open database, vbucketId = %d " "fileRev = %" PRIu64 " numDocs = %" PRIu64, vbid, fileRev, uint64_t(docCount)); return errCode; } else { vbucket_state *state = cachedVBStates[vbid]; if (state == nullptr) { throw std::logic_error( "CouchKVStore::saveDocs: cachedVBStates[" + std::to_string(vbid) + "] is NULL"); } uint64_t maxDBSeqno = 0; sized_buf *ids = new sized_buf[docCount]; for (size_t idx = 0; idx < docCount; idx++) { ids[idx] = docinfos[idx]->id; maxDBSeqno = std::max(maxDBSeqno, docinfos[idx]->db_seq); std::string key(ids[idx].buf, ids[idx].size); kvctx.keyStats[key] = std::make_pair(false, !docinfos[idx]->deleted); } couchstore_docinfos_by_id(db, ids, (unsigned) docCount, 0, readDocInfos, &kvctx); delete[] ids; hrtime_t cs_begin = gethrtime(); uint64_t flags = COMPRESS_DOC_BODIES | COUCHSTORE_SEQUENCE_AS_IS; errCode = couchstore_save_documents(db, docs, docinfos, (unsigned) docCount, flags); st.saveDocsHisto.add((gethrtime() - cs_begin) / 1000); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to save docs to database, " "numDocs = %" PRIu64 " error=%s [%s]\n", uint64_t(docCount), couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); closeDatabaseHandle(db); return errCode; } errCode = saveVBState(db, *state); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to save local docs to " "database, error=%s [%s]", couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); closeDatabaseHandle(db); return errCode; } cs_begin = gethrtime(); errCode = couchstore_commit(db); st.commitHisto.add((gethrtime() - cs_begin) / 1000); if (errCode) { logger.log(EXTENSION_LOG_WARNING, "couchstore_commit failed, error=%s [%s]", couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); closeDatabaseHandle(db); return errCode; } st.batchSize.add(docCount); // retrieve storage system stats for file fragmentation computation couchstore_db_info(db, &info); cachedSpaceUsed[vbid] = info.space_used; cachedFileSize[vbid] = info.file_size; cachedDeleteCount[vbid] = info.deleted_count; cachedDocCount[vbid] = info.doc_count; if (maxDBSeqno != info.last_sequence) { logger.log(EXTENSION_LOG_WARNING, "Seqno in db header (%" PRIu64 ")" " is not matched with what was persisted (%" PRIu64 ")" " for vbucket %d", info.last_sequence, maxDBSeqno, vbid); } state->highSeqno = info.last_sequence; closeDatabaseHandle(db); } /* update stat */ if(errCode == COUCHSTORE_SUCCESS) { st.docsCommitted = docCount; } return errCode; } void CouchKVStore::remVBucketFromDbFileMap(uint16_t vbucketId) { if (vbucketId >= numDbFiles) { logger.log(EXTENSION_LOG_WARNING, "Cannot remove db file map entry for an invalid vbucket, " "vbucket id = %d\n", vbucketId); return; } // just reset revision number of the requested vbucket dbFileRevMap[vbucketId] = 1; } void CouchKVStore::commitCallback(std::vector<CouchRequest *> &committedReqs, kvstats_ctx &kvctx, couchstore_error_t errCode) { size_t commitSize = committedReqs.size(); for (size_t index = 0; index < commitSize; index++) { size_t dataSize = committedReqs[index]->getNBytes(); size_t keySize = committedReqs[index]->getKey().length(); /* update ep stats */ ++st.io_num_write; st.io_write_bytes.fetch_add(keySize + dataSize); if (committedReqs[index]->isDelete()) { int rv = getMutationStatus(errCode); if (rv != -1) { const std::string &key = committedReqs[index]->getKey(); if (kvctx.keyStats[key].first) { rv = 1; // Deletion is for an existing item on DB file. } else { rv = 0; // Deletion is for a non-existing item on DB file. } } if (errCode) { ++st.numDelFailure; } else { st.delTimeHisto.add(committedReqs[index]->getDelta() / 1000); } committedReqs[index]->getDelCallback()->callback(rv); } else { int rv = getMutationStatus(errCode); const std::string &key = committedReqs[index]->getKey(); bool insertion = !kvctx.keyStats[key].first; if (errCode) { ++st.numSetFailure; } else { st.writeTimeHisto.add(committedReqs[index]->getDelta() / 1000); st.writeSizeHisto.add(dataSize + keySize); } mutation_result p(rv, insertion); committedReqs[index]->getSetCallback()->callback(p); } } } ENGINE_ERROR_CODE CouchKVStore::readVBState(Db *db, uint16_t vbId) { sized_buf id; LocalDoc *ldoc = NULL; couchstore_error_t errCode = COUCHSTORE_SUCCESS; vbucket_state_t state = vbucket_state_dead; uint64_t checkpointId = 0; uint64_t maxDeletedSeqno = 0; int64_t highSeqno = 0; std::string failovers; uint64_t purgeSeqno = 0; uint64_t lastSnapStart = 0; uint64_t lastSnapEnd = 0; uint64_t maxCas = 0; int64_t driftCounter = INITIAL_DRIFT; DbInfo info; errCode = couchstore_db_info(db, &info); if (errCode == COUCHSTORE_SUCCESS) { highSeqno = info.last_sequence; purgeSeqno = info.purge_seq; } else { logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::readVBState:Failed to read database info " "for vbucket: %d with error: %s", vbId, couchstore_strerror(errCode)); return couchErr2EngineErr(errCode); } id.buf = (char *)"_local/vbstate"; id.size = sizeof("_local/vbstate") - 1; errCode = couchstore_open_local_document(db, (void *)id.buf, id.size, &ldoc); if (errCode != COUCHSTORE_SUCCESS) { if (errCode == COUCHSTORE_ERROR_DOC_NOT_FOUND) { logger.log(EXTENSION_LOG_NOTICE, "CouchKVStore::readVBState: '_local/vbstate' not found " "for vBucket: %d", vbId); } else { logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::readVBState: Failed to " "retrieve stat info for vBucket: %d with error: %s", vbId, couchstore_strerror(errCode)); } } else { const std::string statjson(ldoc->json.buf, ldoc->json.size); cJSON *jsonObj = cJSON_Parse(statjson.c_str()); if (!jsonObj) { couchstore_free_local_document(ldoc); logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::readVBState: Failed to " "parse the vbstat json doc for vbucket %d: %s", vbId , statjson.c_str()); return couchErr2EngineErr(errCode); } const std::string vb_state = getJSONObjString( cJSON_GetObjectItem(jsonObj, "state")); const std::string checkpoint_id = getJSONObjString( cJSON_GetObjectItem(jsonObj,"checkpoint_id")); const std::string max_deleted_seqno = getJSONObjString( cJSON_GetObjectItem(jsonObj, "max_deleted_seqno")); const std::string snapStart = getJSONObjString( cJSON_GetObjectItem(jsonObj, "snap_start")); const std::string snapEnd = getJSONObjString( cJSON_GetObjectItem(jsonObj, "snap_end")); const std::string maxCasValue = getJSONObjString( cJSON_GetObjectItem(jsonObj, "max_cas")); const std::string driftCount = getJSONObjString( cJSON_GetObjectItem(jsonObj, "drift_counter")); cJSON *failover_json = cJSON_GetObjectItem(jsonObj, "failover_table"); if (vb_state.compare("") == 0 || checkpoint_id.compare("") == 0 || max_deleted_seqno.compare("") == 0) { logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::readVBState: State" " JSON doc for vbucket: %d is in the wrong format: %s, " "vb state: %s, checkpoint id: %s and max deleted seqno: %s", vbId, statjson.c_str(), vb_state.c_str(), checkpoint_id.c_str(), max_deleted_seqno.c_str()); } else { state = VBucket::fromString(vb_state.c_str()); parseUint64(max_deleted_seqno.c_str(), &maxDeletedSeqno); parseUint64(checkpoint_id.c_str(), &checkpointId); if (snapStart.compare("") == 0) { lastSnapStart = highSeqno; } else { parseUint64(snapStart.c_str(), &lastSnapStart); } if (snapEnd.compare("") == 0) { lastSnapEnd = highSeqno; } else { parseUint64(snapEnd.c_str(), &lastSnapEnd); } if (maxCasValue.compare("") != 0) { parseUint64(maxCasValue.c_str(), &maxCas); // MB-17517: If the maxCas on disk was invalid then don't use it - // instead rebuild from the items we load from disk (i.e. as per // an upgrade from an earlier version). if (maxCas == static_cast<uint64_t>(-1)) { logger.log(EXTENSION_LOG_WARNING, "Invalid max_cas (0x%" PRIx64 ") read from '%s' " "for vbucket %" PRIu16 ". Resetting max_cas to " "zero.", maxCas, id.buf, vbId); maxCas = 0; } } if (driftCount.compare("") != 0) { parseInt64(driftCount.c_str(), &driftCounter); } if (failover_json) { char* json = cJSON_PrintUnformatted(failover_json); failovers.assign(json); free(json); } } cJSON_Delete(jsonObj); couchstore_free_local_document(ldoc); } delete cachedVBStates[vbId]; cachedVBStates[vbId] = new vbucket_state(state, checkpointId, maxDeletedSeqno, highSeqno, purgeSeqno, lastSnapStart, lastSnapEnd, maxCas, driftCounter, failovers); return couchErr2EngineErr(errCode); } couchstore_error_t CouchKVStore::saveVBState(Db *db, vbucket_state &vbState) { std::stringstream jsonState; jsonState << "{\"state\": \"" << VBucket::toString(vbState.state) << "\"" << ",\"checkpoint_id\": \"" << vbState.checkpointId << "\"" << ",\"max_deleted_seqno\": \"" << vbState.maxDeletedSeqno << "\"" << ",\"failover_table\": " << vbState.failovers << ",\"snap_start\": \"" << vbState.lastSnapStart << "\"" << ",\"snap_end\": \"" << vbState.lastSnapEnd << "\"" << ",\"max_cas\": \"" << vbState.maxCas << "\"" << ",\"drift_counter\": \"" << vbState.driftCounter << "\"" << "}"; LocalDoc lDoc; lDoc.id.buf = (char *)"_local/vbstate"; lDoc.id.size = sizeof("_local/vbstate") - 1; std::string state = jsonState.str(); lDoc.json.buf = (char *)state.c_str(); lDoc.json.size = state.size(); lDoc.deleted = 0; couchstore_error_t errCode = couchstore_save_local_document(db, &lDoc); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "couchstore_save_local_document failed " "error=%s [%s]\n", couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); } return errCode; } int CouchKVStore::getMultiCb(Db *db, DocInfo *docinfo, void *ctx) { if (docinfo == nullptr) { throw std::invalid_argument("CouchKVStore::getMultiCb: docinfo " "must be non-NULL"); } if (ctx == nullptr) { throw std::invalid_argument("CouchKVStore::getMultiCb: ctx must " "be non-NULL"); } std::string keyStr(docinfo->id.buf, docinfo->id.size); GetMultiCbCtx *cbCtx = static_cast<GetMultiCbCtx *>(ctx); CouchKVStoreStats &st = cbCtx->cks.getCKVStoreStat(); vb_bgfetch_queue_t::iterator qitr = cbCtx->fetches.find(keyStr); if (qitr == cbCtx->fetches.end()) { // this could be a serious race condition in couchstore, // log a warning message and continue cbCtx->cks.logger.log(EXTENSION_LOG_WARNING, "Couchstore returned invalid docinfo, no pending " "bgfetch has been issued for key = %s\n", keyStr.c_str()); return 0; } vb_bgfetch_item_ctx_t& bg_itm_ctx = (*qitr).second; bool meta_only = bg_itm_ctx.isMetaOnly; GetValue returnVal; couchstore_error_t errCode = cbCtx->cks.fetchDoc(db, docinfo, returnVal, cbCtx->vbId, meta_only); if (errCode != COUCHSTORE_SUCCESS && !meta_only) { cbCtx->cks.logger.log(EXTENSION_LOG_WARNING, "Failed to fetch data from database, vBucket=%d " "key=%s error=%s [%s]", cbCtx->vbId, keyStr.c_str(), couchstore_strerror(errCode), couchkvstore_strerrno(db, errCode).c_str()); st.numGetFailure++; } returnVal.setStatus(cbCtx->cks.couchErr2EngineErr(errCode)); std::list<VBucketBGFetchItem *> &fetches = bg_itm_ctx.bgfetched_list; std::list<VBucketBGFetchItem *>::iterator itr = fetches.begin(); bool return_val_ownership_transferred = false; for (itr = fetches.begin(); itr != fetches.end(); ++itr) { return_val_ownership_transferred = true; // populate return value for remaining fetch items with the // same seqid (*itr)->value = returnVal; st.readTimeHisto.add((gethrtime() - (*itr)->initTime) / 1000); if (errCode == COUCHSTORE_SUCCESS) { st.readSizeHisto.add(returnVal.getValue()->getNKey() + returnVal.getValue()->getNBytes()); } } if (!return_val_ownership_transferred) { cbCtx->cks.logger.log(EXTENSION_LOG_WARNING, "CouchKVStore::getMultiCb called with zero" "items in bgfetched_list, vBucket=%d key=%s", cbCtx->vbId, keyStr.c_str()); delete returnVal.getValue(); } return 0; } void CouchKVStore::closeDatabaseHandle(Db *db) { couchstore_error_t ret = couchstore_close_file(db); if (ret != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "couchstore_close_file failed, error=%s [%s]", couchstore_strerror(ret), couchkvstore_strerrno(db, ret).c_str()); } ret = couchstore_free_db(db); if (ret != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "couchstore_free_db failed, error=%s [%s]", couchstore_strerror(ret), couchkvstore_strerrno(nullptr, ret).c_str()); } st.numClose++; } ENGINE_ERROR_CODE CouchKVStore::couchErr2EngineErr(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return ENGINE_SUCCESS; case COUCHSTORE_ERROR_ALLOC_FAIL: return ENGINE_ENOMEM; case COUCHSTORE_ERROR_DOC_NOT_FOUND: return ENGINE_KEY_ENOENT; case COUCHSTORE_ERROR_NO_SUCH_FILE: case COUCHSTORE_ERROR_NO_HEADER: default: // same as the general error return code of // EventuallyPersistentStore::getInternal return ENGINE_TMPFAIL; } } size_t CouchKVStore::getNumPersistedDeletes(uint16_t vbid) { size_t delCount = cachedDeleteCount[vbid]; if (delCount != (size_t) -1) { return delCount; } Db *db = NULL; uint64_t rev = dbFileRevMap[vbid]; couchstore_error_t errCode = openDB(vbid, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode == COUCHSTORE_SUCCESS) { DbInfo info; errCode = couchstore_db_info(db, &info); if (errCode == COUCHSTORE_SUCCESS) { cachedDeleteCount[vbid] = info.deleted_count; closeDatabaseHandle(db); return info.deleted_count; } else { throw std::runtime_error("CouchKVStore::getNumPersistedDeletes:" "Failed to read database info for vBucket = " + std::to_string(vbid) + " rev = " + std::to_string(rev) + " with error:" + couchstore_strerror(errCode)); } closeDatabaseHandle(db); } else { // open failed - map couchstore error code to exception. std::errc ec; switch (errCode) { case COUCHSTORE_ERROR_OPEN_FILE: ec = std::errc::no_such_file_or_directory; break; default: ec = std::errc::io_error; break; } throw std::system_error(std::make_error_code(ec), "CouchKVStore::getNumPersistedDeletes:" "Failed to open database file for vBucket = " + std::to_string(vbid) + " rev = " + std::to_string(rev) + " with error:" + couchstore_strerror(errCode)); } return 0; } DBFileInfo CouchKVStore::getDbFileInfo(uint16_t vbid) { DbInfo info = getDbInfo(vbid); return DBFileInfo{info.file_size, info.space_used}; } DBFileInfo CouchKVStore::getAggrDbFileInfo() { DBFileInfo kvsFileInfo; /** * Iterate over all the vbuckets to get the total. * If the vbucket is dead, then its value would * be zero. */ for (uint16_t vbid = 0; vbid < numDbFiles; vbid++) { kvsFileInfo.fileSize += cachedFileSize[vbid].load(); kvsFileInfo.spaceUsed += cachedSpaceUsed[vbid].load(); } return kvsFileInfo; } size_t CouchKVStore::getNumItems(uint16_t vbid, uint64_t min_seq, uint64_t max_seq) { Db *db = NULL; uint64_t count = 0; uint64_t rev = dbFileRevMap[vbid]; couchstore_error_t errCode = openDB(vbid, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode == COUCHSTORE_SUCCESS) { errCode = couchstore_changes_count(db, min_seq, max_seq, &count); if (errCode != COUCHSTORE_SUCCESS) { throw std::runtime_error("CouchKVStore::getNumItems: Failed to " "get changes count for vBucket = " + std::to_string(vbid) + " rev = " + std::to_string(rev) + " with error:" + couchstore_strerror(errCode)); } closeDatabaseHandle(db); } else { throw std::invalid_argument("CouchKVStore::getNumItems: Failed to " "open database file for vBucket = " + std::to_string(vbid) + " rev = " + std::to_string(rev) + " with error:" + couchstore_strerror(errCode)); } return count; } size_t CouchKVStore::getItemCount(uint16_t vbid) { if (!isReadOnly()) { return cachedDocCount.at(vbid); } return getDbInfo(vbid).doc_count; } RollbackResult CouchKVStore::rollback(uint16_t vbid, uint64_t rollbackSeqno, std::shared_ptr<RollbackCB> cb) { Db *db = NULL; DbInfo info; uint64_t fileRev = dbFileRevMap[vbid]; std::stringstream dbFileName; dbFileName << dbname << "/" << vbid << ".couch." << fileRev; couchstore_error_t errCode; errCode = openDB(vbid, fileRev, &db, (uint64_t) COUCHSTORE_OPEN_FLAG_RDONLY); if (errCode == COUCHSTORE_SUCCESS) { errCode = couchstore_db_info(db, &info); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to read DB info, name=%s", dbFileName.str().c_str()); closeDatabaseHandle(db); return RollbackResult(false, 0, 0, 0); } } else { logger.log(EXTENSION_LOG_WARNING, "Failed to open database, name=%s", dbFileName.str().c_str()); return RollbackResult(false, 0, 0, 0); } uint64_t latestSeqno = info.last_sequence; //Count from latest seq no to 0 uint64_t totSeqCount = 0; errCode = couchstore_changes_count(db, 0, latestSeqno, &totSeqCount); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to get changes count for " "rollback vBucket = %d, rev = %" PRIu64 ", error=%s [%s]", vbid, fileRev, couchstore_strerror(errCode), cb_strerror().c_str()); closeDatabaseHandle(db); return RollbackResult(false, 0, 0, 0); } Db *newdb = NULL; errCode = openDB(vbid, fileRev, &newdb, 0); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to open database, name=%s", dbFileName.str().c_str()); closeDatabaseHandle(db); return RollbackResult(false, 0, 0, 0); } while (info.last_sequence > rollbackSeqno) { errCode = couchstore_rewind_db_header(newdb); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to rewind Db pointer " "for couch file with vbid: %u, whose " "lastSeqno: %" PRIu64 ", while trying to roll back " "to seqNo: %" PRIu64 ", error=%s [%s]", vbid, latestSeqno, rollbackSeqno, couchstore_strerror(errCode), cb_strerror().c_str()); //Reset the vbucket and send the entire snapshot, //as a previous header wasn't found. closeDatabaseHandle(db); return RollbackResult(false, 0, 0, 0); } errCode = couchstore_db_info(newdb, &info); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to read DB info, name=%s", dbFileName.str().c_str()); closeDatabaseHandle(db); closeDatabaseHandle(newdb); return RollbackResult(false, 0, 0, 0); } } //Count from latest seq no to rollback seq no uint64_t rollbackSeqCount = 0; errCode = couchstore_changes_count(db, info.last_sequence, latestSeqno, &rollbackSeqCount); if (errCode != COUCHSTORE_SUCCESS) { logger.log(EXTENSION_LOG_WARNING, "Failed to get changes count for " "rollback vBucket = %d, rev = %" PRIu64 ", error=%s [%s]", vbid, fileRev, couchstore_strerror(errCode), cb_strerror().c_str()); closeDatabaseHandle(db); closeDatabaseHandle(newdb); return RollbackResult(false, 0, 0, 0); } if ((totSeqCount / 2) <= rollbackSeqCount) { //doresetVbucket flag set or rollback is greater than 50%, //reset the vbucket and send the entire snapshot closeDatabaseHandle(db); closeDatabaseHandle(newdb); return RollbackResult(false, 0, 0, 0); } cb->setDbHeader(newdb); std::shared_ptr<Callback<CacheLookup> > cl(new NoLookupCallback()); ScanContext* ctx = initScanContext(cb, cl, vbid, info.last_sequence + 1, DocumentFilter::ALL_ITEMS, ValueFilter::KEYS_ONLY); scan_error_t error = scan(ctx); destroyScanContext(ctx); if (error != scan_success) { closeDatabaseHandle(db); closeDatabaseHandle(newdb); return RollbackResult(false, 0, 0, 0); } readVBState(newdb, vbid); cachedDeleteCount[vbid] = info.deleted_count; cachedDocCount[vbid] = info.doc_count; closeDatabaseHandle(db); //Append the rewinded header to the database file, before closing handle errCode = couchstore_commit(newdb); closeDatabaseHandle(newdb); if (errCode != COUCHSTORE_SUCCESS) { return RollbackResult(false, 0, 0, 0); } vbucket_state *vb_state = cachedVBStates[vbid]; return RollbackResult(true, vb_state->highSeqno, vb_state->lastSnapStart, vb_state->lastSnapEnd); } int populateAllKeys(Db *db, DocInfo *docinfo, void *ctx) { AllKeysCtx *allKeysCtx = (AllKeysCtx *)ctx; uint16_t keylen = docinfo->id.size; char *key = docinfo->id.buf; (allKeysCtx->cb)->callback(keylen, key); if (--(allKeysCtx->count) <= 0) { //Only when count met is less than the actual number of entries return COUCHSTORE_ERROR_CANCEL; } return COUCHSTORE_SUCCESS; } ENGINE_ERROR_CODE CouchKVStore::getAllKeys(uint16_t vbid, std::string &start_key, uint32_t count, std::shared_ptr<Callback<uint16_t&, char*&> > cb) { Db *db = NULL; uint64_t rev = dbFileRevMap[vbid]; couchstore_error_t errCode = openDB(vbid, rev, &db, COUCHSTORE_OPEN_FLAG_RDONLY); if(errCode == COUCHSTORE_SUCCESS) { sized_buf ref = {NULL, 0}; ref.buf = (char*) start_key.c_str(); ref.size = start_key.size(); AllKeysCtx ctx(cb, count); errCode = couchstore_all_docs(db, &ref, COUCHSTORE_NO_DELETES, populateAllKeys, static_cast<void *>(&ctx)); closeDatabaseHandle(db); if (errCode == COUCHSTORE_SUCCESS || errCode == COUCHSTORE_ERROR_CANCEL) { return ENGINE_SUCCESS; } else { logger.log(EXTENSION_LOG_WARNING, "couchstore_all_docs failed for " "database file of vbucket = %d rev = %" PRIu64 ", error=%s [%s]", vbid, rev, couchstore_strerror(errCode), cb_strerror().c_str()); } } else { logger.log(EXTENSION_LOG_WARNING, "Failed to open database file for " "vbucket = %d rev = %" PRIu64 ", errCode = %u", vbid, rev, errCode); } return ENGINE_FAILED; } void CouchKVStore::unlinkCouchFile(uint16_t vbucket, uint64_t fRev) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::unlinkCouchFile: Not valid on a " "read-only object."); } char fname[PATH_MAX]; try { checked_snprintf(fname, sizeof(fname), "%s/%d.couch.%" PRIu64, dbname.c_str(), vbucket, fRev); } catch (std::exception& error) { LOG(EXTENSION_LOG_WARNING, "CouchKVStore::unlinkCouchFile: Failed to build filename: %s", fname); return; } if (remove(fname) == -1) { logger.log(EXTENSION_LOG_WARNING, "Failed to remove database file for " "vbucket = %d rev = %" PRIu64 ", errCode = %u", vbucket, fRev, errno); if (errno != ENOENT) { std::string file_str = fname; pendingFileDeletions.push(file_str); } } } void CouchKVStore::removeCompactFile(const std::string &dbname, uint16_t vbid, uint64_t fileRev) { std::string dbfile = getDBFileName(dbname, vbid, fileRev); std::string compact_file = dbfile + ".compact"; if (!isReadOnly()) { removeCompactFile(compact_file); } else { logger.log(EXTENSION_LOG_WARNING, "A read-only instance of the underlying store was not " "allowed to delete a temporary file: %s", compact_file.c_str()); } } void CouchKVStore::removeCompactFile(const std::string &filename) { if (isReadOnly()) { throw std::logic_error("CouchKVStore::removeCompactFile: Not valid on " "a read-only object."); } if (access(filename.c_str(), F_OK) == 0) { if (remove(filename.c_str()) == 0) { logger.log(EXTENSION_LOG_WARNING, "Removed compact file '%s'", filename.c_str()); } else { logger.log(EXTENSION_LOG_WARNING, "Warning: Failed to remove compact file '%s': %s", filename.c_str(), cb_strerror().c_str()); if (errno != ENOENT) { pendingFileDeletions.push(const_cast<std::string &>(filename)); } } } } /* end of couch-kvstore.cc */
37.902194
92
0.563604
[ "object", "vector" ]
192e5dd1d4d4e29027b7811d48169f59d0b46ab6
3,052
hpp
C++
include/hyper/ParallelHelper.hpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
4
2020-06-23T07:39:33.000Z
2021-11-16T02:22:11.000Z
include/hyper/ParallelHelper.hpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
include/hyper/ParallelHelper.hpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
#include "common/runtime/Query.hpp" #include <deque> #include <tbb/tbb.h> static const size_t morselSize = 10000; struct ProcessingResources { std::vector<runtime::Worker> workers; std::unique_ptr<runtime::Query> query; }; inline ProcessingResources initQuery(size_t nrThreads) { ProcessingResources r; r.query = std::make_unique<runtime::Query>(); r.query->result = std::make_unique<runtime::BlockRelation>(); runtime::Barrier b(nrThreads); r.workers.resize(nrThreads); tbb::parallel_for(size_t(0), nrThreads, size_t(1), [&](auto i) { auto& worker = r.workers[i]; // save thread local worker pointer worker.previousWorker = runtime::this_worker; // use this worker resource runtime::this_worker = &worker; r.query->participate(); b.wait(); }); return r; } inline void leaveQuery(size_t nrThreads) { runtime::Barrier b(nrThreads); tbb::parallel_for(size_t(0), nrThreads, size_t(1), [&](auto) { // reset thread local worker pointer runtime::this_worker = runtime::this_worker->previousWorker; b.wait(); }); } #define PARALLEL_SCAN(N, ENTRIES, BLOCK) \ tbb::parallel_for(tbb::blocked_range<size_t>(0, N, morselSize), \ [&](const tbb::blocked_range<size_t>& r) { \ auto& entries = ENTRIES.local(); \ for (auto i = r.begin(), end = r.end(); i != end; ++i) \ BLOCK \ }) template <typename E, typename L> void parallel_scan(size_t n, E& entriesGlobal, L& cb) { tbb::parallel_for(tbb::blocked_range<size_t>(0, n, morselSize), [&](const tbb::blocked_range<size_t>& r) { auto& entries = entriesGlobal.local(); for (auto i = r.begin(), end = r.end(); i != end; ++i) cb(i, entries); }); } #define PARALLEL_SELECT(N, ENTRIES, BLOCK) \ tbb::parallel_reduce( \ tbb::blocked_range<size_t>(0, N, morselSize), 0, \ [&](const tbb::blocked_range<size_t>& r, const size_t& f) { \ auto& entries = ENTRIES.local(); \ auto found = f; \ for (size_t i = r.begin(), end = r.end(); i != end; ++i) BLOCK \ return found; \ }, \ [](const size_t& a, const size_t& b) { return a + b; }) template <typename E, typename HT> void parallel_insert(E& entries, HT& ht) { tbb::parallel_for(entries.range(), [&ht](const auto& r) { for (auto& entries : r) ht.insertAll(entries); }); }
41.243243
80
0.487877
[ "vector" ]
1937d6171f5d9524b9f9d8a2d09e8da183449d13
881
cpp
C++
cpp/godot-cpp/src/gen/VisualShaderNodeUniform.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/VisualShaderNodeUniform.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/VisualShaderNodeUniform.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "VisualShaderNodeUniform.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { VisualShaderNodeUniform::___method_bindings VisualShaderNodeUniform::___mb = {}; void VisualShaderNodeUniform::___init_method_bindings() { ___mb.mb_get_uniform_name = godot::api->godot_method_bind_get_method("VisualShaderNodeUniform", "get_uniform_name"); ___mb.mb_set_uniform_name = godot::api->godot_method_bind_get_method("VisualShaderNodeUniform", "set_uniform_name"); } String VisualShaderNodeUniform::get_uniform_name() const { return ___godot_icall_String(___mb.mb_get_uniform_name, (const Object *) this); } void VisualShaderNodeUniform::set_uniform_name(const String name) { ___godot_icall_void_String(___mb.mb_set_uniform_name, (const Object *) this, name); } }
27.53125
117
0.804767
[ "object" ]
193cad0abd5fdd1600d520b6fd03eb9449e290c8
120,352
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_SESS_BORDER_CTRLR_STATS_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_SESS_BORDER_CTRLR_STATS_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_SESS_BORDER_CTRLR_STATS_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "CISCO_SESS_BORDER_CTRLR_STATS_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace CISCO_SESS_BORDER_CTRLR_STATS_MIB { CISCOSESSBORDERCTRLRSTATSMIB::CISCOSESSBORDERCTRLRSTATSMIB() : csbradiusstatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable>()) , csbrfbillrealmstatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable>()) , csbsipmthdcurrentstatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable>()) , csbsipmthdhistorystatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable>()) , csbsipmthdrccurrentstatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable>()) , csbsipmthdrchistorystatstable(std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable>()) { csbradiusstatstable->parent = this; csbrfbillrealmstatstable->parent = this; csbsipmthdcurrentstatstable->parent = this; csbsipmthdhistorystatstable->parent = this; csbsipmthdrccurrentstatstable->parent = this; csbsipmthdrchistorystatstable->parent = this; yang_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = true; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::~CISCOSESSBORDERCTRLRSTATSMIB() { } bool CISCOSESSBORDERCTRLRSTATSMIB::has_data() const { if (is_presence_container) return true; return (csbradiusstatstable != nullptr && csbradiusstatstable->has_data()) || (csbrfbillrealmstatstable != nullptr && csbrfbillrealmstatstable->has_data()) || (csbsipmthdcurrentstatstable != nullptr && csbsipmthdcurrentstatstable->has_data()) || (csbsipmthdhistorystatstable != nullptr && csbsipmthdhistorystatstable->has_data()) || (csbsipmthdrccurrentstatstable != nullptr && csbsipmthdrccurrentstatstable->has_data()) || (csbsipmthdrchistorystatstable != nullptr && csbsipmthdrchistorystatstable->has_data()); } bool CISCOSESSBORDERCTRLRSTATSMIB::has_operation() const { return is_set(yfilter) || (csbradiusstatstable != nullptr && csbradiusstatstable->has_operation()) || (csbrfbillrealmstatstable != nullptr && csbrfbillrealmstatstable->has_operation()) || (csbsipmthdcurrentstatstable != nullptr && csbsipmthdcurrentstatstable->has_operation()) || (csbsipmthdhistorystatstable != nullptr && csbsipmthdhistorystatstable->has_operation()) || (csbsipmthdrccurrentstatstable != nullptr && csbsipmthdrccurrentstatstable->has_operation()) || (csbsipmthdrchistorystatstable != nullptr && csbsipmthdrchistorystatstable->has_operation()); } std::string CISCOSESSBORDERCTRLRSTATSMIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbRadiusStatsTable") { if(csbradiusstatstable == nullptr) { csbradiusstatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable>(); } return csbradiusstatstable; } if(child_yang_name == "csbRfBillRealmStatsTable") { if(csbrfbillrealmstatstable == nullptr) { csbrfbillrealmstatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable>(); } return csbrfbillrealmstatstable; } if(child_yang_name == "csbSIPMthdCurrentStatsTable") { if(csbsipmthdcurrentstatstable == nullptr) { csbsipmthdcurrentstatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable>(); } return csbsipmthdcurrentstatstable; } if(child_yang_name == "csbSIPMthdHistoryStatsTable") { if(csbsipmthdhistorystatstable == nullptr) { csbsipmthdhistorystatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable>(); } return csbsipmthdhistorystatstable; } if(child_yang_name == "csbSIPMthdRCCurrentStatsTable") { if(csbsipmthdrccurrentstatstable == nullptr) { csbsipmthdrccurrentstatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable>(); } return csbsipmthdrccurrentstatstable; } if(child_yang_name == "csbSIPMthdRCHistoryStatsTable") { if(csbsipmthdrchistorystatstable == nullptr) { csbsipmthdrchistorystatstable = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable>(); } return csbsipmthdrchistorystatstable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(csbradiusstatstable != nullptr) { _children["csbRadiusStatsTable"] = csbradiusstatstable; } if(csbrfbillrealmstatstable != nullptr) { _children["csbRfBillRealmStatsTable"] = csbrfbillrealmstatstable; } if(csbsipmthdcurrentstatstable != nullptr) { _children["csbSIPMthdCurrentStatsTable"] = csbsipmthdcurrentstatstable; } if(csbsipmthdhistorystatstable != nullptr) { _children["csbSIPMthdHistoryStatsTable"] = csbsipmthdhistorystatstable; } if(csbsipmthdrccurrentstatstable != nullptr) { _children["csbSIPMthdRCCurrentStatsTable"] = csbsipmthdrccurrentstatstable; } if(csbsipmthdrchistorystatstable != nullptr) { _children["csbSIPMthdRCHistoryStatsTable"] = csbsipmthdrchistorystatstable; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::clone_ptr() const { return std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB>(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string CISCOSESSBORDERCTRLRSTATSMIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function CISCOSESSBORDERCTRLRSTATSMIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> CISCOSESSBORDERCTRLRSTATSMIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool CISCOSESSBORDERCTRLRSTATSMIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbRadiusStatsTable" || name == "csbRfBillRealmStatsTable" || name == "csbSIPMthdCurrentStatsTable" || name == "csbSIPMthdHistoryStatsTable" || name == "csbSIPMthdRCCurrentStatsTable" || name == "csbSIPMthdRCHistoryStatsTable") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsTable() : csbradiusstatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbradiusstatsentindex"}) { yang_name = "csbRadiusStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::~CsbRadiusStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbradiusstatsentry.len(); index++) { if(csbradiusstatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::has_operation() const { for (std::size_t index=0; index<csbradiusstatsentry.len(); index++) { if(csbradiusstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbRadiusStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbRadiusStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry>(); ent_->parent = this; csbradiusstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbradiusstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbRadiusStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::CsbRadiusStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbradiusstatsentindex{YType::uint32, "csbRadiusStatsEntIndex"}, csbradiusstatsclientname{YType::str, "csbRadiusStatsClientName"}, csbradiusstatsclienttype{YType::enumeration, "csbRadiusStatsClientType"}, csbradiusstatssrvrname{YType::str, "csbRadiusStatsSrvrName"}, csbradiusstatsacsreqs{YType::uint64, "csbRadiusStatsAcsReqs"}, csbradiusstatsacsrtrns{YType::uint64, "csbRadiusStatsAcsRtrns"}, csbradiusstatsacsaccpts{YType::uint64, "csbRadiusStatsAcsAccpts"}, csbradiusstatsacsrejects{YType::uint64, "csbRadiusStatsAcsRejects"}, csbradiusstatsacschalls{YType::uint64, "csbRadiusStatsAcsChalls"}, csbradiusstatsactreqs{YType::uint64, "csbRadiusStatsActReqs"}, csbradiusstatsactretrans{YType::uint64, "csbRadiusStatsActRetrans"}, csbradiusstatsactrsps{YType::uint64, "csbRadiusStatsActRsps"}, csbradiusstatsmalformedrsps{YType::uint64, "csbRadiusStatsMalformedRsps"}, csbradiusstatsbadauths{YType::uint64, "csbRadiusStatsBadAuths"}, csbradiusstatspending{YType::uint32, "csbRadiusStatsPending"}, csbradiusstatstimeouts{YType::uint64, "csbRadiusStatsTimeouts"}, csbradiusstatsunknowntype{YType::uint64, "csbRadiusStatsUnknownType"}, csbradiusstatsdropped{YType::uint64, "csbRadiusStatsDropped"} { yang_name = "csbRadiusStatsEntry"; yang_parent_name = "csbRadiusStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::~CsbRadiusStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbradiusstatsentindex.is_set || csbradiusstatsclientname.is_set || csbradiusstatsclienttype.is_set || csbradiusstatssrvrname.is_set || csbradiusstatsacsreqs.is_set || csbradiusstatsacsrtrns.is_set || csbradiusstatsacsaccpts.is_set || csbradiusstatsacsrejects.is_set || csbradiusstatsacschalls.is_set || csbradiusstatsactreqs.is_set || csbradiusstatsactretrans.is_set || csbradiusstatsactrsps.is_set || csbradiusstatsmalformedrsps.is_set || csbradiusstatsbadauths.is_set || csbradiusstatspending.is_set || csbradiusstatstimeouts.is_set || csbradiusstatsunknowntype.is_set || csbradiusstatsdropped.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbradiusstatsentindex.yfilter) || ydk::is_set(csbradiusstatsclientname.yfilter) || ydk::is_set(csbradiusstatsclienttype.yfilter) || ydk::is_set(csbradiusstatssrvrname.yfilter) || ydk::is_set(csbradiusstatsacsreqs.yfilter) || ydk::is_set(csbradiusstatsacsrtrns.yfilter) || ydk::is_set(csbradiusstatsacsaccpts.yfilter) || ydk::is_set(csbradiusstatsacsrejects.yfilter) || ydk::is_set(csbradiusstatsacschalls.yfilter) || ydk::is_set(csbradiusstatsactreqs.yfilter) || ydk::is_set(csbradiusstatsactretrans.yfilter) || ydk::is_set(csbradiusstatsactrsps.yfilter) || ydk::is_set(csbradiusstatsmalformedrsps.yfilter) || ydk::is_set(csbradiusstatsbadauths.yfilter) || ydk::is_set(csbradiusstatspending.yfilter) || ydk::is_set(csbradiusstatstimeouts.yfilter) || ydk::is_set(csbradiusstatsunknowntype.yfilter) || ydk::is_set(csbradiusstatsdropped.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbRadiusStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbRadiusStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbradiusstatsentindex, "csbRadiusStatsEntIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbradiusstatsentindex.is_set || is_set(csbradiusstatsentindex.yfilter)) leaf_name_data.push_back(csbradiusstatsentindex.get_name_leafdata()); if (csbradiusstatsclientname.is_set || is_set(csbradiusstatsclientname.yfilter)) leaf_name_data.push_back(csbradiusstatsclientname.get_name_leafdata()); if (csbradiusstatsclienttype.is_set || is_set(csbradiusstatsclienttype.yfilter)) leaf_name_data.push_back(csbradiusstatsclienttype.get_name_leafdata()); if (csbradiusstatssrvrname.is_set || is_set(csbradiusstatssrvrname.yfilter)) leaf_name_data.push_back(csbradiusstatssrvrname.get_name_leafdata()); if (csbradiusstatsacsreqs.is_set || is_set(csbradiusstatsacsreqs.yfilter)) leaf_name_data.push_back(csbradiusstatsacsreqs.get_name_leafdata()); if (csbradiusstatsacsrtrns.is_set || is_set(csbradiusstatsacsrtrns.yfilter)) leaf_name_data.push_back(csbradiusstatsacsrtrns.get_name_leafdata()); if (csbradiusstatsacsaccpts.is_set || is_set(csbradiusstatsacsaccpts.yfilter)) leaf_name_data.push_back(csbradiusstatsacsaccpts.get_name_leafdata()); if (csbradiusstatsacsrejects.is_set || is_set(csbradiusstatsacsrejects.yfilter)) leaf_name_data.push_back(csbradiusstatsacsrejects.get_name_leafdata()); if (csbradiusstatsacschalls.is_set || is_set(csbradiusstatsacschalls.yfilter)) leaf_name_data.push_back(csbradiusstatsacschalls.get_name_leafdata()); if (csbradiusstatsactreqs.is_set || is_set(csbradiusstatsactreqs.yfilter)) leaf_name_data.push_back(csbradiusstatsactreqs.get_name_leafdata()); if (csbradiusstatsactretrans.is_set || is_set(csbradiusstatsactretrans.yfilter)) leaf_name_data.push_back(csbradiusstatsactretrans.get_name_leafdata()); if (csbradiusstatsactrsps.is_set || is_set(csbradiusstatsactrsps.yfilter)) leaf_name_data.push_back(csbradiusstatsactrsps.get_name_leafdata()); if (csbradiusstatsmalformedrsps.is_set || is_set(csbradiusstatsmalformedrsps.yfilter)) leaf_name_data.push_back(csbradiusstatsmalformedrsps.get_name_leafdata()); if (csbradiusstatsbadauths.is_set || is_set(csbradiusstatsbadauths.yfilter)) leaf_name_data.push_back(csbradiusstatsbadauths.get_name_leafdata()); if (csbradiusstatspending.is_set || is_set(csbradiusstatspending.yfilter)) leaf_name_data.push_back(csbradiusstatspending.get_name_leafdata()); if (csbradiusstatstimeouts.is_set || is_set(csbradiusstatstimeouts.yfilter)) leaf_name_data.push_back(csbradiusstatstimeouts.get_name_leafdata()); if (csbradiusstatsunknowntype.is_set || is_set(csbradiusstatsunknowntype.yfilter)) leaf_name_data.push_back(csbradiusstatsunknowntype.get_name_leafdata()); if (csbradiusstatsdropped.is_set || is_set(csbradiusstatsdropped.yfilter)) leaf_name_data.push_back(csbradiusstatsdropped.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsEntIndex") { csbradiusstatsentindex = value; csbradiusstatsentindex.value_namespace = name_space; csbradiusstatsentindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsClientName") { csbradiusstatsclientname = value; csbradiusstatsclientname.value_namespace = name_space; csbradiusstatsclientname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsClientType") { csbradiusstatsclienttype = value; csbradiusstatsclienttype.value_namespace = name_space; csbradiusstatsclienttype.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsSrvrName") { csbradiusstatssrvrname = value; csbradiusstatssrvrname.value_namespace = name_space; csbradiusstatssrvrname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsAcsReqs") { csbradiusstatsacsreqs = value; csbradiusstatsacsreqs.value_namespace = name_space; csbradiusstatsacsreqs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsAcsRtrns") { csbradiusstatsacsrtrns = value; csbradiusstatsacsrtrns.value_namespace = name_space; csbradiusstatsacsrtrns.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsAcsAccpts") { csbradiusstatsacsaccpts = value; csbradiusstatsacsaccpts.value_namespace = name_space; csbradiusstatsacsaccpts.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsAcsRejects") { csbradiusstatsacsrejects = value; csbradiusstatsacsrejects.value_namespace = name_space; csbradiusstatsacsrejects.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsAcsChalls") { csbradiusstatsacschalls = value; csbradiusstatsacschalls.value_namespace = name_space; csbradiusstatsacschalls.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsActReqs") { csbradiusstatsactreqs = value; csbradiusstatsactreqs.value_namespace = name_space; csbradiusstatsactreqs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsActRetrans") { csbradiusstatsactretrans = value; csbradiusstatsactretrans.value_namespace = name_space; csbradiusstatsactretrans.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsActRsps") { csbradiusstatsactrsps = value; csbradiusstatsactrsps.value_namespace = name_space; csbradiusstatsactrsps.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsMalformedRsps") { csbradiusstatsmalformedrsps = value; csbradiusstatsmalformedrsps.value_namespace = name_space; csbradiusstatsmalformedrsps.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsBadAuths") { csbradiusstatsbadauths = value; csbradiusstatsbadauths.value_namespace = name_space; csbradiusstatsbadauths.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsPending") { csbradiusstatspending = value; csbradiusstatspending.value_namespace = name_space; csbradiusstatspending.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsTimeouts") { csbradiusstatstimeouts = value; csbradiusstatstimeouts.value_namespace = name_space; csbradiusstatstimeouts.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsUnknownType") { csbradiusstatsunknowntype = value; csbradiusstatsunknowntype.value_namespace = name_space; csbradiusstatsunknowntype.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRadiusStatsDropped") { csbradiusstatsdropped = value; csbradiusstatsdropped.value_namespace = name_space; csbradiusstatsdropped.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbRadiusStatsEntIndex") { csbradiusstatsentindex.yfilter = yfilter; } if(value_path == "csbRadiusStatsClientName") { csbradiusstatsclientname.yfilter = yfilter; } if(value_path == "csbRadiusStatsClientType") { csbradiusstatsclienttype.yfilter = yfilter; } if(value_path == "csbRadiusStatsSrvrName") { csbradiusstatssrvrname.yfilter = yfilter; } if(value_path == "csbRadiusStatsAcsReqs") { csbradiusstatsacsreqs.yfilter = yfilter; } if(value_path == "csbRadiusStatsAcsRtrns") { csbradiusstatsacsrtrns.yfilter = yfilter; } if(value_path == "csbRadiusStatsAcsAccpts") { csbradiusstatsacsaccpts.yfilter = yfilter; } if(value_path == "csbRadiusStatsAcsRejects") { csbradiusstatsacsrejects.yfilter = yfilter; } if(value_path == "csbRadiusStatsAcsChalls") { csbradiusstatsacschalls.yfilter = yfilter; } if(value_path == "csbRadiusStatsActReqs") { csbradiusstatsactreqs.yfilter = yfilter; } if(value_path == "csbRadiusStatsActRetrans") { csbradiusstatsactretrans.yfilter = yfilter; } if(value_path == "csbRadiusStatsActRsps") { csbradiusstatsactrsps.yfilter = yfilter; } if(value_path == "csbRadiusStatsMalformedRsps") { csbradiusstatsmalformedrsps.yfilter = yfilter; } if(value_path == "csbRadiusStatsBadAuths") { csbradiusstatsbadauths.yfilter = yfilter; } if(value_path == "csbRadiusStatsPending") { csbradiusstatspending.yfilter = yfilter; } if(value_path == "csbRadiusStatsTimeouts") { csbradiusstatstimeouts.yfilter = yfilter; } if(value_path == "csbRadiusStatsUnknownType") { csbradiusstatsunknowntype.yfilter = yfilter; } if(value_path == "csbRadiusStatsDropped") { csbradiusstatsdropped.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRadiusStatsTable::CsbRadiusStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbRadiusStatsEntIndex" || name == "csbRadiusStatsClientName" || name == "csbRadiusStatsClientType" || name == "csbRadiusStatsSrvrName" || name == "csbRadiusStatsAcsReqs" || name == "csbRadiusStatsAcsRtrns" || name == "csbRadiusStatsAcsAccpts" || name == "csbRadiusStatsAcsRejects" || name == "csbRadiusStatsAcsChalls" || name == "csbRadiusStatsActReqs" || name == "csbRadiusStatsActRetrans" || name == "csbRadiusStatsActRsps" || name == "csbRadiusStatsMalformedRsps" || name == "csbRadiusStatsBadAuths" || name == "csbRadiusStatsPending" || name == "csbRadiusStatsTimeouts" || name == "csbRadiusStatsUnknownType" || name == "csbRadiusStatsDropped") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsTable() : csbrfbillrealmstatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbrfbillrealmstatsindex", "csbrfbillrealmstatsrealmname"}) { yang_name = "csbRfBillRealmStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::~CsbRfBillRealmStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbrfbillrealmstatsentry.len(); index++) { if(csbrfbillrealmstatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::has_operation() const { for (std::size_t index=0; index<csbrfbillrealmstatsentry.len(); index++) { if(csbrfbillrealmstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbRfBillRealmStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbRfBillRealmStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry>(); ent_->parent = this; csbrfbillrealmstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbrfbillrealmstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbRfBillRealmStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::CsbRfBillRealmStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbrfbillrealmstatsindex{YType::uint32, "csbRfBillRealmStatsIndex"}, csbrfbillrealmstatsrealmname{YType::str, "csbRfBillRealmStatsRealmName"}, csbrfbillrealmstatstotalstartacrs{YType::uint32, "csbRfBillRealmStatsTotalStartAcrs"}, csbrfbillrealmstatstotalinterimacrs{YType::uint32, "csbRfBillRealmStatsTotalInterimAcrs"}, csbrfbillrealmstatstotalstopacrs{YType::uint32, "csbRfBillRealmStatsTotalStopAcrs"}, csbrfbillrealmstatstotaleventacrs{YType::uint32, "csbRfBillRealmStatsTotalEventAcrs"}, csbrfbillrealmstatssuccstartacrs{YType::uint32, "csbRfBillRealmStatsSuccStartAcrs"}, csbrfbillrealmstatssuccinterimacrs{YType::uint32, "csbRfBillRealmStatsSuccInterimAcrs"}, csbrfbillrealmstatssuccstopacrs{YType::uint32, "csbRfBillRealmStatsSuccStopAcrs"}, csbrfbillrealmstatssucceventacrs{YType::uint32, "csbRfBillRealmStatsSuccEventAcrs"}, csbrfbillrealmstatsfailstartacrs{YType::uint32, "csbRfBillRealmStatsFailStartAcrs"}, csbrfbillrealmstatsfailinterimacrs{YType::uint32, "csbRfBillRealmStatsFailInterimAcrs"}, csbrfbillrealmstatsfailstopacrs{YType::uint32, "csbRfBillRealmStatsFailStopAcrs"}, csbrfbillrealmstatsfaileventacrs{YType::uint32, "csbRfBillRealmStatsFailEventAcrs"} { yang_name = "csbRfBillRealmStatsEntry"; yang_parent_name = "csbRfBillRealmStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::~CsbRfBillRealmStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbrfbillrealmstatsindex.is_set || csbrfbillrealmstatsrealmname.is_set || csbrfbillrealmstatstotalstartacrs.is_set || csbrfbillrealmstatstotalinterimacrs.is_set || csbrfbillrealmstatstotalstopacrs.is_set || csbrfbillrealmstatstotaleventacrs.is_set || csbrfbillrealmstatssuccstartacrs.is_set || csbrfbillrealmstatssuccinterimacrs.is_set || csbrfbillrealmstatssuccstopacrs.is_set || csbrfbillrealmstatssucceventacrs.is_set || csbrfbillrealmstatsfailstartacrs.is_set || csbrfbillrealmstatsfailinterimacrs.is_set || csbrfbillrealmstatsfailstopacrs.is_set || csbrfbillrealmstatsfaileventacrs.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbrfbillrealmstatsindex.yfilter) || ydk::is_set(csbrfbillrealmstatsrealmname.yfilter) || ydk::is_set(csbrfbillrealmstatstotalstartacrs.yfilter) || ydk::is_set(csbrfbillrealmstatstotalinterimacrs.yfilter) || ydk::is_set(csbrfbillrealmstatstotalstopacrs.yfilter) || ydk::is_set(csbrfbillrealmstatstotaleventacrs.yfilter) || ydk::is_set(csbrfbillrealmstatssuccstartacrs.yfilter) || ydk::is_set(csbrfbillrealmstatssuccinterimacrs.yfilter) || ydk::is_set(csbrfbillrealmstatssuccstopacrs.yfilter) || ydk::is_set(csbrfbillrealmstatssucceventacrs.yfilter) || ydk::is_set(csbrfbillrealmstatsfailstartacrs.yfilter) || ydk::is_set(csbrfbillrealmstatsfailinterimacrs.yfilter) || ydk::is_set(csbrfbillrealmstatsfailstopacrs.yfilter) || ydk::is_set(csbrfbillrealmstatsfaileventacrs.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbRfBillRealmStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbRfBillRealmStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbrfbillrealmstatsindex, "csbRfBillRealmStatsIndex"); ADD_KEY_TOKEN(csbrfbillrealmstatsrealmname, "csbRfBillRealmStatsRealmName"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbrfbillrealmstatsindex.is_set || is_set(csbrfbillrealmstatsindex.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsindex.get_name_leafdata()); if (csbrfbillrealmstatsrealmname.is_set || is_set(csbrfbillrealmstatsrealmname.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsrealmname.get_name_leafdata()); if (csbrfbillrealmstatstotalstartacrs.is_set || is_set(csbrfbillrealmstatstotalstartacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatstotalstartacrs.get_name_leafdata()); if (csbrfbillrealmstatstotalinterimacrs.is_set || is_set(csbrfbillrealmstatstotalinterimacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatstotalinterimacrs.get_name_leafdata()); if (csbrfbillrealmstatstotalstopacrs.is_set || is_set(csbrfbillrealmstatstotalstopacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatstotalstopacrs.get_name_leafdata()); if (csbrfbillrealmstatstotaleventacrs.is_set || is_set(csbrfbillrealmstatstotaleventacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatstotaleventacrs.get_name_leafdata()); if (csbrfbillrealmstatssuccstartacrs.is_set || is_set(csbrfbillrealmstatssuccstartacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatssuccstartacrs.get_name_leafdata()); if (csbrfbillrealmstatssuccinterimacrs.is_set || is_set(csbrfbillrealmstatssuccinterimacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatssuccinterimacrs.get_name_leafdata()); if (csbrfbillrealmstatssuccstopacrs.is_set || is_set(csbrfbillrealmstatssuccstopacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatssuccstopacrs.get_name_leafdata()); if (csbrfbillrealmstatssucceventacrs.is_set || is_set(csbrfbillrealmstatssucceventacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatssucceventacrs.get_name_leafdata()); if (csbrfbillrealmstatsfailstartacrs.is_set || is_set(csbrfbillrealmstatsfailstartacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsfailstartacrs.get_name_leafdata()); if (csbrfbillrealmstatsfailinterimacrs.is_set || is_set(csbrfbillrealmstatsfailinterimacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsfailinterimacrs.get_name_leafdata()); if (csbrfbillrealmstatsfailstopacrs.is_set || is_set(csbrfbillrealmstatsfailstopacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsfailstopacrs.get_name_leafdata()); if (csbrfbillrealmstatsfaileventacrs.is_set || is_set(csbrfbillrealmstatsfaileventacrs.yfilter)) leaf_name_data.push_back(csbrfbillrealmstatsfaileventacrs.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsIndex") { csbrfbillrealmstatsindex = value; csbrfbillrealmstatsindex.value_namespace = name_space; csbrfbillrealmstatsindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsRealmName") { csbrfbillrealmstatsrealmname = value; csbrfbillrealmstatsrealmname.value_namespace = name_space; csbrfbillrealmstatsrealmname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsTotalStartAcrs") { csbrfbillrealmstatstotalstartacrs = value; csbrfbillrealmstatstotalstartacrs.value_namespace = name_space; csbrfbillrealmstatstotalstartacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsTotalInterimAcrs") { csbrfbillrealmstatstotalinterimacrs = value; csbrfbillrealmstatstotalinterimacrs.value_namespace = name_space; csbrfbillrealmstatstotalinterimacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsTotalStopAcrs") { csbrfbillrealmstatstotalstopacrs = value; csbrfbillrealmstatstotalstopacrs.value_namespace = name_space; csbrfbillrealmstatstotalstopacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsTotalEventAcrs") { csbrfbillrealmstatstotaleventacrs = value; csbrfbillrealmstatstotaleventacrs.value_namespace = name_space; csbrfbillrealmstatstotaleventacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsSuccStartAcrs") { csbrfbillrealmstatssuccstartacrs = value; csbrfbillrealmstatssuccstartacrs.value_namespace = name_space; csbrfbillrealmstatssuccstartacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsSuccInterimAcrs") { csbrfbillrealmstatssuccinterimacrs = value; csbrfbillrealmstatssuccinterimacrs.value_namespace = name_space; csbrfbillrealmstatssuccinterimacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsSuccStopAcrs") { csbrfbillrealmstatssuccstopacrs = value; csbrfbillrealmstatssuccstopacrs.value_namespace = name_space; csbrfbillrealmstatssuccstopacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsSuccEventAcrs") { csbrfbillrealmstatssucceventacrs = value; csbrfbillrealmstatssucceventacrs.value_namespace = name_space; csbrfbillrealmstatssucceventacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsFailStartAcrs") { csbrfbillrealmstatsfailstartacrs = value; csbrfbillrealmstatsfailstartacrs.value_namespace = name_space; csbrfbillrealmstatsfailstartacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsFailInterimAcrs") { csbrfbillrealmstatsfailinterimacrs = value; csbrfbillrealmstatsfailinterimacrs.value_namespace = name_space; csbrfbillrealmstatsfailinterimacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsFailStopAcrs") { csbrfbillrealmstatsfailstopacrs = value; csbrfbillrealmstatsfailstopacrs.value_namespace = name_space; csbrfbillrealmstatsfailstopacrs.value_namespace_prefix = name_space_prefix; } if(value_path == "csbRfBillRealmStatsFailEventAcrs") { csbrfbillrealmstatsfaileventacrs = value; csbrfbillrealmstatsfaileventacrs.value_namespace = name_space; csbrfbillrealmstatsfaileventacrs.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsIndex") { csbrfbillrealmstatsindex.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsRealmName") { csbrfbillrealmstatsrealmname.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsTotalStartAcrs") { csbrfbillrealmstatstotalstartacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsTotalInterimAcrs") { csbrfbillrealmstatstotalinterimacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsTotalStopAcrs") { csbrfbillrealmstatstotalstopacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsTotalEventAcrs") { csbrfbillrealmstatstotaleventacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsSuccStartAcrs") { csbrfbillrealmstatssuccstartacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsSuccInterimAcrs") { csbrfbillrealmstatssuccinterimacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsSuccStopAcrs") { csbrfbillrealmstatssuccstopacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsSuccEventAcrs") { csbrfbillrealmstatssucceventacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsFailStartAcrs") { csbrfbillrealmstatsfailstartacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsFailInterimAcrs") { csbrfbillrealmstatsfailinterimacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsFailStopAcrs") { csbrfbillrealmstatsfailstopacrs.yfilter = yfilter; } if(value_path == "csbRfBillRealmStatsFailEventAcrs") { csbrfbillrealmstatsfaileventacrs.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbRfBillRealmStatsTable::CsbRfBillRealmStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbRfBillRealmStatsIndex" || name == "csbRfBillRealmStatsRealmName" || name == "csbRfBillRealmStatsTotalStartAcrs" || name == "csbRfBillRealmStatsTotalInterimAcrs" || name == "csbRfBillRealmStatsTotalStopAcrs" || name == "csbRfBillRealmStatsTotalEventAcrs" || name == "csbRfBillRealmStatsSuccStartAcrs" || name == "csbRfBillRealmStatsSuccInterimAcrs" || name == "csbRfBillRealmStatsSuccStopAcrs" || name == "csbRfBillRealmStatsSuccEventAcrs" || name == "csbRfBillRealmStatsFailStartAcrs" || name == "csbRfBillRealmStatsFailInterimAcrs" || name == "csbRfBillRealmStatsFailStopAcrs" || name == "csbRfBillRealmStatsFailEventAcrs") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsTable() : csbsipmthdcurrentstatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbsipmthdcurrentstatsadjname", "csbsipmthdcurrentstatsmethod", "csbsipmthdcurrentstatsinterval"}) { yang_name = "csbSIPMthdCurrentStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::~CsbSIPMthdCurrentStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbsipmthdcurrentstatsentry.len(); index++) { if(csbsipmthdcurrentstatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::has_operation() const { for (std::size_t index=0; index<csbsipmthdcurrentstatsentry.len(); index++) { if(csbsipmthdcurrentstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdCurrentStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbSIPMthdCurrentStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry>(); ent_->parent = this; csbsipmthdcurrentstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbsipmthdcurrentstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbSIPMthdCurrentStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::CsbSIPMthdCurrentStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbsipmthdcurrentstatsadjname{YType::str, "csbSIPMthdCurrentStatsAdjName"}, csbsipmthdcurrentstatsmethod{YType::enumeration, "csbSIPMthdCurrentStatsMethod"}, csbsipmthdcurrentstatsinterval{YType::enumeration, "csbSIPMthdCurrentStatsInterval"}, csbsipmthdcurrentstatsmethodname{YType::str, "csbSIPMthdCurrentStatsMethodName"}, csbsipmthdcurrentstatsreqin{YType::uint32, "csbSIPMthdCurrentStatsReqIn"}, csbsipmthdcurrentstatsreqout{YType::uint32, "csbSIPMthdCurrentStatsReqOut"}, csbsipmthdcurrentstatsresp1xxin{YType::uint32, "csbSIPMthdCurrentStatsResp1xxIn"}, csbsipmthdcurrentstatsresp1xxout{YType::uint32, "csbSIPMthdCurrentStatsResp1xxOut"}, csbsipmthdcurrentstatsresp2xxin{YType::uint32, "csbSIPMthdCurrentStatsResp2xxIn"}, csbsipmthdcurrentstatsresp2xxout{YType::uint32, "csbSIPMthdCurrentStatsResp2xxOut"}, csbsipmthdcurrentstatsresp3xxin{YType::uint32, "csbSIPMthdCurrentStatsResp3xxIn"}, csbsipmthdcurrentstatsresp3xxout{YType::uint32, "csbSIPMthdCurrentStatsResp3xxOut"}, csbsipmthdcurrentstatsresp4xxin{YType::uint32, "csbSIPMthdCurrentStatsResp4xxIn"}, csbsipmthdcurrentstatsresp4xxout{YType::uint32, "csbSIPMthdCurrentStatsResp4xxOut"}, csbsipmthdcurrentstatsresp5xxin{YType::uint32, "csbSIPMthdCurrentStatsResp5xxIn"}, csbsipmthdcurrentstatsresp5xxout{YType::uint32, "csbSIPMthdCurrentStatsResp5xxOut"}, csbsipmthdcurrentstatsresp6xxin{YType::uint32, "csbSIPMthdCurrentStatsResp6xxIn"}, csbsipmthdcurrentstatsresp6xxout{YType::uint32, "csbSIPMthdCurrentStatsResp6xxOut"} { yang_name = "csbSIPMthdCurrentStatsEntry"; yang_parent_name = "csbSIPMthdCurrentStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::~CsbSIPMthdCurrentStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbsipmthdcurrentstatsadjname.is_set || csbsipmthdcurrentstatsmethod.is_set || csbsipmthdcurrentstatsinterval.is_set || csbsipmthdcurrentstatsmethodname.is_set || csbsipmthdcurrentstatsreqin.is_set || csbsipmthdcurrentstatsreqout.is_set || csbsipmthdcurrentstatsresp1xxin.is_set || csbsipmthdcurrentstatsresp1xxout.is_set || csbsipmthdcurrentstatsresp2xxin.is_set || csbsipmthdcurrentstatsresp2xxout.is_set || csbsipmthdcurrentstatsresp3xxin.is_set || csbsipmthdcurrentstatsresp3xxout.is_set || csbsipmthdcurrentstatsresp4xxin.is_set || csbsipmthdcurrentstatsresp4xxout.is_set || csbsipmthdcurrentstatsresp5xxin.is_set || csbsipmthdcurrentstatsresp5xxout.is_set || csbsipmthdcurrentstatsresp6xxin.is_set || csbsipmthdcurrentstatsresp6xxout.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbsipmthdcurrentstatsadjname.yfilter) || ydk::is_set(csbsipmthdcurrentstatsmethod.yfilter) || ydk::is_set(csbsipmthdcurrentstatsinterval.yfilter) || ydk::is_set(csbsipmthdcurrentstatsmethodname.yfilter) || ydk::is_set(csbsipmthdcurrentstatsreqin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsreqout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp1xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp1xxout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp2xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp2xxout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp3xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp3xxout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp4xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp4xxout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp5xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp5xxout.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp6xxin.yfilter) || ydk::is_set(csbsipmthdcurrentstatsresp6xxout.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbSIPMthdCurrentStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdCurrentStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbsipmthdcurrentstatsadjname, "csbSIPMthdCurrentStatsAdjName"); ADD_KEY_TOKEN(csbsipmthdcurrentstatsmethod, "csbSIPMthdCurrentStatsMethod"); ADD_KEY_TOKEN(csbsipmthdcurrentstatsinterval, "csbSIPMthdCurrentStatsInterval"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbsipmthdcurrentstatsadjname.is_set || is_set(csbsipmthdcurrentstatsadjname.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsadjname.get_name_leafdata()); if (csbsipmthdcurrentstatsmethod.is_set || is_set(csbsipmthdcurrentstatsmethod.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsmethod.get_name_leafdata()); if (csbsipmthdcurrentstatsinterval.is_set || is_set(csbsipmthdcurrentstatsinterval.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsinterval.get_name_leafdata()); if (csbsipmthdcurrentstatsmethodname.is_set || is_set(csbsipmthdcurrentstatsmethodname.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsmethodname.get_name_leafdata()); if (csbsipmthdcurrentstatsreqin.is_set || is_set(csbsipmthdcurrentstatsreqin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsreqin.get_name_leafdata()); if (csbsipmthdcurrentstatsreqout.is_set || is_set(csbsipmthdcurrentstatsreqout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsreqout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp1xxin.is_set || is_set(csbsipmthdcurrentstatsresp1xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp1xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp1xxout.is_set || is_set(csbsipmthdcurrentstatsresp1xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp1xxout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp2xxin.is_set || is_set(csbsipmthdcurrentstatsresp2xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp2xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp2xxout.is_set || is_set(csbsipmthdcurrentstatsresp2xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp2xxout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp3xxin.is_set || is_set(csbsipmthdcurrentstatsresp3xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp3xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp3xxout.is_set || is_set(csbsipmthdcurrentstatsresp3xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp3xxout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp4xxin.is_set || is_set(csbsipmthdcurrentstatsresp4xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp4xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp4xxout.is_set || is_set(csbsipmthdcurrentstatsresp4xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp4xxout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp5xxin.is_set || is_set(csbsipmthdcurrentstatsresp5xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp5xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp5xxout.is_set || is_set(csbsipmthdcurrentstatsresp5xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp5xxout.get_name_leafdata()); if (csbsipmthdcurrentstatsresp6xxin.is_set || is_set(csbsipmthdcurrentstatsresp6xxin.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp6xxin.get_name_leafdata()); if (csbsipmthdcurrentstatsresp6xxout.is_set || is_set(csbsipmthdcurrentstatsresp6xxout.yfilter)) leaf_name_data.push_back(csbsipmthdcurrentstatsresp6xxout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsAdjName") { csbsipmthdcurrentstatsadjname = value; csbsipmthdcurrentstatsadjname.value_namespace = name_space; csbsipmthdcurrentstatsadjname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsMethod") { csbsipmthdcurrentstatsmethod = value; csbsipmthdcurrentstatsmethod.value_namespace = name_space; csbsipmthdcurrentstatsmethod.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsInterval") { csbsipmthdcurrentstatsinterval = value; csbsipmthdcurrentstatsinterval.value_namespace = name_space; csbsipmthdcurrentstatsinterval.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsMethodName") { csbsipmthdcurrentstatsmethodname = value; csbsipmthdcurrentstatsmethodname.value_namespace = name_space; csbsipmthdcurrentstatsmethodname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsReqIn") { csbsipmthdcurrentstatsreqin = value; csbsipmthdcurrentstatsreqin.value_namespace = name_space; csbsipmthdcurrentstatsreqin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsReqOut") { csbsipmthdcurrentstatsreqout = value; csbsipmthdcurrentstatsreqout.value_namespace = name_space; csbsipmthdcurrentstatsreqout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp1xxIn") { csbsipmthdcurrentstatsresp1xxin = value; csbsipmthdcurrentstatsresp1xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp1xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp1xxOut") { csbsipmthdcurrentstatsresp1xxout = value; csbsipmthdcurrentstatsresp1xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp1xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp2xxIn") { csbsipmthdcurrentstatsresp2xxin = value; csbsipmthdcurrentstatsresp2xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp2xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp2xxOut") { csbsipmthdcurrentstatsresp2xxout = value; csbsipmthdcurrentstatsresp2xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp2xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp3xxIn") { csbsipmthdcurrentstatsresp3xxin = value; csbsipmthdcurrentstatsresp3xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp3xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp3xxOut") { csbsipmthdcurrentstatsresp3xxout = value; csbsipmthdcurrentstatsresp3xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp3xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp4xxIn") { csbsipmthdcurrentstatsresp4xxin = value; csbsipmthdcurrentstatsresp4xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp4xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp4xxOut") { csbsipmthdcurrentstatsresp4xxout = value; csbsipmthdcurrentstatsresp4xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp4xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp5xxIn") { csbsipmthdcurrentstatsresp5xxin = value; csbsipmthdcurrentstatsresp5xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp5xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp5xxOut") { csbsipmthdcurrentstatsresp5xxout = value; csbsipmthdcurrentstatsresp5xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp5xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp6xxIn") { csbsipmthdcurrentstatsresp6xxin = value; csbsipmthdcurrentstatsresp6xxin.value_namespace = name_space; csbsipmthdcurrentstatsresp6xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdCurrentStatsResp6xxOut") { csbsipmthdcurrentstatsresp6xxout = value; csbsipmthdcurrentstatsresp6xxout.value_namespace = name_space; csbsipmthdcurrentstatsresp6xxout.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsAdjName") { csbsipmthdcurrentstatsadjname.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsMethod") { csbsipmthdcurrentstatsmethod.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsInterval") { csbsipmthdcurrentstatsinterval.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsMethodName") { csbsipmthdcurrentstatsmethodname.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsReqIn") { csbsipmthdcurrentstatsreqin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsReqOut") { csbsipmthdcurrentstatsreqout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp1xxIn") { csbsipmthdcurrentstatsresp1xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp1xxOut") { csbsipmthdcurrentstatsresp1xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp2xxIn") { csbsipmthdcurrentstatsresp2xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp2xxOut") { csbsipmthdcurrentstatsresp2xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp3xxIn") { csbsipmthdcurrentstatsresp3xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp3xxOut") { csbsipmthdcurrentstatsresp3xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp4xxIn") { csbsipmthdcurrentstatsresp4xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp4xxOut") { csbsipmthdcurrentstatsresp4xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp5xxIn") { csbsipmthdcurrentstatsresp5xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp5xxOut") { csbsipmthdcurrentstatsresp5xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp6xxIn") { csbsipmthdcurrentstatsresp6xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdCurrentStatsResp6xxOut") { csbsipmthdcurrentstatsresp6xxout.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdCurrentStatsTable::CsbSIPMthdCurrentStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbSIPMthdCurrentStatsAdjName" || name == "csbSIPMthdCurrentStatsMethod" || name == "csbSIPMthdCurrentStatsInterval" || name == "csbSIPMthdCurrentStatsMethodName" || name == "csbSIPMthdCurrentStatsReqIn" || name == "csbSIPMthdCurrentStatsReqOut" || name == "csbSIPMthdCurrentStatsResp1xxIn" || name == "csbSIPMthdCurrentStatsResp1xxOut" || name == "csbSIPMthdCurrentStatsResp2xxIn" || name == "csbSIPMthdCurrentStatsResp2xxOut" || name == "csbSIPMthdCurrentStatsResp3xxIn" || name == "csbSIPMthdCurrentStatsResp3xxOut" || name == "csbSIPMthdCurrentStatsResp4xxIn" || name == "csbSIPMthdCurrentStatsResp4xxOut" || name == "csbSIPMthdCurrentStatsResp5xxIn" || name == "csbSIPMthdCurrentStatsResp5xxOut" || name == "csbSIPMthdCurrentStatsResp6xxIn" || name == "csbSIPMthdCurrentStatsResp6xxOut") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsTable() : csbsipmthdhistorystatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbsipmthdhistorystatsadjname", "csbsipmthdhistorystatsmethod", "csbsipmthdhistorystatsinterval"}) { yang_name = "csbSIPMthdHistoryStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::~CsbSIPMthdHistoryStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbsipmthdhistorystatsentry.len(); index++) { if(csbsipmthdhistorystatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::has_operation() const { for (std::size_t index=0; index<csbsipmthdhistorystatsentry.len(); index++) { if(csbsipmthdhistorystatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdHistoryStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbSIPMthdHistoryStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry>(); ent_->parent = this; csbsipmthdhistorystatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbsipmthdhistorystatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbSIPMthdHistoryStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::CsbSIPMthdHistoryStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbsipmthdhistorystatsadjname{YType::str, "csbSIPMthdHistoryStatsAdjName"}, csbsipmthdhistorystatsmethod{YType::enumeration, "csbSIPMthdHistoryStatsMethod"}, csbsipmthdhistorystatsinterval{YType::enumeration, "csbSIPMthdHistoryStatsInterval"}, csbsipmthdhistorystatsmethodname{YType::str, "csbSIPMthdHistoryStatsMethodName"}, csbsipmthdhistorystatsreqin{YType::uint32, "csbSIPMthdHistoryStatsReqIn"}, csbsipmthdhistorystatsreqout{YType::uint32, "csbSIPMthdHistoryStatsReqOut"}, csbsipmthdhistorystatsresp1xxin{YType::uint32, "csbSIPMthdHistoryStatsResp1xxIn"}, csbsipmthdhistorystatsresp1xxout{YType::uint32, "csbSIPMthdHistoryStatsResp1xxOut"}, csbsipmthdhistorystatsresp2xxin{YType::uint32, "csbSIPMthdHistoryStatsResp2xxIn"}, csbsipmthdhistorystatsresp2xxout{YType::uint32, "csbSIPMthdHistoryStatsResp2xxOut"}, csbsipmthdhistorystatsresp3xxin{YType::uint32, "csbSIPMthdHistoryStatsResp3xxIn"}, csbsipmthdhistorystatsresp3xxout{YType::uint32, "csbSIPMthdHistoryStatsResp3xxOut"}, csbsipmthdhistorystatsresp4xxin{YType::uint32, "csbSIPMthdHistoryStatsResp4xxIn"}, csbsipmthdhistorystatsresp4xxout{YType::uint32, "csbSIPMthdHistoryStatsResp4xxOut"}, csbsipmthdhistorystatsresp5xxin{YType::uint32, "csbSIPMthdHistoryStatsResp5xxIn"}, csbsipmthdhistorystatsresp5xxout{YType::uint32, "csbSIPMthdHistoryStatsResp5xxOut"}, csbsipmthdhistorystatsresp6xxin{YType::uint32, "csbSIPMthdHistoryStatsResp6xxIn"}, csbsipmthdhistorystatsresp6xxout{YType::uint32, "csbSIPMthdHistoryStatsResp6xxOut"} { yang_name = "csbSIPMthdHistoryStatsEntry"; yang_parent_name = "csbSIPMthdHistoryStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::~CsbSIPMthdHistoryStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbsipmthdhistorystatsadjname.is_set || csbsipmthdhistorystatsmethod.is_set || csbsipmthdhistorystatsinterval.is_set || csbsipmthdhistorystatsmethodname.is_set || csbsipmthdhistorystatsreqin.is_set || csbsipmthdhistorystatsreqout.is_set || csbsipmthdhistorystatsresp1xxin.is_set || csbsipmthdhistorystatsresp1xxout.is_set || csbsipmthdhistorystatsresp2xxin.is_set || csbsipmthdhistorystatsresp2xxout.is_set || csbsipmthdhistorystatsresp3xxin.is_set || csbsipmthdhistorystatsresp3xxout.is_set || csbsipmthdhistorystatsresp4xxin.is_set || csbsipmthdhistorystatsresp4xxout.is_set || csbsipmthdhistorystatsresp5xxin.is_set || csbsipmthdhistorystatsresp5xxout.is_set || csbsipmthdhistorystatsresp6xxin.is_set || csbsipmthdhistorystatsresp6xxout.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbsipmthdhistorystatsadjname.yfilter) || ydk::is_set(csbsipmthdhistorystatsmethod.yfilter) || ydk::is_set(csbsipmthdhistorystatsinterval.yfilter) || ydk::is_set(csbsipmthdhistorystatsmethodname.yfilter) || ydk::is_set(csbsipmthdhistorystatsreqin.yfilter) || ydk::is_set(csbsipmthdhistorystatsreqout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp1xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp1xxout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp2xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp2xxout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp3xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp3xxout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp4xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp4xxout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp5xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp5xxout.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp6xxin.yfilter) || ydk::is_set(csbsipmthdhistorystatsresp6xxout.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbSIPMthdHistoryStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdHistoryStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbsipmthdhistorystatsadjname, "csbSIPMthdHistoryStatsAdjName"); ADD_KEY_TOKEN(csbsipmthdhistorystatsmethod, "csbSIPMthdHistoryStatsMethod"); ADD_KEY_TOKEN(csbsipmthdhistorystatsinterval, "csbSIPMthdHistoryStatsInterval"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbsipmthdhistorystatsadjname.is_set || is_set(csbsipmthdhistorystatsadjname.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsadjname.get_name_leafdata()); if (csbsipmthdhistorystatsmethod.is_set || is_set(csbsipmthdhistorystatsmethod.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsmethod.get_name_leafdata()); if (csbsipmthdhistorystatsinterval.is_set || is_set(csbsipmthdhistorystatsinterval.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsinterval.get_name_leafdata()); if (csbsipmthdhistorystatsmethodname.is_set || is_set(csbsipmthdhistorystatsmethodname.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsmethodname.get_name_leafdata()); if (csbsipmthdhistorystatsreqin.is_set || is_set(csbsipmthdhistorystatsreqin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsreqin.get_name_leafdata()); if (csbsipmthdhistorystatsreqout.is_set || is_set(csbsipmthdhistorystatsreqout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsreqout.get_name_leafdata()); if (csbsipmthdhistorystatsresp1xxin.is_set || is_set(csbsipmthdhistorystatsresp1xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp1xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp1xxout.is_set || is_set(csbsipmthdhistorystatsresp1xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp1xxout.get_name_leafdata()); if (csbsipmthdhistorystatsresp2xxin.is_set || is_set(csbsipmthdhistorystatsresp2xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp2xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp2xxout.is_set || is_set(csbsipmthdhistorystatsresp2xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp2xxout.get_name_leafdata()); if (csbsipmthdhistorystatsresp3xxin.is_set || is_set(csbsipmthdhistorystatsresp3xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp3xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp3xxout.is_set || is_set(csbsipmthdhistorystatsresp3xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp3xxout.get_name_leafdata()); if (csbsipmthdhistorystatsresp4xxin.is_set || is_set(csbsipmthdhistorystatsresp4xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp4xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp4xxout.is_set || is_set(csbsipmthdhistorystatsresp4xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp4xxout.get_name_leafdata()); if (csbsipmthdhistorystatsresp5xxin.is_set || is_set(csbsipmthdhistorystatsresp5xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp5xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp5xxout.is_set || is_set(csbsipmthdhistorystatsresp5xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp5xxout.get_name_leafdata()); if (csbsipmthdhistorystatsresp6xxin.is_set || is_set(csbsipmthdhistorystatsresp6xxin.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp6xxin.get_name_leafdata()); if (csbsipmthdhistorystatsresp6xxout.is_set || is_set(csbsipmthdhistorystatsresp6xxout.yfilter)) leaf_name_data.push_back(csbsipmthdhistorystatsresp6xxout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsAdjName") { csbsipmthdhistorystatsadjname = value; csbsipmthdhistorystatsadjname.value_namespace = name_space; csbsipmthdhistorystatsadjname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsMethod") { csbsipmthdhistorystatsmethod = value; csbsipmthdhistorystatsmethod.value_namespace = name_space; csbsipmthdhistorystatsmethod.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsInterval") { csbsipmthdhistorystatsinterval = value; csbsipmthdhistorystatsinterval.value_namespace = name_space; csbsipmthdhistorystatsinterval.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsMethodName") { csbsipmthdhistorystatsmethodname = value; csbsipmthdhistorystatsmethodname.value_namespace = name_space; csbsipmthdhistorystatsmethodname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsReqIn") { csbsipmthdhistorystatsreqin = value; csbsipmthdhistorystatsreqin.value_namespace = name_space; csbsipmthdhistorystatsreqin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsReqOut") { csbsipmthdhistorystatsreqout = value; csbsipmthdhistorystatsreqout.value_namespace = name_space; csbsipmthdhistorystatsreqout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp1xxIn") { csbsipmthdhistorystatsresp1xxin = value; csbsipmthdhistorystatsresp1xxin.value_namespace = name_space; csbsipmthdhistorystatsresp1xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp1xxOut") { csbsipmthdhistorystatsresp1xxout = value; csbsipmthdhistorystatsresp1xxout.value_namespace = name_space; csbsipmthdhistorystatsresp1xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp2xxIn") { csbsipmthdhistorystatsresp2xxin = value; csbsipmthdhistorystatsresp2xxin.value_namespace = name_space; csbsipmthdhistorystatsresp2xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp2xxOut") { csbsipmthdhistorystatsresp2xxout = value; csbsipmthdhistorystatsresp2xxout.value_namespace = name_space; csbsipmthdhistorystatsresp2xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp3xxIn") { csbsipmthdhistorystatsresp3xxin = value; csbsipmthdhistorystatsresp3xxin.value_namespace = name_space; csbsipmthdhistorystatsresp3xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp3xxOut") { csbsipmthdhistorystatsresp3xxout = value; csbsipmthdhistorystatsresp3xxout.value_namespace = name_space; csbsipmthdhistorystatsresp3xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp4xxIn") { csbsipmthdhistorystatsresp4xxin = value; csbsipmthdhistorystatsresp4xxin.value_namespace = name_space; csbsipmthdhistorystatsresp4xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp4xxOut") { csbsipmthdhistorystatsresp4xxout = value; csbsipmthdhistorystatsresp4xxout.value_namespace = name_space; csbsipmthdhistorystatsresp4xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp5xxIn") { csbsipmthdhistorystatsresp5xxin = value; csbsipmthdhistorystatsresp5xxin.value_namespace = name_space; csbsipmthdhistorystatsresp5xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp5xxOut") { csbsipmthdhistorystatsresp5xxout = value; csbsipmthdhistorystatsresp5xxout.value_namespace = name_space; csbsipmthdhistorystatsresp5xxout.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp6xxIn") { csbsipmthdhistorystatsresp6xxin = value; csbsipmthdhistorystatsresp6xxin.value_namespace = name_space; csbsipmthdhistorystatsresp6xxin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdHistoryStatsResp6xxOut") { csbsipmthdhistorystatsresp6xxout = value; csbsipmthdhistorystatsresp6xxout.value_namespace = name_space; csbsipmthdhistorystatsresp6xxout.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsAdjName") { csbsipmthdhistorystatsadjname.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsMethod") { csbsipmthdhistorystatsmethod.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsInterval") { csbsipmthdhistorystatsinterval.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsMethodName") { csbsipmthdhistorystatsmethodname.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsReqIn") { csbsipmthdhistorystatsreqin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsReqOut") { csbsipmthdhistorystatsreqout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp1xxIn") { csbsipmthdhistorystatsresp1xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp1xxOut") { csbsipmthdhistorystatsresp1xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp2xxIn") { csbsipmthdhistorystatsresp2xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp2xxOut") { csbsipmthdhistorystatsresp2xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp3xxIn") { csbsipmthdhistorystatsresp3xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp3xxOut") { csbsipmthdhistorystatsresp3xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp4xxIn") { csbsipmthdhistorystatsresp4xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp4xxOut") { csbsipmthdhistorystatsresp4xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp5xxIn") { csbsipmthdhistorystatsresp5xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp5xxOut") { csbsipmthdhistorystatsresp5xxout.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp6xxIn") { csbsipmthdhistorystatsresp6xxin.yfilter = yfilter; } if(value_path == "csbSIPMthdHistoryStatsResp6xxOut") { csbsipmthdhistorystatsresp6xxout.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdHistoryStatsTable::CsbSIPMthdHistoryStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbSIPMthdHistoryStatsAdjName" || name == "csbSIPMthdHistoryStatsMethod" || name == "csbSIPMthdHistoryStatsInterval" || name == "csbSIPMthdHistoryStatsMethodName" || name == "csbSIPMthdHistoryStatsReqIn" || name == "csbSIPMthdHistoryStatsReqOut" || name == "csbSIPMthdHistoryStatsResp1xxIn" || name == "csbSIPMthdHistoryStatsResp1xxOut" || name == "csbSIPMthdHistoryStatsResp2xxIn" || name == "csbSIPMthdHistoryStatsResp2xxOut" || name == "csbSIPMthdHistoryStatsResp3xxIn" || name == "csbSIPMthdHistoryStatsResp3xxOut" || name == "csbSIPMthdHistoryStatsResp4xxIn" || name == "csbSIPMthdHistoryStatsResp4xxOut" || name == "csbSIPMthdHistoryStatsResp5xxIn" || name == "csbSIPMthdHistoryStatsResp5xxOut" || name == "csbSIPMthdHistoryStatsResp6xxIn" || name == "csbSIPMthdHistoryStatsResp6xxOut") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsTable() : csbsipmthdrccurrentstatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbsipmthdrccurrentstatsadjname", "csbsipmthdrccurrentstatsmethod", "csbsipmthdrccurrentstatsrespcode", "csbsipmthdrccurrentstatsinterval"}) { yang_name = "csbSIPMthdRCCurrentStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::~CsbSIPMthdRCCurrentStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbsipmthdrccurrentstatsentry.len(); index++) { if(csbsipmthdrccurrentstatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::has_operation() const { for (std::size_t index=0; index<csbsipmthdrccurrentstatsentry.len(); index++) { if(csbsipmthdrccurrentstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdRCCurrentStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbSIPMthdRCCurrentStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry>(); ent_->parent = this; csbsipmthdrccurrentstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbsipmthdrccurrentstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbSIPMthdRCCurrentStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::CsbSIPMthdRCCurrentStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbsipmthdrccurrentstatsadjname{YType::str, "csbSIPMthdRCCurrentStatsAdjName"}, csbsipmthdrccurrentstatsmethod{YType::enumeration, "csbSIPMthdRCCurrentStatsMethod"}, csbsipmthdrccurrentstatsrespcode{YType::uint32, "csbSIPMthdRCCurrentStatsRespCode"}, csbsipmthdrccurrentstatsinterval{YType::enumeration, "csbSIPMthdRCCurrentStatsInterval"}, csbsipmthdrccurrentstatsmethodname{YType::str, "csbSIPMthdRCCurrentStatsMethodName"}, csbsipmthdrccurrentstatsrespin{YType::uint32, "csbSIPMthdRCCurrentStatsRespIn"}, csbsipmthdrccurrentstatsrespout{YType::uint32, "csbSIPMthdRCCurrentStatsRespOut"} { yang_name = "csbSIPMthdRCCurrentStatsEntry"; yang_parent_name = "csbSIPMthdRCCurrentStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::~CsbSIPMthdRCCurrentStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbsipmthdrccurrentstatsadjname.is_set || csbsipmthdrccurrentstatsmethod.is_set || csbsipmthdrccurrentstatsrespcode.is_set || csbsipmthdrccurrentstatsinterval.is_set || csbsipmthdrccurrentstatsmethodname.is_set || csbsipmthdrccurrentstatsrespin.is_set || csbsipmthdrccurrentstatsrespout.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsadjname.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsmethod.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsrespcode.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsinterval.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsmethodname.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsrespin.yfilter) || ydk::is_set(csbsipmthdrccurrentstatsrespout.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbSIPMthdRCCurrentStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdRCCurrentStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbsipmthdrccurrentstatsadjname, "csbSIPMthdRCCurrentStatsAdjName"); ADD_KEY_TOKEN(csbsipmthdrccurrentstatsmethod, "csbSIPMthdRCCurrentStatsMethod"); ADD_KEY_TOKEN(csbsipmthdrccurrentstatsrespcode, "csbSIPMthdRCCurrentStatsRespCode"); ADD_KEY_TOKEN(csbsipmthdrccurrentstatsinterval, "csbSIPMthdRCCurrentStatsInterval"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbsipmthdrccurrentstatsadjname.is_set || is_set(csbsipmthdrccurrentstatsadjname.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsadjname.get_name_leafdata()); if (csbsipmthdrccurrentstatsmethod.is_set || is_set(csbsipmthdrccurrentstatsmethod.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsmethod.get_name_leafdata()); if (csbsipmthdrccurrentstatsrespcode.is_set || is_set(csbsipmthdrccurrentstatsrespcode.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsrespcode.get_name_leafdata()); if (csbsipmthdrccurrentstatsinterval.is_set || is_set(csbsipmthdrccurrentstatsinterval.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsinterval.get_name_leafdata()); if (csbsipmthdrccurrentstatsmethodname.is_set || is_set(csbsipmthdrccurrentstatsmethodname.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsmethodname.get_name_leafdata()); if (csbsipmthdrccurrentstatsrespin.is_set || is_set(csbsipmthdrccurrentstatsrespin.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsrespin.get_name_leafdata()); if (csbsipmthdrccurrentstatsrespout.is_set || is_set(csbsipmthdrccurrentstatsrespout.yfilter)) leaf_name_data.push_back(csbsipmthdrccurrentstatsrespout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsAdjName") { csbsipmthdrccurrentstatsadjname = value; csbsipmthdrccurrentstatsadjname.value_namespace = name_space; csbsipmthdrccurrentstatsadjname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsMethod") { csbsipmthdrccurrentstatsmethod = value; csbsipmthdrccurrentstatsmethod.value_namespace = name_space; csbsipmthdrccurrentstatsmethod.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsRespCode") { csbsipmthdrccurrentstatsrespcode = value; csbsipmthdrccurrentstatsrespcode.value_namespace = name_space; csbsipmthdrccurrentstatsrespcode.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsInterval") { csbsipmthdrccurrentstatsinterval = value; csbsipmthdrccurrentstatsinterval.value_namespace = name_space; csbsipmthdrccurrentstatsinterval.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsMethodName") { csbsipmthdrccurrentstatsmethodname = value; csbsipmthdrccurrentstatsmethodname.value_namespace = name_space; csbsipmthdrccurrentstatsmethodname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsRespIn") { csbsipmthdrccurrentstatsrespin = value; csbsipmthdrccurrentstatsrespin.value_namespace = name_space; csbsipmthdrccurrentstatsrespin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCCurrentStatsRespOut") { csbsipmthdrccurrentstatsrespout = value; csbsipmthdrccurrentstatsrespout.value_namespace = name_space; csbsipmthdrccurrentstatsrespout.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsAdjName") { csbsipmthdrccurrentstatsadjname.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsMethod") { csbsipmthdrccurrentstatsmethod.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsRespCode") { csbsipmthdrccurrentstatsrespcode.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsInterval") { csbsipmthdrccurrentstatsinterval.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsMethodName") { csbsipmthdrccurrentstatsmethodname.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsRespIn") { csbsipmthdrccurrentstatsrespin.yfilter = yfilter; } if(value_path == "csbSIPMthdRCCurrentStatsRespOut") { csbsipmthdrccurrentstatsrespout.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCCurrentStatsTable::CsbSIPMthdRCCurrentStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbSIPMthdRCCurrentStatsAdjName" || name == "csbSIPMthdRCCurrentStatsMethod" || name == "csbSIPMthdRCCurrentStatsRespCode" || name == "csbSIPMthdRCCurrentStatsInterval" || name == "csbSIPMthdRCCurrentStatsMethodName" || name == "csbSIPMthdRCCurrentStatsRespIn" || name == "csbSIPMthdRCCurrentStatsRespOut") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsTable() : csbsipmthdrchistorystatsentry(this, {"csbcallstatsinstanceindex", "csbcallstatsserviceindex", "csbsipmthdrchistorystatsadjname", "csbsipmthdrchistorystatsmethod", "csbsipmthdrchistorystatsrespcode", "csbsipmthdrchistorystatsinterval"}) { yang_name = "csbSIPMthdRCHistoryStatsTable"; yang_parent_name = "CISCO-SESS-BORDER-CTRLR-STATS-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::~CsbSIPMthdRCHistoryStatsTable() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<csbsipmthdrchistorystatsentry.len(); index++) { if(csbsipmthdrchistorystatsentry[index]->has_data()) return true; } return false; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::has_operation() const { for (std::size_t index=0; index<csbsipmthdrchistorystatsentry.len(); index++) { if(csbsipmthdrchistorystatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdRCHistoryStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "csbSIPMthdRCHistoryStatsEntry") { auto ent_ = std::make_shared<CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry>(); ent_->parent = this; csbsipmthdrchistorystatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : csbsipmthdrchistorystatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbSIPMthdRCHistoryStatsEntry") return true; return false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::CsbSIPMthdRCHistoryStatsEntry() : csbcallstatsinstanceindex{YType::str, "csbCallStatsInstanceIndex"}, csbcallstatsserviceindex{YType::str, "csbCallStatsServiceIndex"}, csbsipmthdrchistorystatsadjname{YType::str, "csbSIPMthdRCHistoryStatsAdjName"}, csbsipmthdrchistorystatsmethod{YType::enumeration, "csbSIPMthdRCHistoryStatsMethod"}, csbsipmthdrchistorystatsrespcode{YType::uint32, "csbSIPMthdRCHistoryStatsRespCode"}, csbsipmthdrchistorystatsinterval{YType::enumeration, "csbSIPMthdRCHistoryStatsInterval"}, csbsipmthdrchistorystatsmethodname{YType::str, "csbSIPMthdRCHistoryStatsMethodName"}, csbsipmthdrchistorystatsrespin{YType::uint32, "csbSIPMthdRCHistoryStatsRespIn"}, csbsipmthdrchistorystatsrespout{YType::uint32, "csbSIPMthdRCHistoryStatsRespOut"} { yang_name = "csbSIPMthdRCHistoryStatsEntry"; yang_parent_name = "csbSIPMthdRCHistoryStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::~CsbSIPMthdRCHistoryStatsEntry() { } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::has_data() const { if (is_presence_container) return true; return csbcallstatsinstanceindex.is_set || csbcallstatsserviceindex.is_set || csbsipmthdrchistorystatsadjname.is_set || csbsipmthdrchistorystatsmethod.is_set || csbsipmthdrchistorystatsrespcode.is_set || csbsipmthdrchistorystatsinterval.is_set || csbsipmthdrchistorystatsmethodname.is_set || csbsipmthdrchistorystatsrespin.is_set || csbsipmthdrchistorystatsrespout.is_set; } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(csbcallstatsinstanceindex.yfilter) || ydk::is_set(csbcallstatsserviceindex.yfilter) || ydk::is_set(csbsipmthdrchistorystatsadjname.yfilter) || ydk::is_set(csbsipmthdrchistorystatsmethod.yfilter) || ydk::is_set(csbsipmthdrchistorystatsrespcode.yfilter) || ydk::is_set(csbsipmthdrchistorystatsinterval.yfilter) || ydk::is_set(csbsipmthdrchistorystatsmethodname.yfilter) || ydk::is_set(csbsipmthdrchistorystatsrespin.yfilter) || ydk::is_set(csbsipmthdrchistorystatsrespout.yfilter); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-SESS-BORDER-CTRLR-STATS-MIB:CISCO-SESS-BORDER-CTRLR-STATS-MIB/csbSIPMthdRCHistoryStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "csbSIPMthdRCHistoryStatsEntry"; ADD_KEY_TOKEN(csbcallstatsinstanceindex, "csbCallStatsInstanceIndex"); ADD_KEY_TOKEN(csbcallstatsserviceindex, "csbCallStatsServiceIndex"); ADD_KEY_TOKEN(csbsipmthdrchistorystatsadjname, "csbSIPMthdRCHistoryStatsAdjName"); ADD_KEY_TOKEN(csbsipmthdrchistorystatsmethod, "csbSIPMthdRCHistoryStatsMethod"); ADD_KEY_TOKEN(csbsipmthdrchistorystatsrespcode, "csbSIPMthdRCHistoryStatsRespCode"); ADD_KEY_TOKEN(csbsipmthdrchistorystatsinterval, "csbSIPMthdRCHistoryStatsInterval"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (csbcallstatsinstanceindex.is_set || is_set(csbcallstatsinstanceindex.yfilter)) leaf_name_data.push_back(csbcallstatsinstanceindex.get_name_leafdata()); if (csbcallstatsserviceindex.is_set || is_set(csbcallstatsserviceindex.yfilter)) leaf_name_data.push_back(csbcallstatsserviceindex.get_name_leafdata()); if (csbsipmthdrchistorystatsadjname.is_set || is_set(csbsipmthdrchistorystatsadjname.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsadjname.get_name_leafdata()); if (csbsipmthdrchistorystatsmethod.is_set || is_set(csbsipmthdrchistorystatsmethod.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsmethod.get_name_leafdata()); if (csbsipmthdrchistorystatsrespcode.is_set || is_set(csbsipmthdrchistorystatsrespcode.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsrespcode.get_name_leafdata()); if (csbsipmthdrchistorystatsinterval.is_set || is_set(csbsipmthdrchistorystatsinterval.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsinterval.get_name_leafdata()); if (csbsipmthdrchistorystatsmethodname.is_set || is_set(csbsipmthdrchistorystatsmethodname.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsmethodname.get_name_leafdata()); if (csbsipmthdrchistorystatsrespin.is_set || is_set(csbsipmthdrchistorystatsrespin.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsrespin.get_name_leafdata()); if (csbsipmthdrchistorystatsrespout.is_set || is_set(csbsipmthdrchistorystatsrespout.yfilter)) leaf_name_data.push_back(csbsipmthdrchistorystatsrespout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex = value; csbcallstatsinstanceindex.value_namespace = name_space; csbcallstatsinstanceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex = value; csbcallstatsserviceindex.value_namespace = name_space; csbcallstatsserviceindex.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsAdjName") { csbsipmthdrchistorystatsadjname = value; csbsipmthdrchistorystatsadjname.value_namespace = name_space; csbsipmthdrchistorystatsadjname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsMethod") { csbsipmthdrchistorystatsmethod = value; csbsipmthdrchistorystatsmethod.value_namespace = name_space; csbsipmthdrchistorystatsmethod.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsRespCode") { csbsipmthdrchistorystatsrespcode = value; csbsipmthdrchistorystatsrespcode.value_namespace = name_space; csbsipmthdrchistorystatsrespcode.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsInterval") { csbsipmthdrchistorystatsinterval = value; csbsipmthdrchistorystatsinterval.value_namespace = name_space; csbsipmthdrchistorystatsinterval.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsMethodName") { csbsipmthdrchistorystatsmethodname = value; csbsipmthdrchistorystatsmethodname.value_namespace = name_space; csbsipmthdrchistorystatsmethodname.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsRespIn") { csbsipmthdrchistorystatsrespin = value; csbsipmthdrchistorystatsrespin.value_namespace = name_space; csbsipmthdrchistorystatsrespin.value_namespace_prefix = name_space_prefix; } if(value_path == "csbSIPMthdRCHistoryStatsRespOut") { csbsipmthdrchistorystatsrespout = value; csbsipmthdrchistorystatsrespout.value_namespace = name_space; csbsipmthdrchistorystatsrespout.value_namespace_prefix = name_space_prefix; } } void CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "csbCallStatsInstanceIndex") { csbcallstatsinstanceindex.yfilter = yfilter; } if(value_path == "csbCallStatsServiceIndex") { csbcallstatsserviceindex.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsAdjName") { csbsipmthdrchistorystatsadjname.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsMethod") { csbsipmthdrchistorystatsmethod.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsRespCode") { csbsipmthdrchistorystatsrespcode.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsInterval") { csbsipmthdrchistorystatsinterval.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsMethodName") { csbsipmthdrchistorystatsmethodname.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsRespIn") { csbsipmthdrchistorystatsrespin.yfilter = yfilter; } if(value_path == "csbSIPMthdRCHistoryStatsRespOut") { csbsipmthdrchistorystatsrespout.yfilter = yfilter; } } bool CISCOSESSBORDERCTRLRSTATSMIB::CsbSIPMthdRCHistoryStatsTable::CsbSIPMthdRCHistoryStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "csbCallStatsInstanceIndex" || name == "csbCallStatsServiceIndex" || name == "csbSIPMthdRCHistoryStatsAdjName" || name == "csbSIPMthdRCHistoryStatsMethod" || name == "csbSIPMthdRCHistoryStatsRespCode" || name == "csbSIPMthdRCHistoryStatsInterval" || name == "csbSIPMthdRCHistoryStatsMethodName" || name == "csbSIPMthdRCHistoryStatsRespIn" || name == "csbSIPMthdRCHistoryStatsRespOut") return true; return false; } const Enum::YLeaf CiscoSbcSIPMethod::unknown {1, "unknown"}; const Enum::YLeaf CiscoSbcSIPMethod::ack {2, "ack"}; const Enum::YLeaf CiscoSbcSIPMethod::bye {3, "bye"}; const Enum::YLeaf CiscoSbcSIPMethod::cancel {4, "cancel"}; const Enum::YLeaf CiscoSbcSIPMethod::info {5, "info"}; const Enum::YLeaf CiscoSbcSIPMethod::invite {6, "invite"}; const Enum::YLeaf CiscoSbcSIPMethod::message {7, "message"}; const Enum::YLeaf CiscoSbcSIPMethod::notify {8, "notify"}; const Enum::YLeaf CiscoSbcSIPMethod::options {9, "options"}; const Enum::YLeaf CiscoSbcSIPMethod::prack {10, "prack"}; const Enum::YLeaf CiscoSbcSIPMethod::refer {11, "refer"}; const Enum::YLeaf CiscoSbcSIPMethod::register_ {12, "register"}; const Enum::YLeaf CiscoSbcSIPMethod::subscribe {13, "subscribe"}; const Enum::YLeaf CiscoSbcSIPMethod::update {14, "update"}; const Enum::YLeaf CiscoSbcRadiusClientType::authentication {1, "authentication"}; const Enum::YLeaf CiscoSbcRadiusClientType::accounting {2, "accounting"}; } }
46.218126
885
0.777262
[ "vector" ]
194134137d947ca7fabeff61fbb2529cf1c4445f
4,068
cpp
C++
oop2_project/BoardObject.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
2
2020-08-19T10:19:22.000Z
2021-08-15T15:29:47.000Z
oop2_project/BoardObject.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
null
null
null
oop2_project/BoardObject.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
2
2020-10-06T08:42:04.000Z
2020-12-24T11:03:35.000Z
#include "BoardObject.h" #include "GameScreen.h" #include "MovingObject.h" #include "SoundManager.h" BoardObject::BoardObject(GameScreen& gameScreen, int drawPriority) : AnimationView(gameScreen.getWindow()), m_gameScreen(gameScreen), m_inGame(false) { setDrawPriority(drawPriority); init(); } void BoardObject::playSound(const string& name, float pitch, float volume) { static float maxHearPixels = static_cast<float>(MAX_HEAR_SOUND_CELLS * getDefaultSize().x); float diffP = maxHearPixels - getRadiusFromPlayer(); if (diffP > 0.f) { float realVolume = (volume*diffP)/maxHearPixels; GUI::SoundManager::getInterface().playSound(name, realVolume, pitch); } } float BoardObject::getRadiusFromPlayer() const { return getDistance(getGameScreen().getWorld().getBODS().getPlayer()); } void BoardObject::setDrawPriority(int drawPriority) { if (drawPriority < 0) throw std::out_of_range("Draw priority " + std::to_string(drawPriority) + " must be bigger or equals to zero"); m_drawPriority = drawPriority; } float BoardObject::getDistance(const std::shared_ptr<BoardObject>& other) const { sf::Vector2f myCenter = getCenter(), otherCenter = other->getPosition(); return sqrt(pow(myCenter.x - otherCenter.x, 2) + pow(myCenter.y - otherCenter.y, 2)); } string BoardObject::toString() const { string str = "BoardObject: { proxyId=" + std::to_string(m_proxyId) + ", drawPriority=" + std::to_string(m_drawPriority); str += ", aabb: { lower: { x=" + std::to_string(m_aabb.lowerBound.x) + ", y=" + std::to_string(m_aabb.lowerBound.y) + " }"; str += ", upper: { x=" + std::to_string(m_aabb.upperBound.x) + ", y=" + std::to_string(m_aabb.upperBound.y) + " }"; str += ", " + AnimationView::toString() + " }"; return str; } void BoardObject::setInGame(const std::shared_ptr<BoardObject>& self) { m_inGame = true; m_self = self; onJoinedGame(); // call event } std::forward_list<BoardObject*> BoardObject::getCollidesList() { // collide query handler struct QueryHandler { QueryHandler(GameScreen& gameScreen, BoardObject* self) : m_gameScreen(gameScreen), m_self(self) {} GameScreen& m_gameScreen; std::forward_list<BoardObject*> m_collides; BoardObject* m_self; // callback from Box2D lib bool QueryCallback(int32 proxyId) { // check if isn't me if (proxyId != m_self->getProxyId()) { b2DynamicTree& aabbTree = m_gameScreen.getWorld().getBODS().getAABBTree(); BoardObject* bo = static_cast<BoardObject*>(aabbTree.GetUserData(proxyId)); m_collides.push_front(bo); } return true; } // build collides list std::forward_list<BoardObject*> quaryCollides() { b2DynamicTree& aabbTree = m_gameScreen.getWorld().getBODS().getAABBTree(); aabbTree.Query(this, m_self->getAABB()); return m_collides; } }; // build collide list QueryHandler quaryHandler(m_gameScreen, this); return quaryHandler.quaryCollides(); } const std::shared_ptr<BoardObject>& BoardObject::getSelf() const { if (!isInGame()) std::logic_error("Cannot get self because object not in game"); return m_self; } const sf::Vector2i& BoardObject::getDefaultSize() { // init static sf::Vector2i DEFAULT_SIZE(50, 50); return DEFAULT_SIZE; } void BoardObject::vanish() { onVanish(); getGameScreen().getWorld().getBODS().requestRemoveBO(getSelf()); } void BoardObject::updateComponents() { AnimationView::updateComponents(); updateAABB(); } void BoardObject::updateAABB() { // save last AABB b2AABB lastAABB = m_aabb; // update AABB member const sf::Vector2f& position = getPosition(); const sf::Vector2i& size = getSize(); m_aabb.lowerBound = b2Vec2(position.x, position.y); m_aabb.upperBound = b2Vec2(position.x + float(size.x), position.y + float(size.y)); if (isInGame()) { // update in tree b2Vec2 displacement = m_aabb.GetCenter() - lastAABB.GetCenter(); b2DynamicTree& aabbTree = getGameScreen().getWorld().getBODS().getAABBTree(); aabbTree.MoveProxy(m_proxyId, m_aabb, displacement); } } void BoardObject::init() { setParent(getGameScreen().getWorld()); setSize(getDefaultSize()); }
28.055172
124
0.717306
[ "object" ]
194ee59353d2a8c9da24e50c592f4e086806d078
1,460
cpp
C++
megatron/fused_kernels/fused_weight_gradient_dense.cpp
zarzen/Megatron-LM
d898a8991d1a08d29074f87819d1bf41517e35f5
[ "Apache-2.0" ]
null
null
null
megatron/fused_kernels/fused_weight_gradient_dense.cpp
zarzen/Megatron-LM
d898a8991d1a08d29074f87819d1bf41517e35f5
[ "Apache-2.0" ]
null
null
null
megatron/fused_kernels/fused_weight_gradient_dense.cpp
zarzen/Megatron-LM
d898a8991d1a08d29074f87819d1bf41517e35f5
[ "Apache-2.0" ]
null
null
null
#include <torch/torch.h> #include <torch/extension.h> #include <vector> #include <stdio.h> #include "type_shim.h" template <typename T> int wgrad_gemm_accum_fp32_cuda(T *input, T *d_output, float *d_weight, int in_dim, int hidden_dim, int out_dim); void wgrad_gemm_accum_fp32(const at::Tensor input, const at::Tensor d_output, at::Tensor d_weight) { at::Tensor input_2d, d_output_2d; // input tensor: collapse to the first dim auto in_sizes = input.sizes(); if (input.dim() > 2) { input_2d = input.view({-1, in_sizes[in_sizes.size() - 1]}); } else { input_2d = input; } // d_output tensor: collapse to the first dim auto d_out_sizes = d_output.sizes(); if (d_output.dim() > 2) { d_output_2d = d_output.view({-1, d_out_sizes[d_out_sizes.size() - 1]}); } else { d_output_2d = d_output; } int hidden_dim = input_2d.size(0); int in_dim = input_2d.size(1); int out_dim = d_weight.size(0); DISPATCH_HALF_BFLOAT_AND_FLOAT(input_2d.scalar_type(), "wgrad_gemm_accum_fp32", int result = wgrad_gemm_accum_fp32_cuda<scalar_t>( input_2d.data_ptr<scalar_t>(), d_output_2d.data_ptr<scalar_t>(), d_weight.data_ptr<float>(), in_dim, hidden_dim, out_dim); ); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("wgrad_gemm_accum_fp32", &wgrad_gemm_accum_fp32, "wgrad gemm accum in fp32"); }
30.416667
112
0.65
[ "vector" ]
1955067fd72481a63954e19cc2cc74d4a4edddf9
736
hpp
C++
include/utility/trait/type/features/is_move_constructible.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
2
2017-12-10T10:59:48.000Z
2017-12-13T04:11:14.000Z
include/utility/trait/type/features/is_move_constructible.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
include/utility/trait/type/features/is_move_constructible.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
#ifndef __UTILITY_TRAIT_TYPE_FEATURES_IS_MOVE_CONSTRUCTIBLE__ #define __UTILITY_TRAIT_TYPE_FEATURES_IS_MOVE_CONSTRUCTIBLE__ #include<utility/trait/trait_helper.hpp> #include<utility/trait/type/transform/add_reference.hpp> #include<utility/trait/type/features/is_constructible.hpp> namespace utility { namespace trait { namespace type { namespace features { // is_move_constructible template<typename _T> struct is_move_constructible : public trait::type::features::is_constructible<_T, typename trait::type::transform::add_rvalue_reference<_T>::type> { }; } } } } #endif // __UTILITY_TRAIT_TYPE_FEATURES_IS_MOVE_CONSTRUCTIBLE__
23
67
0.716033
[ "transform" ]
195b9555deb61f71ed83aba35b356c43086a30da
12,976
hpp
C++
src/Math/vec3.hpp
MaGetzUb/SoftwareRenderer
e1d6242617863a1d9fdc272c1011a3938d1dbbc9
[ "BSD-2-Clause" ]
1
2020-01-01T12:07:07.000Z
2020-01-01T12:07:07.000Z
src/Math/vec3.hpp
MaGetzUb/SoftwareRenderer
e1d6242617863a1d9fdc272c1011a3938d1dbbc9
[ "BSD-2-Clause" ]
null
null
null
src/Math/vec3.hpp
MaGetzUb/SoftwareRenderer
e1d6242617863a1d9fdc272c1011a3938d1dbbc9
[ "BSD-2-Clause" ]
1
2018-07-20T07:51:06.000Z
2018-07-20T07:51:06.000Z
/* Copyright © 2018, Marko Ranta All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 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. */ //Vector 3 class, based on my other project 'FrostCore'. ~MaGetzUb #ifndef VEC3_HPP #define VEC3_HPP #include "math.hpp" #include "matrix.hpp" template<class T> struct tquat; template <class T> struct tvec3; template <class T> struct tvec2; template<class T> inline static tvec3<T> operator*(T a, const tvec3<T>& b); template<class T> inline static tvec3<T> operator*(const tvec3<T>& a, T b); template <class T> struct tvec3 { static_assert(std::is_arithmetic<T>::value, "Only arithmetic types allowed for tvec3!"); union { struct { T x, y, z; }; struct { T r, g, b; }; struct { T w, h, d; }; }; tvec3(): x(0), y(0), z(0) {} tvec3(T v): x(v), y(v), z(v) {} tvec3(T av, T bv, T cv): x(av), y(bv), z(cv) {} tvec3(const tvec3<T>& r): x(r.x), y(r.y), z(r.z) {} tvec3(tvec3<T>&& r): tvec3() { std::swap(x, r.x); std::swap(y, r.y); std::swap(z, r.z); } template<class B> explicit tvec3(const tvec3<B>& b): x((T)b.x), y((T)b.y), z((T)b.z) {} ~tvec3() {} T& operator[](int i) { return *((T*)&x+i); } const T& operator[](int i) const { return *((T*)&x+i); } inline tvec3& operator=(const tvec3<T>& r) { x = r.x; y = r.y; z = r.z; return *this; } inline tvec3& operator+=(const tvec3<T>& r) { x += r.x; y += r.y; z += r.z; return *this; } inline tvec3& operator-=(const tvec3<T>& r) { x -= r.x; y -= r.y; z -= r.z; return *this; } inline tvec3& operator*=(T r) { x *= r; y *= r; z *= r; return *this; } inline tvec3& operator/=(T r) { x /= r; y /= r; z /= r; return *this; } bool operator==(const tvec3& r) { return ((x == r.x) && (y == r.y) && (z == r.z)); } tvec3 operator-() { return tvec3<T>(-x, -y, -z); } inline T dot(const tvec3& r) const { return x*r.x + y*r.y + z*r.z; } inline tvec3 cross(const tvec3& r) const { return tvec3<T>{y*r.z - z*r.y, z*r.x - x*r.z, x*r.y - y*r.x}; } /*inline tmat3<T> outer(const tvec3& b) const { return tmat3<T>({x*b.x, x*b.y, x*b.z}, {y*b.x, y*b.y, y*b.z}, {z*b.x, z*b.y, z*b.z}); }*/ inline tvec3 mix(const tvec3& r, T amt) const { return (*this)*((T)1 - amt) + r*amt; } inline T magnitude() const { return dot(*this); } inline T length() const { return sqrt(magnitude()); } inline tvec3& normalize() { T mag = magnitude(); //if(mag == (T)1) return *this; *this /= sqrt(mag); return *this; } inline void basis(tvec3<T>& t, tvec3<T>& bt) const { #define SQRT1OVER3 0.57735026918962576450914878050196 t = (x < (T)SQRT1OVER3) ? tvec3<T>{(T)y, -(T)x, (T)0} : tvec3<T>{(T)0, (T)z, -(T)y}; t = reorthogonalize(*this, t); bt = (*this).cross(t); bt = reorthogonalize(*this, bt); #undef SQRT1OVER3 } inline tvec3 normalized() const { return tvec3(*this).normalize(); } inline tvec3<T> rotated(const tquat<T>& q) const { return q.rotate(*this); } inline tvec3<T>& rotate(const tquat<T>& q) { *this = q.rotate(*this); return *this; } inline tvec2<T> vec2() const { return {x, y}; } inline tvec3<T>& rotate(T angle, const tvec3<T>& axis) { T sinHalfAng = Sin(angle); T cosHalfAng = Cos(angle); T rx = axis.x * sinHalfAng; T ry = axis.y * sinHalfAng; T rz = axis.z * sinHalfAng; T rw = cosHalfAng; tquat<T> rotQ(rx, ry, rz, rw); return rotate(rotQ); } inline tvec3<T> rotated(T angle, const tvec3<T>& axis) const { tvec3<T> n = (*this); n.rotate(angle, axis); return n; } inline tvec3<T> xzy() const { return tvec3(x, z, y); } inline tvec3<T> yxz() const { return tvec3(y, x, z); } inline tvec3<T> yzx() const { return tvec3(y, z, x); } inline tvec3<T> zyx() const { return tvec3(z, y, x); } inline tvec3<T> zxy() const { return tvec3(z, x, y); } }; template <class T> void tmat4<T>::transform(const tvec3<T>& vec) { transform(vec.x, vec.y, vec.z); } template <class T> inline static T length(const tvec3<T>& v) { return v.length(); } template <class T> inline static T magnitude(const tvec3<T>& v) { return v.magnitude(); } template<class T> inline static T operator*(const tvec3<T>& a, const tvec3<T>& b) { return a.x*b.x + a.y*b.y + a.z*b.z; } template <class T> static inline tvec3<T> normalize(const tvec3<T>& vec) { return vec.normalized(); } template <class T> inline static tvec3<T> reorthogonalize(const tvec3<T>& a, const tvec3<T>& b) { return normalize(a - dot(a, b) * b); } template<class T> inline static tvec3<T>& operator-(tvec3<T>& vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } template<class T> inline static bool operator==(const tvec3<T>& a, const tvec3<T>& b) { return (a.x == b.x && a.y == b.y && a.z == b.z); } template<class T> inline static bool operator!=(const tvec3<T>& a, const tvec3<T>& b) { return !(a == b); } template<class T> inline static tvec3<T> operator+(const tvec3<T>& a, const tvec3<T>& b) { return tvec3<T>(a.x+b.x, a.y+b.y, a.z+b.z); } template<class T> inline static tvec3<T> operator-(const tvec3<T>& a, const tvec3<T>& b) { return tvec3<T>(a.x-b.x, a.y-b.y, a.z-b.z); } template<class T> inline static tvec3<T> operator-(const tvec3<T>& v) { return tvec3<T>(-v.x, -v.y, -v.z); } template<class T> inline static tvec3<T> operator/(const tvec3<T>& a, T b) { return tvec3<T>(a.x / b, a.y / b, a.z / b); } template<class T, class B> inline static tvec3<T> operator/(const tvec3<T>& a, B b) { return tvec3<T>(a.x / (T)b, a.y / (T)b, a.z / (T)b); } template<class T> inline static tvec3<T> operator*(const tvec3<T>& a, T b) { return tvec3<T>(a.x * b, a.y * b, a.z * b); } template<class T, class B> inline static tvec3<T> operator*(const tvec3<T>& a, B b) { return tvec3<T>(a.x * (T)b, a.y * (T)b, a.z * (T)b); } //Hadamard product template<class T> inline static tvec3<T> operator*(const tvec3<T>& a, const tvec3<T>& b) { return tvec3<T>(a.x * b.x, a.y*b.y, a.z*b.z); } template<class T> inline static tvec3<T> operator*(T a, const tvec3<T>& b) { return tvec3<T>(a * b.x, a * b.y, a * b.z); } template <class T> static tvec3<T> operator*(const tmat4<T>& m, const tvec3<T>& v) { tvec3<T> o; o.x = v.x * m[0][0] + v.y * m[1][0] + v.z * m[2][0] + (T)1 * m[3][0]; o.y = v.x * m[0][1] + v.y * m[1][1] + v.z * m[2][1] + (T)1 * m[3][1]; o.z = v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + (T)1 * m[3][2]; return o; } /* template <class T> static tvec3<T> operator*(const tmat3<T>& m, const tvec3<T>& v) { tvec3<T> o; o.x = v.x * m[0][0] + v.y * m[1][0] + v.z * m[2][0]; o.y = v.x * m[0][1] + v.y * m[1][1] + v.z * m[2][1]; o.z = v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2]; return o; } */ typedef tvec3<double> dvec3; typedef tvec3<float> vec3; typedef tvec3<int> ivec3; typedef tvec3<unsigned> uvec3; #ifdef USE_SIMD //__m128 row1 = _mm_set_ps(m.data()[0], m.data()[1], m.data()[2], m.data()[3]); //__m128 row2 = _mm_set_ps(m.data()[4], m.data()[5], m.data()[6], m.data()[7]); //__m128 row3 = _mm_set_ps(m.data()[8], m.data()[9], m.data()[10], m.data()[11]); //__m128 row4 = _mm_set_ps(m.data()[12], m.data()[13], m.data()[14], m.data()[15]); inline static vec3 operator*(const mat4& m, const vec3& vec) { #if 1 // x*a + y*b + z*d + w*e __m128 x = _mm_set1_ps(vec.x); __m128 y = _mm_set1_ps(vec.y); __m128 z = _mm_set1_ps(vec.z); __m128 w = _mm_set1_ps(1.0f); __m128 col1 = _mm_set_ps(m[0][0], m[0][1], m[0][2], m[0][3]); __m128 col2 = _mm_set_ps(m[1][0], m[1][1], m[1][2], m[1][3]); __m128 col3 = _mm_set_ps(m[2][0], m[2][1], m[2][2], m[2][3]); __m128 col4 = _mm_set_ps(m[3][0], m[3][1], m[3][2], m[3][3]); __m128 ans = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x, col1), _mm_mul_ps(y, col2)), _mm_add_ps(_mm_mul_ps(z, col3), _mm_mul_ps(w, col4))); vec3 out{ans.m128_f32[3], ans.m128_f32[2], ans.m128_f32[1]}; #else vec3 out(vec.x*m[0][0] + vec.y*m[1][0] + vec.z*m[2][0] + m[3][0], vec.x*m[0][1] + vec.y*m[1][1] + vec.z*m[2][1] + m[3][1], vec.x*m[0][2] + vec.y*m[1][2] + vec.z*m[2][2] + m[3][2]); #endif return out; } inline static vec3 operator*(const vec3& vec, const mat4& m) { #if 1 #if 1 // x*a + y*b + z*d + w*e __m128 x = _mm_set1_ps(vec.x); __m128 y = _mm_set1_ps(vec.y); __m128 z = _mm_set1_ps(vec.z); __m128 w = _mm_set1_ps(1.0f); __m128 col1 = _mm_set_ps(m[0][0], m[1][0], m[2][0], m[3][0]); __m128 col2 = _mm_set_ps(m[0][1], m[1][1], m[2][1], m[3][1]); __m128 col3 = _mm_set_ps(m[0][2], m[1][2], m[2][2], m[3][2]); __m128 col4 = _mm_set_ps(m[0][3], m[1][3], m[2][3], m[3][3]); __m128 ans = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x, col1), _mm_mul_ps(y, col2)), _mm_add_ps(_mm_mul_ps(z, col3), _mm_mul_ps(w, col4))); #else __m128 col = _mm_set_ps(vec.x, vec.y, vec.z, 1.0f); __m128 row1 = _mm_load_ps(&m[0][0]); __m128 row2 = _mm_load_ps(&m[0][1]); __m128 row3 = _mm_load_ps(&m[0][2]); __m128 row4 = _mm_load_ps(&m[0][3]); __m128 ans = _mm_add_ps(_mm_add_ps(_mm_mul_ps(row1, col), _mm_mul_ps(row2, col)), _mm_add_ps(_mm_mul_ps(row3, col), _mm_mul_ps(row4, col))); #endif vec3 out{ans.m128_f32[3], ans.m128_f32[2], ans.m128_f32[1]}; #else vec3 out(vec.x*m[0][0] + vec.y*m[1][0] + vec.z*m[2][0] + m[3][0], vec.x*m[0][1] + vec.y*m[1][1] + vec.z*m[2][1] + m[3][1], vec.x*m[0][2] + vec.y*m[1][2] + vec.z*m[2][2] + m[3][2]); #endif return out; } inline static vec3 operator+(const vec3& a, const vec3& b) { __m128 avec = _mm_set_ps(a.x, a.y, a.z, 0.0f); __m128 bvec = _mm_set_ps(b.x, b.y, b.z, 0.0f); __m128 out = _mm_add_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } inline static vec3 operator-(const vec3& a, const vec3& b) { __m128 avec = _mm_set_ps(a.x, a.y, a.z, 0.0f); __m128 bvec = _mm_set_ps(b.x, b.y, b.z, 0.0f); __m128 out = _mm_sub_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } inline static vec3 operator/(const vec3& a, float b) { __m128 avec = _mm_set_ps(a.x, a.y, a.z, 0.0f); __m128 bvec = _mm_set_ps(b, b, b, 0.0f); __m128 out = _mm_div_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } inline static vec3 operator*(const vec3& a, float b) { __m128 avec = _mm_set_ps(a.x, a.y, a.z, 0.0f); __m128 bvec = _mm_set_ps(b, b, b, 0.0f); __m128 out = _mm_mul_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } //Does the hadamard product inline static vec3 operator*(const vec3& a, const vec3& b) { __m128 avec = _mm_set_ps(a.x, a.y, a.z, 0.0f); __m128 bvec = _mm_set_ps(b.x, b.y, b.z, 0.0f); __m128 out = _mm_mul_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } inline static vec3 operator*(float a, const vec3& b) { __m128 avec = _mm_set_ps(a, a, a, 0.0f); __m128 bvec = _mm_set_ps(b.x, b.y, b.z, 0.0f); __m128 out = _mm_mul_ps(avec, bvec); return vec3{out.m128_f32[3], out.m128_f32[2], out.m128_f32[1]}; } #endif #define self (*this) template<class T> tvec3<T> tmat4<T>::translation() const { return tvec3<T>{self[3][0], self[3][1], self[3][2]}; } template<class T> tvec3<T> tmat4<T>::scaling() const { return tvec3<T>{self[0][0], self[1][1], self[2][2]}; } #undef self template<class T> inline static std::ostream& operator<<(std::ostream& o, const tvec3<T>& b) { o << "x: "<<b.x<<" y: "<<b.y<<" z: "<<b.z; return o; } template <class T> static tvec3<T> cross(const tvec3<T>& a, const tvec3<T>& b) { return tvec3<T>(a).cross(b); } template <class T> static T dot(const tvec3<T>& a, const tvec3<T>& b) { return a.dot(b); } /* template <class T> static tmat3<T> outer(const tvec3<T>& a, const tvec3<T>& b) { return a.outer(b); } */ template<class T> static tvec3<T> Mix(const tvec3<T>& a, const tvec3<T>& b, T amt) { return a.mix(b, amt); } #endif // VEC3_HPP
24.208955
141
0.613671
[ "vector", "transform" ]
196510e6f2adeec7a98dd6eb4f7d5793932c249c
3,834
hpp
C++
src/mirrage/asset/include/mirrage/asset/stream.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/asset/include/mirrage/asset/stream.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/asset/include/mirrage/asset/stream.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
/** iostreams for assets ***************************************************** * * * Copyright (c) 2014 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <mirrage/asset/aid.hpp> #include <mirrage/utils/log.hpp> #include <mirrage/utils/maybe.hpp> #include <mirrage/utils/template_utils.hpp> #include <plog/Log.h> #include <gsl/gsl> #include <iostream> #include <memory> #include <string> #include <vector> namespace mirrage::asset { struct File_handle; class Asset_manager; class stream { public: stream(AID aid, Asset_manager& manager, File_handle* file, const std::string& path); stream(stream&&); stream(const stream&) = delete; ~stream() noexcept; stream& operator=(const stream&) = delete; stream& operator =(stream&&) noexcept; auto length() const noexcept -> size_t; auto aid() const noexcept { return _aid; } auto& manager() noexcept { return _manager; } void close(); protected: File_handle* _file; AID _aid; Asset_manager& _manager; class fbuf; std::unique_ptr<fbuf> _fbuf; }; class istream : public stream, public std::istream { public: istream(AID aid, Asset_manager& manager, const std::string& path); istream(istream&&); auto operator=(istream &&) -> istream&; auto lines() -> std::vector<std::string>; auto content() -> std::string; auto bytes() -> std::vector<char>; // low-level direct read operation (without intermediate buffer). Disturbs normal stream operation // No further reads allowed after this operation! void read_direct(char* target, std::size_t size); }; class ostream : public stream, public std::ostream { public: ostream(AID aid, Asset_manager& manager, const std::string& path); ostream(ostream&&); ~ostream(); auto operator=(ostream &&) -> ostream&; }; } // namespace mirrage::asset #ifdef ENABLE_SF2_ASSETS #include <sf2/sf2.hpp> namespace mirrage::asset { /** * Specialize this template for each asset-type * Instances should be lightweight * Implementations should NEVER return nullptr */ template <class T> struct Loader { static_assert(sf2::is_loadable<T, sf2::format::Json_reader>::value, "Required AssetLoader specialization not provided."); static auto load(istream in) -> T { auto r = T(); sf2::deserialize_json( in, [&](auto& msg, uint32_t row, uint32_t column) { LOG(plog::error) << "Error parsing JSON from " << in.aid().str() << " at " << row << ":" << column << ": " << msg; }, r); return r; } static void save(ostream out, const T& asset) { sf2::serialize_json(out, asset); } }; } // namespace mirrage::asset #else namespace mirrage::asset { /** * Specialize this template for each asset-type * Instances should be lightweight * Implementations should NEVER return nullptr */ template <class T> struct Loader { static_assert(util::dependent_false<T>(), "Required AssetLoader specialization not provided."); static auto load(istream in) -> T; static void save(ostream out, const T& asset); }; } // namespace mirrage::asset #endif namespace mirrage::asset { using Bytes = std::vector<char>; template <> struct Loader<Bytes> { static auto load(istream in) -> Bytes { return in.bytes(); } void save(ostream out, const Bytes& data) { out.write(data.data(), gsl::narrow<std::streamsize>(data.size())); } }; } // namespace mirrage::asset
26.260274
100
0.603026
[ "vector" ]
19685fac20e212ad308b6e4cc3cce89a23e38fda
26,242
cpp
C++
simcore/simulation/library/bead_spring.cpp
lamsoa729/simcore
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
[ "MIT" ]
null
null
null
simcore/simulation/library/bead_spring.cpp
lamsoa729/simcore
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
[ "MIT" ]
null
null
null
simcore/simulation/library/bead_spring.cpp
lamsoa729/simcore
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
[ "MIT" ]
null
null
null
#include "bead_spring.hpp" BeadSpring::BeadSpring() : Mesh() { SetParameters(); } void BeadSpring::SetParameters() { color_ = params_->bead_spring.color; draw_ = draw_type::_from_string(params_->bead_spring.draw_type.c_str()); length_ = params_->bead_spring.length; persistence_length_ = params_->bead_spring.persistence_length; diameter_ = params_->bead_spring.diameter; max_bond_length_ = params_->bead_spring.max_bond_length; bond_rest_length_ = params_->bead_spring.bond_rest_length; bond_spring_ = params_->bead_spring.bond_spring; driving_factor_ = params_->bead_spring.driving_factor; stoch_flag_ = params_->stoch_flag; // determines whether we are using stochastic forces eq_steps_ = params_->n_steps_equil; eq_steps_count_ = 0; } void BeadSpring::Init() { InitElements(); InsertBeadSpring(); UpdatePrevPositions(); CalculateAngles(); SetDiffusion(); } void BeadSpring::InitElements() { n_bonds_max_ = (int)ceil(length_ / (bond_rest_length_)); Reserve(n_bonds_max_); // Allocate control structures int n_sites_max = n_bonds_max_ + 1; cos_thetas_.resize(n_sites_max - 2); // max_sites-2 } void BeadSpring::GenerateProbableOrientation() { /* This updates the current orientation with a generated probable orientation where we generate random theta pulled from probability distribution P(th) = exp(k cos(th)) where k is the persistence_length of the filament If k is too large, there is enormous imprecision in this calculation since sinh(k) is very large so to fix this I introduce an approximate distribution that is valid for large k */ double theta; if (persistence_length_ == 0) { theta = gsl_rng_uniform_pos(rng_.r) * M_PI; } else if (persistence_length_ < 100) { theta = acos(log(exp(-persistence_length_ / bond_length_) + 2.0 * gsl_rng_uniform_pos(rng_.r) * sinh(persistence_length_ / bond_length_)) / (persistence_length_ / bond_length_)); } else { theta = acos((log(2.0 * gsl_rng_uniform_pos(rng_.r)) - log(2.0) + persistence_length_ / bond_length_) / (persistence_length_ / bond_length_)); } double new_orientation[3] = {0, 0, 0}; if (n_dim_ == 2) { theta = (gsl_rng_uniform_int(rng_.r, 2) == 0 ? -1 : 1) * theta; new_orientation[0] = cos(theta); new_orientation[1] = sin(theta); } else { double phi = gsl_rng_uniform_pos(rng_.r) * 2.0 * M_PI; new_orientation[0] = sin(theta) * cos(phi); new_orientation[1] = sin(theta) * sin(phi); new_orientation[2] = cos(theta); } rotate_vector_relative(n_dim_, new_orientation, orientation_); std::copy(new_orientation, new_orientation + 3, orientation_); } void BeadSpring::InsertFirstBond() { if (params_->bead_spring.insertion_type.compare("random") == 0) { InitRandomSite(diameter_); AddRandomBondToTip(bond_length_); } else if (params_->bead_spring.insertion_type.compare("random_oriented") == 0) { InitRandomSite(diameter_); std::fill(orientation_, orientation_ + 3, 0.0); orientation_[n_dim_ - 1] = (gsl_rng_uniform_pos(rng_.r) > 0.5 ? 1.0 : -1.0); AddBondToTip(orientation_, bond_length_); } else if (params_->bead_spring.insertion_type.compare("centered_oriented") == 0) { std::fill(position_, position_ + 3, 0.0); position_[n_dim_ - 1] = -0.5 * length_; InitSiteAt(position_, diameter_); std::fill(orientation_, orientation_ + 3, 0.0); orientation_[n_dim_ - 1] = 1.0; AddBondToTip(orientation_, bond_length_); } else if (params_->bead_spring.insertion_type.compare("centered_random") == 0) { generate_random_unit_vector(n_dim_, orientation_, rng_.r); for (int i = 0; i < n_dim_; ++i) { position_[i] = -0.5 * length_ * orientation_[i]; } InitSiteAt(position_, diameter_); AddBondToTip(orientation_, bond_length_); } } void BeadSpring::InsertBeadSpring() { bond_length_ = bond_rest_length_; Clear(); InsertFirstBond(); SetOrientation(bonds_[n_bonds_ - 1].GetOrientation()); bool probable_orientation = (params_->bead_spring.insertion_type.compare("simple_crystal") != 0 && params_->bead_spring.insertion_type.compare("random_oriented") != 0); for (int i = 0; i < n_bonds_max_ - 1; ++i) { if (probable_orientation) { GenerateProbableOrientation(); } AddBondToTip(orientation_, bond_length_); } for (bond_iterator bond = bonds_.begin(); bond != bonds_.end(); ++bond) { bond->SetColor(color_, draw_); } UpdateBondPositions(); UpdateSiteOrientations(); } void BeadSpring::InsertAt(double *pos, double *u) { bond_length_ = bond_rest_length_; for (int i = 0; i < n_dim_; ++i) { position_[i] = pos[i] - 0.5 * length_ * u[i]; } InitSiteAt(position_, diameter_); std::copy(u, u + 3, orientation_); AddBondToTip(orientation_, bond_length_); SetOrientation(bonds_[n_bonds_ - 1].GetOrientation()); for (int i = 0; i < n_bonds_max_ - 1; ++i) { if (params_->bead_spring.insertion_type.compare("simple_crystal") != 0) { GenerateProbableOrientation(); } AddBondToTip(orientation_, bond_length_); } UpdateBondPositions(); UpdateSiteOrientations(); UpdatePrevPositions(); CalculateAngles(); SetDiffusion(); } void BeadSpring::SetDiffusion() { rand_sigma_ = sqrt(24.0 * diameter_ / delta_); } double const BeadSpring::GetVolume() { if (n_dim_ == 2) { return diameter_ * length_ + 0.25 * M_PI * diameter_ * diameter_; } if (n_dim_ == 3) { return 0.25 * M_PI * diameter_ * diameter_ * length_ + 1.0 / 6.0 * M_PI * diameter_ * diameter_ * diameter_; } } void BeadSpring::UpdatePosition(bool midstep) { // ApplyForcesTorques(); Integrate(midstep); eq_steps_count_++; } /******************************************************************************* BD algorithm for inextensible wormlike chains with anisotropic friction Montesi, Morse, Pasquali. J Chem Phys 122, 084903 (2005). ********************************************************************************/ void BeadSpring::Integrate(bool midstep) { CalculateAngles(); CalculateTangents(); if (midstep) { CalcRandomForces(); UpdatePrevPositions(); } AddRandomForces(); AddBendingForces(); AddSpringForces(); UpdateSitePositions(midstep); UpdateBondPositions(); UpdateSiteOrientations(); } // void BeadSpring::UpdatePrevPositions() { // for (int i_site=0;i_site<n_sites_;++i_site) { // sites_[i_site].SetPrevPosition(sites_[i_site].GetPosition()); //} //} void BeadSpring::UpdateSiteOrientations() { for (int i = 0; i < n_sites_ - 1; ++i) { sites_[i].SetOrientation(bonds_[i].GetOrientation()); } sites_[n_sites_ - 1].SetOrientation(bonds_[n_bonds_ - 1].GetOrientation()); } void BeadSpring::CalculateAngles() { double cos_angle; for (int i_site = 0; i_site < n_sites_ - 2; ++i_site) { double const *const u1 = sites_[i_site].GetOrientation(); double const *const u2 = sites_[i_site + 1].GetOrientation(); cos_angle = dot_product(n_dim_, u1, u2); cos_thetas_[i_site] = cos_angle; } } void BeadSpring::CalculateTangents() { for (auto it = sites_.begin(); it != sites_.end(); ++it) { it->CalcTangent(); } } void BeadSpring::CalcRandomForces() { if (!stoch_flag_) return; for (int i_site = 0; i_site < n_sites_; ++i_site) { for (int i = 0; i < n_dim_; ++i) { double kick = gsl_rng_uniform_pos(rng_.r) - 0.5; force_[i] = kick * rand_sigma_; } sites_[i_site].SetRandomForce(force_); } } void BeadSpring::AddRandomForces() { if (!stoch_flag_) return; for (int i_site = 0; i_site < n_sites_; ++i_site) { sites_[i_site].AddRandomForce(); } } void BeadSpring::AddBendingForces() { /* These forces are calculated from the potential U = k(theta-pi)^2 where * theta is the angle between two neighboring bonds consisting of three * beads. I will include the derivation of the site forces in the * documentation (JMM 20171215) */ for (int i_theta = 0; i_theta < n_bonds_ - 1; ++i_theta) { double udotu = cos_thetas_[i_theta]; double kappa; if (1 - udotu < 1e-10) { kappa = 0; } else { kappa = -2 * persistence_length_ * (acos(cos_thetas_[i_theta]) - M_PI) / sqrt(1 - SQR(cos_thetas_[i_theta])); } double linv1 = 1.0 / bonds_[i_theta].GetLength(); double linv2 = 1.0 / bonds_[i_theta + 1].GetLength(); double const *const u1 = sites_[i_theta].GetOrientation(); double const *const u2 = sites_[i_theta + 1].GetOrientation(); // Forces for the first of three sites, which is part of the force on the // second site for (int i = 0; i < n_dim_; ++i) { force_[i] = kappa * linv1 * linv1 * (-u2[i] + udotu * u1[i]); } sites_[i_theta].AddForce(force_); sites_[i_theta + 1].SubForce(force_); // Forces for the third of three sites, which is part of the force on the // second site for (int i = 0; i < n_dim_; ++i) { force_[i] = kappa * linv2 * linv2 * (u1[i] - udotu * u2[i]); } sites_[i_theta + 2].AddForce(force_); sites_[i_theta + 1].SubForce(force_); } } void BeadSpring::AddSpringForces() { /* FENE springs have the potential U(r) = -1/2 k r_max^2 ln(1 - * ((r-r0)/r_max)^2) */ for (int i_bond = 0; i_bond < n_bonds_; ++i_bond) { double r_diff = bonds_[i_bond].GetLength() - bond_rest_length_; double f_mag = bond_spring_ * r_diff / (1 - SQR(r_diff) / SQR(max_bond_length_)); // double f_mag = bond_spring_ * (r-max_bond_length_); for (int i = 0; i < n_dim_; ++i) { force_[i] = f_mag * sites_[i_bond].GetOrientation()[i]; } sites_[i_bond + 1].SubForce(force_); sites_[i_bond].AddForce(force_); } // for(int i_bond=0; i_bond<n_bonds_; ++i_bond) { // double r = bonds_[i_bond].GetLength(); // double f_mag = bond_spring_ * r / (1 - SQR(r)/SQR(max_bond_length_)); // for (int i=0;i<n_dim_;++i) { // force_[i] = f_mag * sites_[i_bond].GetOrientation()[i]; //} // sites_[i_bond+1].SubForce(force_); // sites_[i_bond].AddForce(force_); //} } void BeadSpring::UpdateSitePositions(bool midstep) { double delta = (midstep ? 0.5 * delta_ : delta_); for (int i_site = 0; i_site < n_sites_; ++i_site) { double const *const f_site = sites_[i_site].GetForce(); double const *const r_prev = sites_[i_site].GetPrevPosition(); for (int i = 0; i < n_dim_; ++i) { position_[i] = r_prev[i] + f_site[i] * delta / diameter_; } sites_[i_site].SetPosition(position_); } // Next, update orientation vectors double u_mag, r_diff[3]; for (int i_site = 0; i_site < n_sites_ - 1; ++i_site) { double const *const r_site1 = sites_[i_site].GetPosition(); double const *const r_site2 = sites_[i_site + 1].GetPosition(); u_mag = 0.0; for (int i = 0; i < n_dim_; ++i) { r_diff[i] = r_site2[i] - r_site1[i]; u_mag += SQR(r_diff[i]); } u_mag = sqrt(u_mag); for (int i = 0; i < n_dim_; ++i) r_diff[i] /= u_mag; sites_[i_site].SetOrientation(r_diff); sites_[i_site].UpdatePeriodic(); } sites_[n_sites_ - 1].SetOrientation(sites_[n_sites_ - 2].GetOrientation()); } void BeadSpring::UpdateAvgPosition() { std::fill(position_, position_ + 3, 0.0); std::fill(orientation_, orientation_ + 3, 0.0); for (auto site_it = sites_.begin(); site_it != sites_.end(); ++site_it) { double const *const site_pos = site_it->GetPosition(); double const *const site_u = site_it->GetOrientation(); for (int i = 0; i < n_dim_; ++i) { position_[i] += site_pos[i]; orientation_[i] += site_u[i]; } } normalize_vector(orientation_, n_dim_); for (int i = 0; i < n_dim_; ++i) { position_[i] /= n_sites_; } } void BeadSpring::ApplyForcesTorques() { ApplyInteractionForces(); } // FIXME void BeadSpring::ApplyInteractionForces() {} // void BeadSpring::Draw(std::vector<graph_struct*> * graph_array) { // for (auto site=sites_.begin(); site!= sites_.end(); ++site) { // site->Draw(graph_array); //} //} // Scale bond and site positions from new unit cell void BeadSpring::ScalePosition() { // scale first bond position using new unit cell bonds_[0].ScalePosition(); // then reposition sites based on first bond position // handle first site double r[3]; double const *const bond_r = bonds_[0].GetPosition(); double const *const bond_u = bonds_[0].GetOrientation(); for (int i = 0; i < n_dim_; ++i) r[i] = bond_r[i] - 0.5 * bond_length_ * bond_u[i]; sites_[0].SetPosition(r); // then handle remaining sites for (int i_site = 1; i_site < n_sites_; ++i_site) { double const *const prev_r = sites_[i_site - 1].GetPosition(); double const *const prev_u = sites_[i_site - 1].GetOrientation(); for (int i = 0; i < n_dim_; ++i) r[i] = prev_r[i] + bond_length_ * prev_u[i]; sites_[i_site].SetPosition(r); } // update remaining bond positions UpdateBondPositions(); } void BeadSpring::GetAvgOrientation(double *au) { double avg_u[3] = {0.0, 0.0, 0.0}; int size = 0; for (auto it = sites_.begin(); it != sites_.end(); ++it) { double const *const u = it->GetOrientation(); for (int i = 0; i < n_dim_; ++i) avg_u[i] += u[i]; size++; } if (size == 0) Logger::Error("Something went wrong in GetAvgOrientation!"); for (int i = 0; i < n_dim_; ++i) avg_u[i] /= size; std::copy(avg_u, avg_u + 3, au); } void BeadSpring::GetAvgPosition(double *ap) { double avg_p[3] = {0.0, 0.0, 0.0}; int size = 0; for (auto it = sites_.begin(); it != sites_.end(); ++it) { double const *const p = it->GetPosition(); for (int i = 0; i < n_dim_; ++i) avg_p[i] += p[i]; size++; } if (size == 0) Logger::Error("Something went wrong in GetAvgPosition!"); for (int i = 0; i < n_dim_; ++i) avg_p[i] /= size; std::copy(avg_p, avg_p + 3, ap); } void BeadSpring::ReportAll() { printf("cos_thetas:\n {"); for (int i = 0; i < n_sites_ - 2; ++i) printf(" %5.5f ", cos_thetas_[i]); printf("}\n"); } /* The spec output for one bead_spring is: diameter length persistence_length n_sites, all site positions */ void BeadSpring::WriteSpec(std::fstream &ospec) { ospec.write(reinterpret_cast<char *>(&diameter_), sizeof(diameter_)); ospec.write(reinterpret_cast<char *>(&length_), sizeof(length_)); ospec.write(reinterpret_cast<char *>(&persistence_length_), sizeof(persistence_length_)); ospec.write(reinterpret_cast<char *>(&n_sites_), sizeof(n_sites_)); double temp[3]; for (int i = 0; i < n_sites_; ++i) { double const *const pos = sites_[i].GetPosition(); std::copy(pos, pos + 3, temp); for (auto &p : temp) ospec.write(reinterpret_cast<char *>(&p), sizeof(p)); } return; } void BeadSpring::ReadSpec(std::fstream &ispec) { if (ispec.eof()) return; double r_site[3]; ispec.read(reinterpret_cast<char *>(&diameter_), sizeof(diameter_)); ispec.read(reinterpret_cast<char *>(&length_), sizeof(length_)); ispec.read(reinterpret_cast<char *>(&persistence_length_), sizeof(persistence_length_)); ispec.read(reinterpret_cast<char *>(&n_sites_), sizeof(n_sites_)); sites_.resize(n_sites_, sites_[0]); // Get initial site position // Initialize sites from relative positions for (int i_site = 0; i_site < n_sites_; ++i_site) { for (int i = 0; i < 3; ++i) ispec.read(reinterpret_cast<char *>(&r_site[i]), sizeof(double)); sites_[i_site].SetPosition(r_site); } UpdateBondPositions(); UpdateSiteOrientations(); UpdatePrevPositions(); CalculateAngles(); } void BeadSpring::WritePosit(std::fstream &oposit) { double avg_pos[3], avg_u[3]; GetAvgPosition(avg_pos); GetAvgOrientation(avg_u); std::copy(avg_pos, avg_pos + 3, position_); UpdatePeriodic(); for (auto &pos : position_) oposit.write(reinterpret_cast<char *>(&pos), sizeof(pos)); for (auto &spos : scaled_position_) oposit.write(reinterpret_cast<char *>(&spos), sizeof(spos)); for (auto &u : avg_u) oposit.write(reinterpret_cast<char *>(&u), sizeof(u)); oposit.write(reinterpret_cast<char *>(&diameter_), sizeof(diameter_)); oposit.write(reinterpret_cast<char *>(&length_), sizeof(length_)); } void BeadSpring::ReadPosit(std::fstream &iposit) { if (iposit.eof()) return; double avg_pos[3], avg_u[3], s_pos[3]; for (int i = 0; i < 3; ++i) iposit.read(reinterpret_cast<char *>(&avg_pos[i]), sizeof(double)); for (int i = 0; i < 3; ++i) iposit.read(reinterpret_cast<char *>(&s_pos[i]), sizeof(double)); for (int i = 0; i < 3; ++i) iposit.read(reinterpret_cast<char *>(&avg_u[i]), sizeof(double)); iposit.read(reinterpret_cast<char *>(&diameter_), sizeof(diameter_)); iposit.read(reinterpret_cast<char *>(&length_), sizeof(length_)); // Initialize first bond position for (int i = 0; i < n_dim_; ++i) avg_pos[i] = avg_pos[i] - 0.5 * (length_ - bond_length_) * avg_u[i]; for (int i_bond = 0; i_bond < n_bonds_; ++i_bond) { bonds_[i_bond].SetPosition(avg_pos); bonds_[i_bond].SetOrientation(avg_u); bonds_[i_bond].SetDiameter(diameter_); bonds_[i_bond].UpdatePeriodic(); // Set next bond position for (int i = 0; i < n_dim_; ++i) avg_pos[i] += bond_length_ * avg_u[i]; } } void BeadSpring::WriteCheckpoint(std::fstream &ocheck) { void *rng_state = gsl_rng_state(rng_.r); size_t rng_size = gsl_rng_size(rng_.r); ocheck.write(reinterpret_cast<char *>(&rng_size), sizeof(size_t)); ocheck.write(reinterpret_cast<char *>(rng_state), rng_size); WriteSpec(ocheck); } void BeadSpring::ReadCheckpoint(std::fstream &icheck) { if (icheck.eof()) return; void *rng_state = gsl_rng_state(rng_.r); size_t rng_size; icheck.read(reinterpret_cast<char *>(&rng_size), sizeof(size_t)); icheck.read(reinterpret_cast<char *>(rng_state), rng_size); ReadSpec(icheck); n_sites_ = n_bonds_ + 1; double r[3]; for (int i = 0; i < 3; ++i) r[i] = bonds_[0].GetPosition()[i] - 0.5 * bond_length_ * bonds_[0].GetOrientation()[i]; sites_[0].SetPosition(r); sites_[0].SetOrientation(bonds_[0].GetOrientation()); for (int i_bond = 1; i_bond < n_bonds_; ++i_bond) { for (int i = 0; i < 3; ++i) r[i] += bond_length_ * sites_[i_bond - 1].GetOrientation()[i]; sites_[i_bond].SetPosition(r); sites_[i_bond].SetOrientation(bonds_[i_bond].GetOrientation()); } for (int i = 0; i < 3; ++i) r[i] += bond_length_ * sites_[n_sites_ - 2].GetOrientation()[i]; sites_[n_sites_ - 1].SetPosition(r); sites_[n_sites_ - 1].SetOrientation(bonds_[n_bonds_ - 1].GetOrientation()); UpdateBondPositions(); // Reallocate control structures cos_thetas_.resize(n_sites_ - 2); // max_sites-2 } void BeadSpringSpecies::InitAnalysis() { time_ = 0; // if (params_->bead_spring.diffusion_analysis) { // InitDiffusionAnalysis(); //} if (params_->bead_spring.theta_analysis) { InitThetaAnalysis(); } if (params_->bead_spring.lp_analysis) { InitMse2eAnalysis(); } RunAnalysis(); } void BeadSpringSpecies::InitMse2eAnalysis() { std::string fname = params_->run_name; fname.append("_bead_spring.mse2e"); mse2e_file_.open(fname, std::ios::out); mse2e_file_ << "mse2e_analysis_file\n"; mse2e_file_ << "length diameter bond_length persistence_length driving ndim " "nsteps nspec delta\n"; auto it = members_.begin(); double l = it->GetLength(); double d = it->GetDiameter(); double cl = it->GetBondLength(); double pl = it->GetPersistenceLength(); double dr = it->GetDriving(); double nspec = GetNSpec(); double theory; if (params_->n_dim == 2) { theory = l * pl * 4.0 - 8.0 * pl * pl * (1 - exp(-0.5 * l / pl)); } else { theory = l * pl * 2.0 - 2.0 * pl * pl * (1 - exp(-l / pl)); } mse2e_file_ << l << " " << d << " " << cl << " " << pl << " " << dr << " " << params_->n_dim << " " << params_->n_steps << " " << nspec << " " << params_->delta << "\n"; mse2e_file_ << "num_bead_springs_averaged mse2e_mean mse2e_std_err " "avg_contour_length theory\n"; mse2e_ = 0; mse2e2_ = 0; n_samples_ = 0; avg_clen_ = 0; } void BeadSpringSpecies::InitDiffusionAnalysis() { std::string fname = params_->run_name; fname.append("_bead_spring.diffusion"); mse2e_file_.open(fname, std::ios::out); mse2e_file_ << "mse2e_analysis_file\n"; mse2e_file_ << "length diameter bond_length persistence_length driving ndim " "nsteps nspec delta theory\n"; auto it = members_.begin(); double l = it->GetLength(); double d = it->GetDiameter(); double cl = it->GetBondLength(); double pl = it->GetPersistenceLength(); double dr = it->GetDriving(); double nspec = GetNSpec(); double theory; if (params_->n_dim == 2) { theory = l * pl * 4.0 - 8.0 * pl * pl * (1 - exp(-0.5 * l / pl)); } else { theory = l * pl * 2.0 - 2.0 * pl * pl * (1 - exp(-l / pl)); } mse2e_file_ << l << " " << d << " " << cl << " " << pl << " " << dr << " " << params_->n_dim << " " << params_->n_steps << " " << nspec << " " << params_->delta << " " << theory << "\n"; mse2e_file_ << "num_bead_springs_averaged mse2e_mean mse2e_std_err\n"; mse2e_ = 0.0; mse2e2_ = 0.0; n_samples_ = 0; } void BeadSpringSpecies::InitThetaAnalysis() { // TODO Should check to make sure the same lengths, child lengths, persistence // lengths, etc are used for each bead_spring in system. std::string fname = params_->run_name; fname.append("_bead_spring.theta"); theta_file_.open(fname, std::ios::out); theta_file_ << "theta_analysis_file\n"; theta_file_ << "length diameter bond_length persistence_length " "n_bead_springs n_bonds n_steps n_spec delta n_dim \n"; double l, cl, pl, dr, d; int nbonds; int nmembers = members_.size(); for (auto it = members_.begin(); it != members_.end(); ++it) { l = it->GetLength(); d = it->GetDiameter(); cl = it->GetBondLength(); pl = it->GetPersistenceLength(); dr = it->GetDriving(); nbonds = it->GetNBonds(); } int nspec = GetNSpec(); theta_file_ << l << " " << d << " " << cl << " " << pl << " " << dr << " " << nmembers << " " << nbonds << " " << params_->n_steps << " " << nspec << " " << params_->delta << " " << params_->n_dim << " " << "\n"; theta_file_ << "cos_theta"; for (int i = 0; i < nbonds - 1; ++i) { theta_file_ << " theta_" << i + 1 << i + 2; } theta_file_ << "\n"; n_bins_ = 10000; int nfil = members_.size(); theta_histogram_ = new int *[nbonds - 1]; for (int ibond = 0; ibond < nbonds - 1; ++ibond) { theta_histogram_[ibond] = new int[n_bins_]; for (int ibin = 0; ibin < n_bins_; ++ibin) { theta_histogram_[ibond][ibin] = 0; } } } void BeadSpringSpecies::RunAnalysis() { // TODO Analyze conformation and ms end-to-end if (params_->bead_spring.theta_analysis) { if (params_->interaction_flag) { std::cout << "WARNING! Theta analysis running on interacting bead_springs!\n"; } RunThetaAnalysis(); } if (params_->bead_spring.lp_analysis) { RunMse2eAnalysis(); } time_++; } void BeadSpringSpecies::RunMse2eAnalysis() { // Treat as though we have many spirals for now // if ( ! mse2e_file_.is_open()) { // early_exit = true; // std::cout << " Error! Problem opening file in RunMse2eAnalysis! // Exiting.\n"; //} // mse2e_file_ << time_; for (auto it = members_.begin(); it != members_.end(); ++it) { double const *const head_pos = it->GetHeadPosition(); double const *const tail_pos = it->GetTailPosition(); double mse2e_temp = 0.0; for (int i = 0; i < params_->n_dim; ++i) { double temp = (head_pos[i] - tail_pos[i]); mse2e_temp += temp * temp; } mse2e_ += mse2e_temp; mse2e2_ += mse2e_temp * mse2e_temp; // mse2e_file_ << " " << mse2e ; avg_clen_ += it->GetContourLength(); } // mse2e_ /= members_.size(); // mse2e2_ /= members_.size(); // mse2e_file_ << "\n"; n_samples_++; } void BeadSpringSpecies::RunThetaAnalysis() { for (auto it = members_.begin(); it != members_.end(); ++it) { std::vector<double> const *const thetas = it->GetThetas(); for (int i = 0; i < (it->GetNBonds() - 1); ++i) { int bin_number = (int)floor((1 + (*thetas)[i]) * (n_bins_ / 2)); if (bin_number == n_bins_) { bin_number = n_bins_ - 1; } else if (bin_number == -1) { bin_number = 0; } else if (bin_number > n_bins_ && bin_number < 0) { Logger::Error("Something went wrong in RunThetaAnalysis!"); } theta_histogram_[i][bin_number]++; } } } void BeadSpringSpecies::FinalizeAnalysis() { if (spiral_file_.is_open()) { spiral_file_.close(); } if (theta_file_.is_open()) { FinalizeThetaAnalysis(); theta_file_.close(); } if (mse2e_file_.is_open()) { FinalizeMse2eAnalysis(); mse2e_file_.close(); } if (diffusion_file_.is_open()) { // FinalizeDiffusionAnalysis(); diffusion_file_.close(); } } void BeadSpringSpecies::FinalizeMse2eAnalysis() { int num = members_.size(); mse2e_file_ << num << " "; mse2e_ /= n_samples_ * num; mse2e2_ /= n_samples_ * num; mse2e_file_ << mse2e_ << " "; mse2e_file_ << sqrt((mse2e2_ - mse2e_ * mse2e_) / (num * n_samples_)) << " "; avg_clen_ /= n_samples_ * num; double pl = params_->bead_spring.persistence_length; double theory; if (params_->n_dim == 2) { theory = avg_clen_ * pl * 4.0 - 8.0 * pl * pl * (1 - exp(-0.5 * avg_clen_ / pl)); } else { theory = avg_clen_ * pl * 2.0 - 2.0 * pl * pl * (1 - exp(-avg_clen_ / pl)); } mse2e_file_ << avg_clen_ << " " << theory << "\n"; } void BeadSpringSpecies::FinalizeThetaAnalysis() { int nbonds = members_[members_.size() - 1].GetNBonds(); for (int i = 0; i < n_bins_; ++i) { double axis = (2.0 / n_bins_) * i - 1; theta_file_ << " " << axis; for (int ibond = 0; ibond < nbonds - 1; ++ibond) { theta_file_ << " " << theta_histogram_[ibond][i]; } theta_file_ << "\n"; } for (int ibond = 0; ibond < nbonds - 1; ++ibond) { delete[] theta_histogram_[ibond]; } delete[] theta_histogram_; }
34.896277
81
0.634784
[ "mesh", "vector" ]
196a2f251f6ee86c069b1a6c19c2a282d78eb245
3,320
cpp
C++
Trem/src/trem/renderer/camera.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
10
2021-01-17T01:48:31.000Z
2021-12-31T19:31:22.000Z
Trem/src/trem/renderer/camera.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
null
null
null
Trem/src/trem/renderer/camera.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
null
null
null
#include "trpch.h" #include "camera.h" namespace Trem { Camera::Camera(float left, float right, float bottom, float top) { //create the cameras transform (view matrix) and the projection matrix for the entire scene //and combine them into the view-projection matrix viewMatrix_ = glm::translate(glm::mat4{1.f}, position_) * glm::rotate(glm::mat4{1.f}, rotationAngle_, {0.f, 0.f, 1.f}); projectionMatrix_ = glm::ortho(left, right, bottom, top, 1.f, -1.f); viewProjectionMatrix_ = projectionMatrix_ * glm::inverse(viewMatrix_); } void Camera::move(KeyEvent* ev) { glm::vec3 camMovement{0.f}; float camSpeed = 5.f; switch (ev->keycode()) { case Key::W: camMovement.y = camSpeed; break; case Key::S: camMovement.y = -camSpeed; break; case Key::A: camMovement.x = -camSpeed; break; case Key::D: camMovement.x = camSpeed; break; } setPosition(position_ + camMovement); Logger::logger()->info("camera moved to x:{0}, y:{1}", position_.x, position_.y); } //setters void Camera::setProjectionMatrix(const glm::mat4& projectionMatrix) { projectionMatrix_ = projectionMatrix; calculateViewProjectionMatrix(); } void Camera::setViewMatrix(const glm::mat4& viewMatrix) { viewMatrix_ = viewMatrix; calculateViewProjectionMatrix(); } void Camera::setEventCallback(const std::function<void(Event&)>& callback) { eventCallback_ = callback; } void Camera::setPosition(const glm::vec3& position) { position_ = position; calculateViewProjectionMatrix(); } void Camera::setRotation(const float rotationAngle) { rotationAngle_ = rotationAngle; calculateViewProjectionMatrix(); } void Camera::calculateProjectionMatrix(float left, float right, float bottom, float top) { projectionMatrix_ = glm::ortho(left, right, bottom, top, 1.f, -1.f); calculateViewProjectionMatrix(); } void Camera::calculateViewProjectionMatrix() { viewMatrix_ = glm::translate(glm::mat4{1.f}, position_) * glm::rotate(glm::mat4{1.f}, rotationAngle_, {0.f, 0.f, 1.f}); //needs to be inverse because the position of each object multiplied with the matrix //needs to be moved to the opposite direction of the cameras movement viewProjectionMatrix_ = projectionMatrix_ * glm::inverse(viewMatrix_); } //getters glm::vec3 Camera::position() const { return position_; } glm::mat4 Camera::viewMatrix() const { return viewMatrix_; } glm::mat4 Camera::projectionMatrix() const { return projectionMatrix_; } glm::mat4 Camera::viewProjectionMatrix() const { return viewProjectionMatrix_; } bool Camera::handleEvent(Event& ev) { if(ev.inCategory(EventCategory::KeyboardEvent)) { KeyEvent* keyEvent = static_cast<KeyEvent*>(&ev); move(keyEvent); } if(ev.type() == EventType::WindowResized) { WindowResizedEvent* windowResizedEvent = static_cast<WindowResizedEvent*>(&ev); float right = static_cast<float>(windowResizedEvent->windowSize_.x); float top = static_cast<float>(windowResizedEvent->windowSize_.y); calculateProjectionMatrix(0.f, right, 0.f, top); } return false; } }
27.438017
133
0.664759
[ "object", "transform" ]
196de90c92af4c2cdab9245fe21c92021a506552
2,298
cpp
C++
Old 2P/skiiingresort/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
Old 2P/skiiingresort/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
Old 2P/skiiingresort/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <math.h> #define int long long #include <bits/stdc++.h> using namespace std; vector<int> dijkstra(int start, vector<vector<pair<int,int> > > &graph){ int n = (int)graph.size(); priority_queue<pair<int,int> > pq; vector<int> dist(n,-1); pq.push({0,start}); dist[start] = 0; while(pq.size() != 0){ int distance = -pq.top().first; int pos = pq.top().second; pq.pop(); if(dist[pos] != -1 && dist[pos] < distance){ continue; } for(int i=0; i < (int) graph[pos].size();i++){ int next = graph[pos][i].first; int edge = graph[pos][i].second; if(dist[next] != -1 && dist[next] <= distance+edge){ continue; } dist[next] = distance+edge; pq.push({-(distance+edge), next}); } } return dist; } signed main() { int numberOfCrossings, numberOfLifts, numberOfPists; cin >> numberOfCrossings >> numberOfLifts >> numberOfPists; //ios_base::sync_with_stdio(false); //cin.tie(0); //This will be in the form of maximal time till they have to be on the ofen, for how long and index vector<vector<pair<int,int> > > pists(numberOfCrossings); vector<vector<pair<int,int> > > lifts(numberOfCrossings); vector<vector<int>> toLifts(numberOfCrossings); vector<int> roots; for (int i = 0; i < numberOfLifts; ++i) { int firstCrossing, secondCrossing, time; cin >>firstCrossing >> secondCrossing >> time; lifts[firstCrossing].push_back(make_pair(secondCrossing, time)); toLifts[secondCrossing].push_back(firstCrossing); } int removedEntries vector<string> output; int currentTime = 0; for (int j = 0; j < dyingTable.size(); ++j) { output.push_back(to_string(currentTime)); if(currentTime > dyingTable[j][0]){ cout << "Impossible"; exit(1); } output.push_back(to_string(dyingTable[j][2])); currentTime+=dyingTable[j][1]; } for (int k = 0; k < output.size(); ++k) { if(k%2==1){ cout << output[k] << "\n"; } else{ cout << output[k] << " "; } } }
27.357143
103
0.560923
[ "vector" ]
1976411a59f544ac7fb37788c57a833040cb62ed
20,111
cpp
C++
verify_new.cpp
amkarahalios/cadical
ab54674c7af98a0057cb16f7e1e372effa321e63
[ "MIT" ]
null
null
null
verify_new.cpp
amkarahalios/cadical
ab54674c7af98a0057cb16f7e1e372effa321e63
[ "MIT" ]
null
null
null
verify_new.cpp
amkarahalios/cadical
ab54674c7af98a0057cb16f7e1e372effa321e63
[ "MIT" ]
2
2021-11-09T03:57:59.000Z
2021-11-09T04:24:25.000Z
#include <string> #include <vector> #include <set> #include <fstream> #include <sstream> #include <iostream> #include <cmath> void parse_edge_file(int numberOfColors, std::string inputFileName, int &numVertices, std::vector<std::vector<bool> > &existingEdges) { // Parsing // - Read line by line std::vector<std::pair<int, int> > edges; std::vector<std::vector<bool> > edgeMatrix; int numberOfVertices; std::string line; std::ifstream infile(inputFileName); while (std::getline(infile, line)) { if (line[0] == 'c') { continue; } else if (line[0] == 'p') { std::string buf; std::stringstream ss(line); std::vector<std::string> tokens; while (ss >> buf) { tokens.push_back(buf); } numberOfVertices = std::stoi(tokens[2]); numVertices = numberOfVertices; } else if (line[0] == 'e') { std::string buf; std::stringstream ss(line); std::vector<std::string> tokens; while (ss >> buf) { tokens.push_back(buf); } int vertex1 = std::stoi(tokens[1]); int vertex2 = std::stoi(tokens[2]); edges.push_back(std::make_pair(vertex1, vertex2)); } } // Setup adjacency matrix edgeMatrix.resize(numberOfVertices); for (int vertexNum = 0; vertexNum < numberOfVertices; ++vertexNum) { edgeMatrix[vertexNum].resize(numberOfVertices); for (int vertexNum1 = 0; vertexNum1 < numberOfVertices; ++vertexNum1) { edgeMatrix[vertexNum][vertexNum1] = false; } } for (int edgeIndex = 0; edgeIndex < edges.size(); ++edgeIndex) { const std::pair<int, int> &edge = edges[edgeIndex]; edgeMatrix[edge.first - 1][edge.second - 1] = true; edgeMatrix[edge.second - 1][edge.first - 1] = true; } existingEdges.resize(edgeMatrix.size()); for (int i = 0; i < edgeMatrix.size(); ++i) { existingEdges[i].resize(edgeMatrix.size()); for (int j = 0; j < edgeMatrix.size(); ++j) { existingEdges[i][j] = edgeMatrix[i][j]; } } } std::vector<std::set<int> > getKCliques(int k, std::vector<std::vector<bool> > edgeMatrix) { std::vector<std::set<int> > res; if (k < 2) { return res; } if (k == 2) { for (int i = 0; i < edgeMatrix.size() - 1; i++) { for (int j = i + 1; j < edgeMatrix.size(); j++) { if (edgeMatrix[i][j]) { std::set<int> a; a.insert(i); a.insert(j); res.push_back(a); } } } return res; } else { std::vector<std::set<int> > smallCliques = getKCliques(k - 1, edgeMatrix); for (int i = 0; i < smallCliques.size(); i++) { for (int j = 0; j < edgeMatrix.size(); j++) { if ((smallCliques[i].find(j) == smallCliques[i].end()) && ((*smallCliques[i].rbegin()) < j)) { bool pos = true; for (int t : smallCliques[i]) { if (!edgeMatrix[j][t]) { pos = false; } } if (pos) { std::set<int> b; for (int l : smallCliques[i]) { b.insert(l); } b.insert(j); res.push_back(b); } } } } return res; } } std::set<int> getFirstAlmostKCliques(int k, std::vector<std::vector<bool> > edgeMatrix) { // for (int i = 0; i<edgeMatrix.size();i++) // { // for (int j = 0; j< edgeMatrix.size();j++) // { // std::cout<< edgeMatrix[i][j]; // } // std::cout<< std::endl; // } std::set<int> res; if (k <= 2) { std::set<int> a; a.insert(0); return a; } else { std::vector<std::set<int> > smallCliques = getKCliques(k - 1, edgeMatrix); for (int i = 0; i < smallCliques.size(); i++) { std::cout << "small clique: "; for (int j : smallCliques[i]) { std::cout << j << ","; } std::cout << std::endl; } for (int i = 0; i < smallCliques.size(); i++) { for (int j = 0; j < edgeMatrix.size(); j++) { if (smallCliques[i].find(j) == smallCliques[i].end()) { int s = 0; for (int t : smallCliques[i]) { s += int(edgeMatrix[j][t]); } if (s == k - 2) { for (int l : smallCliques[i]) { res.insert(l); // std::cout << l << " "; } res.insert(j); // std::cout << j << " "; // std::cout << std::endl; return res; } } } } return res; } } //Always merge to the smaller vertex and delete all connections for the larger vertex std::vector<std::vector<bool> > merge(int vertA, int vertB, std::vector<std::vector<bool> > edgeMatrix) { int a = std::min(vertA, vertB); int b = std::max(vertA, vertB); std::vector<std::vector<bool> > res; res.resize(edgeMatrix.size()); for (int i = 0; i < edgeMatrix.size(); i++) { res[i].resize(edgeMatrix[i].size()); if (i == a) { for (int j = 0; j < edgeMatrix[i].size(); j++) { res[i][j] = (edgeMatrix[a][j] || edgeMatrix[b][j]); } } else if (i != b) { for (int j = 0; j < edgeMatrix[i].size(); j++) { if (j == a) { res[i][j] = (edgeMatrix[i][a] || edgeMatrix[i][b]); } else if (j == b) { res[i][b] = 0; } else { res[i][j] = edgeMatrix[i][j]; } } } } return res; } std::vector<std::vector<bool> > addEdge(int vertA, int vertB, std::vector<std::vector<bool> > edgeMatrix) { std::vector<std::vector<bool> > res; res.resize(edgeMatrix.size()); for (int i = 0; i < edgeMatrix.size(); i++) { res[i].resize(edgeMatrix[i].size()); for (int j = 0; j < edgeMatrix[i].size(); j++) { res[i][j] = edgeMatrix[i][j]; } } res[vertA][vertB] = true; res[vertB][vertA] = true; return res; } //if there exists a first almost clique, merge the nodes, return the positive merge literal and the merged graph std::pair<int, std::vector<std::vector<bool> > > mergeFirstAlmostClique(int numColors, std::vector<std::vector<bool> > edgeMatrix, int numVertex) { std::set<int> clik = getFirstAlmostKCliques(numColors + 1, edgeMatrix); if (clik.size()) { std::cout << "Almost Clique:"; for (int i : clik) { std::cout << i << " "; } std::cout << std::endl; int mergeA = -1; int mergeB = -1; for (int i : clik) { for (int j : clik) { if ((i < j) && (!edgeMatrix[i][j])) { // mergePair.push_back(1); mergeA = i; mergeB = j; } } } int mergeLit = numColors * numVertex + std::min(mergeA, mergeB) * numVertex + std::max(mergeA, mergeB) + 1; edgeMatrix = merge(mergeA, mergeB, edgeMatrix); return std::make_pair(mergeLit, edgeMatrix); } else { return std::make_pair(0, edgeMatrix); } } //parse proof file into list of sets std::vector<std::set<int> > parse_proof_file(std::string proofFileName, int numVertex, int numColors) { std::vector<std::set<int> > proof; std::string line; std::ifstream infile(proofFileName); // int count = 0; while (std::getline(infile, line)) { // count++; // std::cout << "proof in " << count << std::endl; if (line[0] == 'd') { continue; } else { std::string buf; std::stringstream ss(line); std::vector<std::string> tokens; while (ss >> buf) { tokens.push_back(buf); } std::set<int> clause; for (int i = 0; i < tokens.size(); i++) { int num = std::stoi(tokens[i]); if ((num != 0) && (std::abs(num) > numVertex * numColors)) { clause.insert(num); } } if (clause.size()) { proof.push_back(clause); } } } return proof; } int set_one_diff(std::set<int> a, std::set<int> b) { if (a.size() == 1) { return *a.begin(); } int diff = 0; for (int i : a) { if (b.find(i) == b.end()) { if (!diff) { diff = i; } else { return 0; } } } return diff; } std::vector<std::vector<int> > convertOpsSet2Vec(std::set<int> ops, int numVertex, int numColors) { std::vector<std::vector<int> > operations; for (int j : ops) { std::vector<int> op; if (j > 0) { op.push_back(-1); } else { op.push_back(1); } //vertNum1, vertNum2 start at 1, while the edgeMatrix is 0-indexed. int vertNum1 = std::ceil((std::abs(j) - numVertex * numColors) * 1.0 / numVertex); int vertNum2 = std::abs(j) - numVertex * (numColors + vertNum1 - 1); op.push_back(vertNum1 - 1); op.push_back(vertNum2 - 1); operations.push_back(op); } return operations; } std::set<int> convertOpsVec2Set(std::vector<std::vector<int> > impliedOps, int numVertex, int numColors) { std::set<int> convertImp; for (int i = 0; i < impliedOps.size(); i++) { int mergeLit = numColors * numVertex + std::min(impliedOps[i][1], impliedOps[i][2]) * numVertex + std::max(impliedOps[i][1], impliedOps[i][2]) + 1; if (impliedOps[i][0] > 0) { convertImp.insert(-mergeLit); } else { convertImp.insert(mergeLit); } } return convertImp; } //operate on the graph. If there is an invalid merge, return false std::pair<bool, std::vector<std::vector<bool> > > batchOperate(std::set<int> ops, std::vector<std::vector<bool> > edgeMatrix, int numVertex, int numColors) { // std::cout <<"here 1" <<std::endl; std::vector<std::vector<int> > operations = convertOpsSet2Vec(ops, numVertex, numColors); // std::cout<< operations.size()<< std::endl; // std::cout <<"here 2" <<std::endl; // std::cout << "in batch operate"<<std::endl; std::vector<std::set<int> > mergeList; for (int i = 0; i < operations.size(); i++) { // std::cout <<operations[i].size() <<std::endl; // std::cout <<"here 3" <<std::endl; if (operations[i][0] == -1) { // std::cout <<"here 4" <<std::endl; // std::cout << operations[i][1]<<std::endl; // std::cout << operations[i][2]<<std::endl; edgeMatrix = addEdge(operations[i][1], operations[i][2], edgeMatrix); } else { // std::cout <<"here 10" <<std::endl; bool inserted = false; for (int j = 0; j < mergeList.size(); j++) { if ((!inserted) && (mergeList[j].find(operations[i][1]) != mergeList[j].end() || mergeList[j].find(operations[i][2]) != mergeList[j].end())) { std::set<int> merges = mergeList[j]; merges.insert(operations[i][1]); merges.insert(operations[i][2]); mergeList[j] = merges; inserted = true; } } // std::cout <<"here 11" <<std::endl; if (!inserted) { // std::cout <<"here 12" <<std::endl; std::set<int> merges; merges.insert(operations[i][1]); merges.insert(operations[i][2]); mergeList.push_back(merges); } } // std::cout <<"here 5" <<std::endl; } // std::cout<<mergeList.size()<<std::endl; //attempt to merge the nodes. If there exists an edge between the nodes, return false for (int k = 0; k < mergeList.size(); k++) { std::set<int> m = mergeList[k]; for (int a : m) { for (int b : m) { if (edgeMatrix[a][b]) { // std::cout <<"here 6" <<std::endl; return std::make_pair(false, edgeMatrix); } } } int vert1 = *m.begin(); std::set<int>::iterator it = m.begin(); it++; // std::cout <<"here 7" <<std::endl; while (it != m.end()) { // std::cout <<"here 8" <<std::endl; edgeMatrix = merge(vert1, *it, edgeMatrix); // std::cout <<"here 9" <<std::endl; it++; } } return std::make_pair(true, edgeMatrix); } std::set<int> findImpliedOperations(std::set<int> ops, std::vector<std::vector<bool> > edgeMatrix, int numVertex, int numColors) { // std::cout << "in batch operate"<<std::endl; std::vector<std::vector<int> > operations = convertOpsSet2Vec(ops, numVertex, numColors); std::vector<std::vector<int> > addList; std::vector<std::set<int> > mergeList; for (int i = 0; i < operations.size(); i++) { if (operations[i][0] == -1) { std::vector<int> addVec; addVec.push_back(operations[i][1]); addVec.push_back(operations[i][2]); addList.push_back(addVec); } else { bool inserted = false; for (int j = 0; j < mergeList.size(); j++) { if ((!inserted) && (mergeList[j].find(operations[i][1]) != mergeList[j].end() || mergeList[j].find(operations[i][2]) != mergeList[j].end())) { std::set<int> merges = mergeList[j]; merges.insert(operations[i][1]); merges.insert(operations[i][2]); mergeList[j] = merges; inserted = true; } } if (!inserted) { std::set<int> merges; merges.insert(operations[i][1]); merges.insert(operations[i][2]); mergeList.push_back(merges); } } } std::vector<std::vector<int> > impliedOps; for (int i = 0; i < addList.size(); i++) { std::set<int> firstSet; firstSet.insert(addList[i][0]); std::set<int> secondSet; secondSet.insert(addList[i][1]); for (int j = 0; j < mergeList.size(); j++) { if (mergeList[j].find(addList[i][0]) != mergeList[j].end()) { firstSet = mergeList[j]; } if (mergeList[j].find(addList[i][1]) != mergeList[j].end()) { secondSet = mergeList[j]; } } for (int a : firstSet) { for (int b : secondSet) { if (a != b) { std::vector<int> op; op.push_back(-1); op.push_back(a); op.push_back(b); impliedOps.push_back(op); } } } } for (int k = 0; k < mergeList.size(); k++) { std::set<int> m = mergeList[k]; for (int a : m) { for (int b : m) { if (a != b) { std::vector<int> op; op.push_back(1); op.push_back(a); op.push_back(b); impliedOps.push_back(op); for (int s = 0; s < edgeMatrix.size(); s++) { if ((edgeMatrix[a][s])) { std::vector<int> op; op.push_back(-1); op.push_back(b); op.push_back(s); impliedOps.push_back(op); } if ((edgeMatrix[b][s])) { std::vector<int> op; op.push_back(-1); op.push_back(a); op.push_back(s); impliedOps.push_back(op); } } } } } } return convertOpsVec2Set(impliedOps, numVertex, numColors); } //return the full list of ops in addition to whether conflict was found std::pair<bool, std::set<int> > conflictAfterOp(std::set<int> ops, std::vector<std::vector<bool> > edgeMatrix, int numColors, int numVertex) { // std::cout <<"here 1" <<std::endl; std::pair<bool, std::vector<std::vector<bool> > > operatedMatrix = batchOperate(ops, edgeMatrix, numVertex, numColors); // std::cout <<"here 2" <<std::endl; if (!operatedMatrix.first) { return std::make_pair(true, ops); } // std::cout <<"here 3" <<std::endl; if (getKCliques(numColors + 1, operatedMatrix.second).size()) { // std::cout <<"here 4" <<std::endl; return std::make_pair(true, ops); } // std::cout <<"here 5" <<std::endl; std::pair<int, std::vector<std::vector<bool> > > litMatrixPair = mergeFirstAlmostClique(numColors, operatedMatrix.second, numVertex); // std::cout <<"here 6" <<std::endl; while (litMatrixPair.first) { ops.insert(-litMatrixPair.first); edgeMatrix = litMatrixPair.second; if (getKCliques(numColors + 1, edgeMatrix).size()) { return std::make_pair(true, ops); } else { litMatrixPair = mergeFirstAlmostClique(numColors, edgeMatrix, numVertex); } } return std::make_pair(false, ops); } bool negates(std::set<int> prev, std::set<int> cur) { bool neg = true; for (int i:prev) { if (cur.find(-i)==cur.end()) { neg = false; break; } } return neg; } bool verify_proof(std::vector<std::set<int> > proof, int numVertex, int numColors, std::vector<std::vector<bool> > edgeMatrix) { std::set<int> emptyClause; proof.push_back(emptyClause); for (int i = 0; i < proof.size(); i++) { std::cout << "line number: " << i << std::endl; std::cout << "verifying proof line "; for (int j : proof[i]) { std::cout << j << " "; } std::cout << "0" << std::endl; std::vector<std::vector<int> > operations; std::set<int> cur_op; for (int j : proof[i]) { cur_op.insert(j); } bool added = true; bool foundConflict = false; while (added) { added = false; // std::cout <<"here 1" <<std::endl; std::pair<bool, std::set<int> > boolSetpair = conflictAfterOp(cur_op, edgeMatrix, numColors, numVertex); // std::cout <<"here 2" <<std::endl; if (boolSetpair.first) { foundConflict = true; break; } else { // std::cout << "c" << std::endl; int cur_op_size = cur_op.size(); cur_op = boolSetpair.second; // std::cout <<"here 3" <<std::endl; cur_op = findImpliedOperations(cur_op, edgeMatrix, numVertex, numColors); // std::cout <<"here 4" <<std::endl; for (int l = i - 1; l >= 0; l--) { if (negates(proof[l],cur_op)) { foundConflict = true; break; } int diff = set_one_diff(proof[l], cur_op); // std::cout << "diff is " << diff << std::endl; if (diff && (cur_op.find(-diff) == cur_op.end())) { cur_op.insert(-diff); std::cout << "adding " << -diff << " to ops" << std::endl; } } std::cout << "cur_ops "; for (int p : cur_op) { std::cout << p << " "; } std::cout << "0" << std::endl; if (cur_op_size < cur_op.size()) { added = true; std::cout << "added, " << cur_op.size() << std::endl; } } } if (!foundConflict) { std::cout << "line number: " << i << std::endl; std::cout << "current ops: "; for (int j : cur_op) { std::cout << j << " "; } std::cout << "0" << std::endl; operations = convertOpsSet2Vec(cur_op, numVertex, numColors); for (int i = 0; i < operations.size(); i++) { if (operations[i][0] > 0) { std::cout << "contract "; } else { std::cout << "add edge "; } for (int j = 1; j < operations[i].size(); j++) { std::cout << operations[i][j] + 1 << " "; } std::cout << std::endl; } std::cout << "does not result in a conflict " << std::endl; return false; } } return true; } int main(int argc, char **argv) { // take the number of colors and the file path as input int numberOfColors; std::string dimacsFileName; std::vector<std::vector<bool> > edgeMtrx; int numVertices; std::string proofFileName; if (argc == 4) { numberOfColors = std::atoi(argv[1]); dimacsFileName = argv[2]; proofFileName = argv[3]; } else { std::cout << "Incorrect number of input arguments" << std::endl; } parse_edge_file(numberOfColors, dimacsFileName, numVertices, edgeMtrx); std::vector<std::set<int> > pf = parse_proof_file(proofFileName, numVertices, numberOfColors); std::cout << pf.size() <<std::endl; std::cout << verify_proof(pf, numVertices, numberOfColors, edgeMtrx) << std::endl; }
26.566711
155
0.520909
[ "vector" ]
19792604cc6ab52c0b8e8071d2835d5026a748cd
2,952
cpp
C++
source/STM32I2C.cpp
nedseb/codal-stm32
295f5db277b58beb850a6b61d5ec7d452760d561
[ "BSD-3-Clause" ]
null
null
null
source/STM32I2C.cpp
nedseb/codal-stm32
295f5db277b58beb850a6b61d5ec7d452760d561
[ "BSD-3-Clause" ]
13
2021-01-18T13:27:27.000Z
2021-12-20T09:31:51.000Z
source/STM32I2C.cpp
nedseb/codal-stm32
295f5db277b58beb850a6b61d5ec7d452760d561
[ "BSD-3-Clause" ]
null
null
null
#include "STM32I2C.h" #include <algorithm> #include "PeripheralPins.h" // #include "codal_target_hal.h" using namespace std; using namespace codal; STM32I2C::STM32I2C(STM32Pin& sda, STM32Pin& scl) : I2C(sda, scl), currentAddress(0), isOnTransmission(false) { i2c.sda = (PinName)sda.name; i2c.scl = (PinName)scl.name; i2c.isMaster = 1; i2c.generalCall = 0; } int STM32I2C::setFrequency(uint32_t frequency) { i2c_setTiming(&i2c, frequency); return DEVICE_OK; } void STM32I2C::beginTransmission(uint16_t address) { if (isOnTransmission) return; // target_disable_irq(); isOnTransmission = true; currentAddress = address; dataToSent.clear(); } void STM32I2C::endTransmission(bool sendStop) { if (!isOnTransmission) return; i2c_init(&i2c); setXferOptions(sendStop); unsigned packets = dataToSent.size() / getBufferSize(); if (getBufferSize() * packets < dataToSent.size()) { packets++; } for (unsigned i = 0; i < packets; ++i) { auto offset = i * getBufferSize(); auto length = min<unsigned>(dataToSent.size() - offset, getBufferSize()); i2c_master_write(&i2c, currentAddress, dataToSent.data() + offset, length); } i2c_deinit(&i2c); isOnTransmission = false; currentAddress = 0; // target_enable_irq(); } int STM32I2C::write(uint8_t data) { if (!isOnTransmission) { return 0; } dataToSent.push_back(data); return DEVICE_OK; } int STM32I2C::write(uint8_t* data, size_t len) { if (!isOnTransmission) { return 0; } dataToSent.insert(dataToSent.end(), data, data + len); return DEVICE_OK; } void STM32I2C::writeRegister(uint8_t reg, uint8_t value) { write(reg); write(value); } vector<uint8_t> STM32I2C::read(uint8_t address, size_t len, bool sendStop) { // target_disable_irq(); vector<uint8_t> data(len); i2c_init(&i2c); setXferOptions(sendStop); i2c_master_read(&i2c, address, data.data(), len); i2c_deinit(&i2c); // target_enable_irq(); return data; } vector<uint8_t> STM32I2C::readRegister(uint8_t address, uint8_t reg, size_t len, bool sendStop) { beginTransmission(address); write(reg); endTransmission(false); return read(address, len, sendStop); } int STM32I2C::write(uint16_t address, uint8_t* data, int len, bool repeated) { beginTransmission(address); write(data, len); endTransmission(!repeated); return DEVICE_OK; } int STM32I2C::read(uint16_t address, uint8_t* data, int len, bool repeated) { auto result = read(address, len, !repeated); memcpy(data, result.data(), len); return DEVICE_OK; } void STM32I2C::setXferOptions(bool sendStop) { #if defined(I2C_OTHER_FRAME) if (sendStop) { i2c.handle.XferOptions = I2C_OTHER_AND_LAST_FRAME; } else { i2c.handle.XferOptions = I2C_OTHER_FRAME; } #endif }
20.219178
108
0.660908
[ "vector" ]
197c0f6587805c6f77cff9ef5a2de36ee517f2f5
1,962
cc
C++
Code/1696-strange-printer-ii.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/1696-strange-printer-ii.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/1696-strange-printer-ii.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: bool isPrintable(vector<vector<int>>& targetGrid) { unordered_map<int, vector<int>> m; // minx, miny, maxx, maxy for (int i = 0; i < targetGrid.size(); i++) { for (int j = 0; j < targetGrid[0].size(); j++) { int color = targetGrid[i][j]; if (m.find(color) == m.end()) { m[color] = {i, j, i, j}; } else { auto &frame = m[color]; m[color] = {min(i, frame[0]), min(j, frame[1]), max(i, frame[2]), max(j, frame[3])}; } } } bool hasChange = true; bool needChange = false; unordered_set<int> done; while (hasChange) { hasChange = false; needChange = false; for (auto it = m.begin(); it != m.end(); ++it) { int color = it->first; if (done.find(color) != done.end()) { continue; } auto &frame = it->second; bool flag = true; for (int i = frame[0]; flag && i <= frame[2]; i++) { for (int j = frame[1]; j <= frame[3]; j++) { if (targetGrid[i][j] != color && targetGrid[i][j] != -1) { flag = false; break; } } } if (flag) { for (int i = frame[0]; flag && i <= frame[2]; i++) { for (int j = frame[1]; j <= frame[3]; j++) { targetGrid[i][j] = -1; } } done.insert(color); hasChange = true; } else { needChange = true; } } } return !needChange; } };
35.672727
104
0.344546
[ "vector" ]
19874f5e588754d9dd2c3e7fd98c350620036c53
1,031
cpp
C++
PrimeFactorizer/main.cpp
jehannes/PrimeCalculator
7ad1b7f5cacb9a08c092e1583e28ece952359d2e
[ "Apache-2.0" ]
null
null
null
PrimeFactorizer/main.cpp
jehannes/PrimeCalculator
7ad1b7f5cacb9a08c092e1583e28ece952359d2e
[ "Apache-2.0" ]
null
null
null
PrimeFactorizer/main.cpp
jehannes/PrimeCalculator
7ad1b7f5cacb9a08c092e1583e28ece952359d2e
[ "Apache-2.0" ]
null
null
null
#include "STDlibs.h" #include "PrimeFactor.h" #include "Fraction.h" using namespace std; //unique_ptr <PrimeFactor> fac; unique_ptr <Fraction> Frac; shared_ptr <PrimeLibrary> Lib; int main(void) { // vector <uint64_t> Divs; //uint64_t num; string num; int mode = 0; string more; while (true) { cout << "give number:"; cin >> num; cout << "\ngive mode:"; cin >> mode; Lib = shared_ptr <PrimeLibrary>(make_shared<PrimeLibrary>(mode)); Frac = unique_ptr <Fraction>(make_unique <Fraction>(Lib)); /* fac = unique_ptr <PrimeFactor>(new PrimeFactor(mode)); Divs = fac->factor(num); cout << "the factors of " << num << " are:\n"; for (uint64_t i : Divs) { cout << i << " "; } Frac->setFraction(num); */ Frac->setFraction(num); system("CLS"); cout << Frac->getFractionString(); cout << "\n\n\n"; cout << "more? "; cin >> more; if (more == "Y" || more == "y") { Lib.reset(); Frac.reset(); system("CLS"); } else { break; } } return NULL; }
16.629032
67
0.582929
[ "vector" ]
1989dfcf6c96dfbe439910294dc63d230611caf6
1,616
cpp
C++
src/tools/dnd/dataObjects/PlaylistTransitiveData.cpp
etrange02/Fux
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
[ "CECILL-B" ]
2
2016-03-21T10:48:34.000Z
2017-03-17T19:50:34.000Z
src/tools/dnd/dataObjects/PlaylistTransitiveData.cpp
etrange02/Fux
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
[ "CECILL-B" ]
null
null
null
src/tools/dnd/dataObjects/PlaylistTransitiveData.cpp
etrange02/Fux
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
[ "CECILL-B" ]
null
null
null
/*************************************************************** * Name: PlaylistTransitiveData.cpp * Purpose: Code for Fu(X) 2.0 * Author: David Lecoconnier (david.lecoconnier@free.fr) * Created: 2015-06-24 * Copyright: David Lecoconnier (http://www.getfux.fr) * License: **************************************************************/ #include "tools/dnd/dataObjects/PlaylistTransitiveData.h" using namespace dragAndDrop; /** @brief Constructor. */ PlaylistTransitiveData::PlaylistTransitiveData() : TTransitiveData<std::shared_ptr<music::Music>>() { } /** @brief Destructor. */ PlaylistTransitiveData::~PlaylistTransitiveData() { } /** @brief Copy constructor. * * @param other const PlaylistTransitiveData& * */ PlaylistTransitiveData::PlaylistTransitiveData(const PlaylistTransitiveData& other) : TTransitiveData(other) { } /** @brief Copy operator. * * @param rhs const PlaylistTransitiveData& * @return PlaylistTransitiveData& * */ PlaylistTransitiveData& PlaylistTransitiveData::operator=(const PlaylistTransitiveData& rhs) { if (this == &rhs) return *this; // handle self assignment //assignment operator return *this; } wxArrayString PlaylistTransitiveData::getFilenames() const { const std::vector<std::shared_ptr<music::Music>>& items = getItems(); wxArrayString data; for (std::vector<std::shared_ptr<music::Music>>::const_iterator iter = items.begin(); iter != items.end(); ++iter) { data.Add( (*iter)->GetFileName() ); } return data; } bool PlaylistTransitiveData::isPlaylistKind() const { return true; }
24.119403
118
0.65099
[ "vector" ]
198ba8bf99c1c6bede37d74ad99d3ab42bd43f5e
5,255
hpp
C++
libfma/include/fma/plugin/MemoryPluginAdapter.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/include/fma/plugin/MemoryPluginAdapter.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/include/fma/plugin/MemoryPluginAdapter.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#ifndef __FMA_PLUGIN_MEMORYPLUGINADAPTER_H__ #define __FMA_PLUGIN_MEMORYPLUGINADAPTER_H__ #include <memory> #include <vector> #include "../types/InternalValue.hpp" namespace FMA { class Log; class Project; namespace output { class DynamicBuffer; } namespace linker { class LinkerBlock; } namespace interpret { typedef std::shared_ptr<class BaseContext> ContextPtr; } namespace symbol { typedef std::shared_ptr<class Reference> ReferencePtr; typedef std::shared_ptr<class SymbolReference> SymbolReferencePtr; } namespace assem { class Instruction; class BinaryCodeGeneratorScope; } namespace plugin { class MemoryBlockPlacement { public: MemoryBlockPlacement() {} virtual ~MemoryBlockPlacement() {} virtual bool isValid() const = 0; virtual uint64_t asTranslatedAddress() const = 0; virtual uint64_t asLongAddress() const = 0; }; struct MemorySymbolMapCommand { MemorySymbolMapCommand() {} MemorySymbolMapCommand(uint32_t reference, const std::string &command) : reference(reference), command(command) {} uint32_t reference; std::string command; }; struct MemorySymbolMapBreakpoint { MemorySymbolMapBreakpoint(const symbol::SymbolReferencePtr &reference, bool notifyOnly, const std::string &comment) : reference(reference) , notifyOnly(notifyOnly) , comment(comment) {} symbol::SymbolReferencePtr reference; bool notifyOnly; std::string comment; }; class MemorySymbolMap { public: MemorySymbolMap() {} virtual ~MemorySymbolMap() {} virtual symbol::SymbolReferencePtr createReference() = 0; virtual symbol::SymbolReferencePtr createReference(const std::string &hint) = 0; virtual symbol::ReferencePtr createCommand(const std::string &command) = 0; virtual void addEmulatorBreakpoint(const symbol::SymbolReferencePtr &, bool notifyOnly, const std::string &comment) = 0; virtual bool hasResolved(const std::string &) const = 0; virtual uint64_t getResolved(const std::string &) const = 0; virtual std::vector<std::string> getSymbolNames() const = 0; virtual const std::vector<MemorySymbolMapCommand> &getCommands() const = 0; virtual const std::vector<MemorySymbolMapBreakpoint> &getBreakpoints() const = 0; virtual std::string getSymbolTypeHint(const std::string &) const { return "ANY"; } virtual uint32_t getSymbolSizeHint(const std::string &) const { return 1; } virtual void dump() const {} }; class MemoryLocation { public: MemoryLocation() {} virtual ~MemoryLocation() {} virtual void overrideAllow(const interpret::ContextPtr &, const interpret::GroupedParameterList &) = 0; virtual void allow(const interpret::ContextPtr &, const interpret::GroupedParameterList &) = 0; virtual void deny(const interpret::ContextPtr &, const interpret::GroupedParameterList &) = 0; virtual bool serialize(output::DynamicBuffer &) const = 0; }; typedef std::shared_ptr<MemoryLocation> MemoryLocationPtr; class MemoryBlock { public: enum Usage { READ_ONLY, RANDOM_ACCESS }; MemoryBlock(Usage usage) : usage(usage), lastIsReturn(false) {}; virtual ~MemoryBlock() {} virtual void setNameHint(const std::string &) {} virtual std::string getNameHint() const { return ""; } virtual symbol::SymbolReferencePtr createReference() = 0; virtual void markIsUsed(bool used=true) = 0; virtual void write(void *data, uint32_t size) = 0; virtual void write(const symbol::ReferencePtr &reference, uint32_t size) = 0; virtual void write(assem::Instruction *instruct) = 0; virtual symbol::ReferencePtr reference() = 0; virtual symbol::ReferencePtr reference(const symbol::SymbolReferencePtr &reference) = 0; virtual symbol::ReferencePtr reference(const std::string &) { return reference(); } virtual bool buildByteCode(assem::BinaryCodeGeneratorScope *scope) = 0; virtual MemoryLocationPtr location() = 0; static MemoryBlock *getFromContext(const interpret::ContextPtr &context); static MemoryBlock *getFromType(const types::TypePtr &type); void declareInType(const types::TypePtr &type); inline void setLastIsReturn(bool isReturn) { lastIsReturn=isReturn; }; inline bool isReturned() const { return lastIsReturn; } protected: Usage usage; bool lastIsReturn; }; typedef types::InternalObject<MemoryBlock*> InternalMemoryBlock; typedef std::vector<MemoryBlock*> MemoryBlockList; class MemoryPluginAdapter { public: MemoryPluginAdapter(Project *project) : project(project) {} virtual ~MemoryPluginAdapter() {} virtual MemorySymbolMap *getSymbolMap() const = 0; virtual MemoryBlock *allocateBlock(MemoryBlock::Usage usage, const std::string &name) = 0; virtual const MemoryBlockList &getBlocks() = 0; virtual MemoryLocationPtr deserializeLocation(Log *, output::DynamicBuffer &) const { return MemoryLocationPtr(); } virtual symbol::SymbolReferencePtr createReference(const std::string &name) = 0; virtual uint64_t translateAddress(uint64_t address) { return address; } virtual bool placeDynamicBlocks() = 0; virtual bool placeStaticBlocks() = 0; virtual bool registerLinkerBlockSymbols(linker::LinkerBlock *block) = 0; virtual const MemoryBlockPlacement *requireStaticBlockPlacement(linker::LinkerBlock *block) = 0; protected: Project *project; }; } } #endif
30.552326
122
0.753378
[ "vector" ]
199068e2ba480297b73bc41f35bec0a0e7454c23
1,507
cpp
C++
clients/cpp-tiny/generated/lib/Models/PipelineBranchesitempullRequestlinks.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-tiny/generated/lib/Models/PipelineBranchesitempullRequestlinks.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-tiny/generated/lib/Models/PipelineBranchesitempullRequestlinks.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
#include "PipelineBranchesitempullRequestlinks.h" using namespace Tiny; PipelineBranchesitempullRequestlinks::PipelineBranchesitempullRequestlinks() { self = std::string(); _class = std::string(); } PipelineBranchesitempullRequestlinks::PipelineBranchesitempullRequestlinks(std::string jsonString) { this->fromJson(jsonString); } PipelineBranchesitempullRequestlinks::~PipelineBranchesitempullRequestlinks() { } void PipelineBranchesitempullRequestlinks::fromJson(std::string jsonObj) { bourne::json object = bourne::json::parse(jsonObj); const char *selfKey = "self"; if(object.has_key(selfKey)) { bourne::json value = object[selfKey]; jsonToValue(&self, value, "std::string"); } const char *_classKey = "_class"; if(object.has_key(_classKey)) { bourne::json value = object[_classKey]; jsonToValue(&_class, value, "std::string"); } } bourne::json PipelineBranchesitempullRequestlinks::toJson() { bourne::json object = bourne::json::object(); object["self"] = getSelf(); object["_class"] = getClass(); return object; } std::string PipelineBranchesitempullRequestlinks::getSelf() { return self; } void PipelineBranchesitempullRequestlinks::setSelf(std::string self) { this->self = self; } std::string PipelineBranchesitempullRequestlinks::getClass() { return _class; } void PipelineBranchesitempullRequestlinks::setClass(std::string _class) { this->_class = _class; }
14.084112
98
0.708693
[ "object" ]
19916014192fd8a6255ad6d2efc245423b50618f
2,188
cpp
C++
SumAllLeftLeavesOfBinaryTree.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
2
2015-07-01T17:47:02.000Z
2015-07-01T17:53:11.000Z
SumAllLeftLeavesOfBinaryTree.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
null
null
null
SumAllLeftLeavesOfBinaryTree.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
null
null
null
// Given a binary tree sum all of the left leaves. // // Time Complexity: O(n) // Space Complexity: O(1) // // Complier: Visual Studio 2013 (v120) #include <memory> #include <vector> #include "CppUnitTest.h" using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace SumAllLeftLeavesOfBinaryTree { class Node { public: int value; shared_ptr<Node> left; shared_ptr<Node> right; Node(int v) : value(v) {} void insert(shared_ptr<Node> node) { if (node->value <= value) { if (left == nullptr) { left = node; } else { left->insert(node); } } else { if (right == nullptr) { right = node; } else { right->insert(node); } } } }; int sumOfAllLeftLeaves(shared_ptr<Node> node) { int sum = 0; if (node->left != nullptr) { // && node->right == nullptr) { if (node->left->left == nullptr) { // Base case return node->left->value; } else { sum += sumOfAllLeftLeaves(node->left); } } if (node->right != nullptr) { sum += sumOfAllLeftLeaves(node->right); } return sum; } shared_ptr<Node> buildTree(const vector<int> values) { auto root = make_shared<Node>(Node(values[0])); for (auto i = 1; i < values.size(); i++) { root->insert(make_shared<Node>(Node(values[i]))); } return root; } TEST_CLASS(SumAllLeftLeavesOfBinaryTreeTests) { public: TEST_METHOD(WhenAllRightChildren_ExpectZero) { auto tree = buildTree({ 1, 2, 3, 4 }); auto result = sumOfAllLeftLeaves(tree); Assert::AreEqual(0, result); } TEST_METHOD(WhenAllLeftChildren_ExpectLeftmostNode) { auto tree = buildTree({ 5, 4, 3, 2 }); auto result = sumOfAllLeftLeaves(tree); Assert::AreEqual(2, result); } // 10 // 5 15 // 2 8 12 18 TEST_METHOD(WhenBalancedTree_ExpectSumOfAllLeftLeaves) { auto tree = buildTree({ 10, 5, 15, 2, 8, 12, 18}); auto result = sumOfAllLeftLeaves(tree); Assert::AreEqual(2 + 12, result); } }; }
23.526882
64
0.571298
[ "vector" ]
199547f473d9e755f7c9bee30bd3bf4e0b7f3a38
1,751
hpp
C++
packages/monte_carlo/estimator/native/src/MonteCarlo_ParticleLeavingCellEventDispatcher.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/estimator/native/src/MonteCarlo_ParticleLeavingCellEventDispatcher.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/estimator/native/src/MonteCarlo_ParticleLeavingCellEventDispatcher.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_ParticleLeavingCellEventDispatcher.hpp //! \author Alex Robinson //! \brief Particle leaving cell event dispatcher class declaration. //! //---------------------------------------------------------------------------// #ifndef FACEMC_PARTICLE_LEAVING_CELL_EVENT_DISPATCHER_HPP #define FACEMC_PARTICLE_LEAVING_CELL_EVENT_DISPATCHER_HPP // Boost Includes #include <boost/unordered_map.hpp> // Teuchos Includes #include <Teuchos_RCP.hpp> // FRENSIE Includes #include "MonteCarlo_ParticleEventDispatcher.hpp" #include "MonteCarlo_ParticleLeavingCellEventObserver.hpp" #include "MonteCarlo_ParticleState.hpp" #include "MonteCarlo_ModuleTraits.hpp" #include "Geometry_ModuleTraits.hpp" namespace MonteCarlo{ //! The particle leaving cell event dispatcher class ParticleLeavingCellEventDispatcher : public ParticleEventDispatcher<Geometry::ModuleTraits::InternalCellHandle, ParticleLeavingCellEventObserver> { public: //! Constructor ParticleLeavingCellEventDispatcher( const Geometry::ModuleTraits::InternalCellHandle cell_id ); //! Destructor ~ParticleLeavingCellEventDispatcher() { /* ... */ } //! Dispatch the new event to the observers void dispatchParticleLeavingCellEvent( const ParticleState& particle, const Geometry::ModuleTraits::InternalCellHandle cell_leaving ); }; } // end MonteCarlo namespace #endif // end FACEMC_PARTICLE_LEAVING_CELL_EVENT_DISPATCHER_HPP //---------------------------------------------------------------------------// // end MonteCarlo_ParticleLeavingCellEventDispatcher.hpp //---------------------------------------------------------------------------//
31.267857
79
0.651628
[ "geometry" ]
199b356eeca1b54b88f52d7dfc8904f95c581e0d
868
hh
C++
tests/test-util/print-objects.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
tests/test-util/print-objects.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
tests/test-util/print-objects.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- #ifndef FAINT_TEST_PRINT_OBJECTS_HH #define FAINT_TEST_PRINT_OBJECTS_HH #include <iosfwd> #include <vector> #define PRINTER(CLASS)class CLASS; std::ostream& operator<<(std::ostream&, const CLASS&) namespace faint{ PRINTER(Angle); PRINTER(CaretRange); PRINTER(IntLineSegment); PRINTER(IntPoint); PRINTER(IntRect); PRINTER(IntSize); PRINTER(LineSegment); PRINTER(Paint); PRINTER(Point); PRINTER(Rect); PRINTER(utf8_char); PRINTER(Color); PRINTER(ColRGB); PRINTER(Index); // Avoids unsigned char values being casted to char and printed as // garbage ascii, by outputting them as unsigned int instead. std::ostream& operator<<(std::ostream&, unsigned char); template<typename T> std::ostream& operator<<(std::ostream& o, const std::vector<T>& v){ for (const auto& i : v){ o << i << " "; } return o; } } // namespace #endif
21.7
88
0.723502
[ "vector" ]
199d862ee29ec56237d124b9dc8aa55fc0c5eb52
2,573
cc
C++
ehpc/src/model/DescribeImagePriceRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ehpc/src/model/DescribeImagePriceRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ehpc/src/model/DescribeImagePriceRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ehpc/model/DescribeImagePriceRequest.h> using AlibabaCloud::EHPC::Model::DescribeImagePriceRequest; DescribeImagePriceRequest::DescribeImagePriceRequest() : RpcServiceRequest("ehpc", "2018-04-12", "DescribeImagePrice") { setMethod(HttpRequest::Method::Get); } DescribeImagePriceRequest::~DescribeImagePriceRequest() {} int DescribeImagePriceRequest::getPeriod()const { return period_; } void DescribeImagePriceRequest::setPeriod(int period) { period_ = period; setParameter("Period", std::to_string(period)); } int DescribeImagePriceRequest::getAmount()const { return amount_; } void DescribeImagePriceRequest::setAmount(int amount) { amount_ = amount; setParameter("Amount", std::to_string(amount)); } std::string DescribeImagePriceRequest::getImageId()const { return imageId_; } void DescribeImagePriceRequest::setImageId(const std::string& imageId) { imageId_ = imageId; setParameter("ImageId", imageId); } std::string DescribeImagePriceRequest::getSkuCode()const { return skuCode_; } void DescribeImagePriceRequest::setSkuCode(const std::string& skuCode) { skuCode_ = skuCode; setParameter("SkuCode", skuCode); } std::string DescribeImagePriceRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeImagePriceRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string DescribeImagePriceRequest::getPriceUnit()const { return priceUnit_; } void DescribeImagePriceRequest::setPriceUnit(const std::string& priceUnit) { priceUnit_ = priceUnit; setParameter("PriceUnit", priceUnit); } std::string DescribeImagePriceRequest::getOrderType()const { return orderType_; } void DescribeImagePriceRequest::setOrderType(const std::string& orderType) { orderType_ = orderType; setParameter("OrderType", orderType); }
24.046729
79
0.749709
[ "model" ]
19a4a2dd25a6cd83e53416008a5d0e8f287a5357
1,395
hpp
C++
include/georithm/transform/Shear.hpp
DNKpp/georithm
3eb7e3f2be8ff0aabe402ac22944807564693ece
[ "BSL-1.0" ]
1
2018-06-18T12:51:26.000Z
2018-06-18T12:51:26.000Z
include/georithm/transform/Shear.hpp
DNKpp/georithm
3eb7e3f2be8ff0aabe402ac22944807564693ece
[ "BSL-1.0" ]
null
null
null
include/georithm/transform/Shear.hpp
DNKpp/georithm
3eb7e3f2be8ff0aabe402ac22944807564693ece
[ "BSL-1.0" ]
2
2020-08-16T16:03:21.000Z
2020-09-05T15:06:56.000Z
// Copyright Dominic Koepke 2017 - 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #ifndef GEORITHM_TRANSFORM_SHEAR_HPP #define GEORITHM_TRANSFORM_SHEAR_HPP #pragma once #include "georithm/Concepts.hpp" namespace georithm::transform { template <NDimensionalVectorObject<2> TVectorType> class Shear { public: using VectorType = TVectorType; using ValueType = typename TVectorType::ValueType; constexpr Shear() noexcept = default; /*ToDo: c++20 constexpr */ ~Shear() noexcept = default; constexpr explicit Shear(const VectorType& shear) noexcept : m_Shear{ shear } { } constexpr Shear(const Shear&) = default; constexpr Shear& operator =(const Shear&) = default; constexpr Shear(Shear&&) = default; constexpr Shear& operator =(Shear&&) = default; [[nodiscard]] constexpr bool operator ==(const Shear&) const = default; [[nodiscard]] constexpr const VectorType& shear() const noexcept { return m_Shear; } [[nodiscard]] constexpr VectorType& shear() noexcept { return m_Shear; } [[nodiscard]] constexpr VectorType transform(const VectorType& vec) const noexcept { return { vec.x() + m_Shear.x() * vec.y(), vec.y() + m_Shear.y() * vec.x() }; } private: VectorType m_Shear; }; } #endif
23.25
84
0.694624
[ "transform" ]
19a51dcb36d11dc76c7c81908c8e03888d8a6b76
12,999
cpp
C++
VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/selector/graphics/chooser/UIGChooserItem.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
1
2015-04-30T14:18:45.000Z
2015-04-30T14:18:45.000Z
VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/selector/graphics/chooser/UIGChooserItem.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/selector/graphics/chooser/UIGChooserItem.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
/* $Id: UIGChooserItem.cpp $ */ /** @file * VBox Qt GUI - UIGChooserItem class definition. */ /* * Copyright (C) 2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Qt includes: */ # include <QApplication> # include <QStyle> # include <QPainter> # include <QGraphicsScene> # include <QStyleOptionFocusRect> # include <QGraphicsSceneMouseEvent> # include <QStateMachine> # include <QPropertyAnimation> # include <QSignalTransition> /* GUI includes: */ # include "UIGChooserItem.h" # include "UIGChooserModel.h" # include "UIGChooserItemGroup.h" # include "UIGChooserItemMachine.h" #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ UIGChooserItem::UIGChooserItem(UIGChooserItem *pParent, bool fTemporary) : m_fRoot(!pParent) , m_fTemporary(fTemporary) , m_pParent(pParent) , m_iPreviousMinimumWidthHint(0) , m_iPreviousMinimumHeightHint(0) , m_dragTokenPlace(DragToken_Off) , m_fHovered(false) , m_pHighlightMachine(0) , m_pForwardAnimation(0) , m_pBackwardAnimation(0) , m_iAnimationDuration(400) , m_iDefaultDarkness(100) , m_iHighlightDarkness(90) , m_iAnimationDarkness(m_iDefaultDarkness) , m_iDragTokenDarkness(110) { /* Basic item setup: */ setOwnedByLayout(false); setAcceptDrops(true); setFocusPolicy(Qt::NoFocus); setFlag(QGraphicsItem::ItemIsSelectable, false); setAcceptHoverEvents(!isRoot()); /* Non-root item? */ if (!isRoot()) { /* Create state machine: */ m_pHighlightMachine = new QStateMachine(this); /* Create 'default' state: */ QState *pStateDefault = new QState(m_pHighlightMachine); /* Create 'highlighted' state: */ QState *pStateHighlighted = new QState(m_pHighlightMachine); /* Forward animation: */ m_pForwardAnimation = new QPropertyAnimation(this, "animationDarkness", this); m_pForwardAnimation->setDuration(m_iAnimationDuration); m_pForwardAnimation->setStartValue(m_iDefaultDarkness); m_pForwardAnimation->setEndValue(m_iHighlightDarkness); /* Backward animation: */ m_pBackwardAnimation = new QPropertyAnimation(this, "animationDarkness", this); m_pBackwardAnimation->setDuration(m_iAnimationDuration); m_pBackwardAnimation->setStartValue(m_iHighlightDarkness); m_pBackwardAnimation->setEndValue(m_iDefaultDarkness); /* Add state transitions: */ QSignalTransition *pDefaultToHighlighted = pStateDefault->addTransition(this, SIGNAL(sigHoverEnter()), pStateHighlighted); pDefaultToHighlighted->addAnimation(m_pForwardAnimation); QSignalTransition *pHighlightedToDefault = pStateHighlighted->addTransition(this, SIGNAL(sigHoverLeave()), pStateDefault); pHighlightedToDefault->addAnimation(m_pBackwardAnimation); /* Initial state is 'default': */ m_pHighlightMachine->setInitialState(pStateDefault); /* Start state-machine: */ m_pHighlightMachine->start(); } } UIGChooserItemGroup* UIGChooserItem::toGroupItem() { UIGChooserItemGroup *pItem = qgraphicsitem_cast<UIGChooserItemGroup*>(this); AssertMsg(pItem, ("Trying to cast invalid item type to UIGChooserItemGroup!")); return pItem; } UIGChooserItemMachine* UIGChooserItem::toMachineItem() { UIGChooserItemMachine *pItem = qgraphicsitem_cast<UIGChooserItemMachine*>(this); AssertMsg(pItem, ("Trying to cast invalid item type to UIGChooserItemMachine!")); return pItem; } UIGChooserModel* UIGChooserItem::model() const { UIGChooserModel *pModel = qobject_cast<UIGChooserModel*>(QIGraphicsWidget::scene()->parent()); AssertMsg(pModel, ("Incorrect graphics scene parent set!")); return pModel; } UIActionPool* UIGChooserItem::actionPool() const { return model()->actionPool(); } UIGChooserItem* UIGChooserItem::parentItem() const { return m_pParent; } void UIGChooserItem::show() { /* Call to base-class: */ QIGraphicsWidget::show(); } void UIGChooserItem::hide() { /* Call to base-class: */ QIGraphicsWidget::hide(); } void UIGChooserItem::setRoot(bool fRoot) { m_fRoot = fRoot; handleRootStatusChange(); } bool UIGChooserItem::isRoot() const { return m_fRoot; } bool UIGChooserItem::isHovered() const { return m_fHovered; } void UIGChooserItem::setHovered(bool fHovered) { m_fHovered = fHovered; if (m_fHovered) emit sigHoverEnter(); else emit sigHoverLeave(); } void UIGChooserItem::updateGeometry() { /* Call to base-class: */ QIGraphicsWidget::updateGeometry(); /* Update parent's geometry: */ if (parentItem()) parentItem()->updateGeometry(); /* Special handling for root-items: */ if (isRoot()) { /* Root-item should notify chooser-view if minimum-width-hint was changed: */ int iMinimumWidthHint = minimumWidthHint(); if (m_iPreviousMinimumWidthHint != iMinimumWidthHint) { /* Save new minimum-width-hint, notify listener: */ m_iPreviousMinimumWidthHint = iMinimumWidthHint; emit sigMinimumWidthHintChanged(m_iPreviousMinimumWidthHint); } /* Root-item should notify chooser-view if minimum-height-hint was changed: */ int iMinimumHeightHint = minimumHeightHint(); if (m_iPreviousMinimumHeightHint != iMinimumHeightHint) { /* Save new minimum-height-hint, notify listener: */ m_iPreviousMinimumHeightHint = iMinimumHeightHint; emit sigMinimumHeightHintChanged(m_iPreviousMinimumHeightHint); } } } void UIGChooserItem::makeSureItsVisible() { /* If item is not visible: */ if (!isVisible()) { /* Get parrent item, assert if can't: */ if (UIGChooserItemGroup *pParentItem = parentItem()->toGroupItem()) { /* We should make parent visible: */ pParentItem->makeSureItsVisible(); /* And make sure its opened: */ if (pParentItem->isClosed()) pParentItem->open(false); } } } void UIGChooserItem::setDragTokenPlace(DragToken where) { /* Something changed? */ if (m_dragTokenPlace != where) { m_dragTokenPlace = where; update(); } } DragToken UIGChooserItem::dragTokenPlace() const { return m_dragTokenPlace; } bool UIGChooserItem::isTemporary() const { return m_fTemporary; } void UIGChooserItem::hoverMoveEvent(QGraphicsSceneHoverEvent*) { if (!m_fHovered) { m_fHovered = true; emit sigHoverEnter(); } } void UIGChooserItem::hoverLeaveEvent(QGraphicsSceneHoverEvent*) { if (m_fHovered) { m_fHovered = false; emit sigHoverLeave(); } } void UIGChooserItem::mousePressEvent(QGraphicsSceneMouseEvent *pEvent) { /* By default, non-moveable and non-selectable items * can't grab mouse-press events which is required * to grab further mouse-move events which we wants... */ if (isRoot()) pEvent->ignore(); else pEvent->accept(); } void UIGChooserItem::mouseMoveEvent(QGraphicsSceneMouseEvent *pEvent) { /* Make sure item is really dragged: */ if (QLineF(pEvent->screenPos(), pEvent->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance()) return; /* Initialize dragging: */ QDrag *pDrag = new QDrag(pEvent->widget()); model()->setCurrentDragObject(pDrag); pDrag->setPixmap(toPixmap()); pDrag->setMimeData(createMimeData()); pDrag->exec(Qt::MoveAction | Qt::CopyAction, Qt::MoveAction); } void UIGChooserItem::dragMoveEvent(QGraphicsSceneDragDropEvent *pEvent) { /* Make sure we are non-root: */ if (!isRoot()) { /* Allow drag tokens only for the same item type as current: */ bool fAllowDragToken = false; if ((type() == UIGChooserItemType_Group && pEvent->mimeData()->hasFormat(UIGChooserItemGroup::className())) || (type() == UIGChooserItemType_Machine && pEvent->mimeData()->hasFormat(UIGChooserItemMachine::className()))) fAllowDragToken = true; /* Do we need a drag-token? */ if (fAllowDragToken) { QPoint p = pEvent->pos().toPoint(); if (p.y() < 10) setDragTokenPlace(DragToken_Up); else if (p.y() > minimumSizeHint().toSize().height() - 10) setDragTokenPlace(DragToken_Down); else setDragTokenPlace(DragToken_Off); } } /* Check if drop is allowed: */ pEvent->setAccepted(isDropAllowed(pEvent, dragTokenPlace())); } void UIGChooserItem::dragLeaveEvent(QGraphicsSceneDragDropEvent*) { resetDragToken(); } void UIGChooserItem::dropEvent(QGraphicsSceneDragDropEvent *pEvent) { /* Do we have token active? */ switch (dragTokenPlace()) { case DragToken_Off: { /* Its our drop, processing: */ processDrop(pEvent); break; } default: { /* Its parent drop, passing: */ parentItem()->processDrop(pEvent, this, dragTokenPlace()); break; } } } /* static */ void UIGChooserItem::configurePainterShape(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, int iRadius) { /* Rounded corners? */ if (iRadius) { /* Setup clipping: */ QPainterPath roundedPath; roundedPath.addRoundedRect(pOption->rect, iRadius, iRadius); pPainter->setClipPath(roundedPath); } } /* static */ void UIGChooserItem::paintFrameRect(QPainter *pPainter, const QRect &rect, bool fIsSelected, int iRadius) { pPainter->save(); QPalette pal = QApplication::palette(); QColor base = pal.color(QPalette::Active, fIsSelected ? QPalette::Highlight : QPalette::Window); pPainter->setPen(base.darker(160)); if (iRadius) pPainter->drawRoundedRect(rect, iRadius, iRadius); else pPainter->drawRect(rect); pPainter->restore(); } /* static */ void UIGChooserItem::paintPixmap(QPainter *pPainter, const QPoint &point, const QPixmap &pixmap) { pPainter->drawPixmap(point, pixmap); } /* static */ void UIGChooserItem::paintText(QPainter *pPainter, QPoint point, const QFont &font, QPaintDevice *pPaintDevice, const QString &strText) { /* Prepare variables: */ QFontMetrics fm(font, pPaintDevice); point += QPoint(0, fm.ascent()); /* Draw text: */ pPainter->save(); pPainter->setFont(font); pPainter->drawText(point, strText); pPainter->restore(); } /* static */ QSize UIGChooserItem::textSize(const QFont &font, QPaintDevice *pPaintDevice, const QString &strText) { /* Make sure text is not empty: */ if (strText.isEmpty()) return QSize(0, 0); /* Return text size, based on font-metrics: */ QFontMetrics fm(font, pPaintDevice); return QSize(fm.width(strText), fm.height()); } /* static */ int UIGChooserItem::textWidth(const QFont &font, QPaintDevice *pPaintDevice, int iCount) { /* Return text width: */ QFontMetrics fm(font, pPaintDevice); QString strString; strString.fill('_', iCount); return fm.width(strString); } /* static */ QString UIGChooserItem::compressText(const QFont &font, QPaintDevice *pPaintDevice, QString strText, int iWidth) { /* Check if passed text is empty: */ if (strText.isEmpty()) return strText; /* Check if passed text feats maximum width: */ QFontMetrics fm(font, pPaintDevice); if (fm.width(strText) <= iWidth) return strText; /* Truncate otherwise: */ QString strEllipsis = QString("..."); int iEllipsisWidth = fm.width(strEllipsis + " "); while (!strText.isEmpty() && fm.width(strText) + iEllipsisWidth > iWidth) strText.truncate(strText.size() - 1); return strText + strEllipsis; } UIGChooserItemMimeData::UIGChooserItemMimeData(UIGChooserItem *pItem) : m_pItem(pItem) { } bool UIGChooserItemMimeData::hasFormat(const QString &strMimeType) const { if (strMimeType == QString(m_pItem->metaObject()->className())) return true; return false; } UIGChooserItem* UIGChooserItemMimeData::item() const { return m_pItem; }
29.14574
130
0.661589
[ "geometry", "model" ]
30ae53fa07ea168d03bcb8f61caa1bdc925a48e7
743
cpp
C++
Scripts/456_past.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
Scripts/456_past.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
Scripts/456_past.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: bool find132pattern(vector<int>& nums) { int second = INT_MIN; stack<int> sta; // 1 -5 -2 -3 // stack: 1 // stack 1 -5 -2 -1 -3 for (int i = nums.size()-1; i >= 0; --i) { // its's a reverse order if (nums[i] < second) return true; if (sta.size() != 0 && nums[i] > sta.top()){ while (sta.size() != 0 && nums[i] > sta.top()){ second = sta.top(); // only we pop once // we record the last value, and for the 132, this value is the `1` sta.pop(); } } sta.push(nums[i]); } return false; } };
32.304348
87
0.40646
[ "vector" ]
30af7a7f87b409d80a020e59a195e3c2fc93204c
2,763
cpp
C++
src/caffe/layers/swish_layer.cpp
naibaf7/caffe
29960153c828820b1abb55a5792283742f57caa2
[ "Intel", "BSD-2-Clause" ]
89
2015-04-20T01:25:01.000Z
2021-12-07T17:03:28.000Z
src/caffe/layers/swish_layer.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
62
2015-06-18T13:11:20.000Z
2019-02-19T05:00:10.000Z
src/caffe/layers/swish_layer.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
30
2015-07-05T17:08:09.000Z
2022-02-10T13:16:02.000Z
#include <cmath> #include <vector> #include "caffe/layers/swish_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template<typename Dtype, typename MItype, typename MOtype> inline Dtype sigmoid(Dtype x) { return 0.5 * tanh(0.5 * x) + 0.5; } template<typename Dtype, typename MItype, typename MOtype> void SwishLayer<Dtype, MItype, MOtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { NeuronLayer<Dtype, MItype, MOtype>::LayerSetUp(bottom, top); } template<typename Dtype, typename MItype, typename MOtype> void SwishLayer<Dtype, MItype, MOtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { NeuronLayer<Dtype, MItype, MOtype>::Reshape(bottom, top); if (Caffe::mode() == Caffe::GPU && this->device_program_.get() == nullptr) { this->GenerateProgram(); } } template<typename Dtype, typename MItype, typename MOtype> void SwishLayer<Dtype, MItype, MOtype>::Forward_cpu( const vector<Blob<MItype>*>& bottom, const vector<Blob<MOtype>*>& top) { const MItype* bottom_data = bottom[0]->cpu_data(); MOtype* top_data = top[0]->mutable_cpu_data(); const int_tp count = bottom[0]->count(); Dtype beta = this->layer_param_.swish_param().beta(); for (int_tp i = 0; i < count; ++i) { top_data[i] = bottom_data[i] * sigmoid<Dtype, MItype, MOtype>(beta * bottom_data[i]); } } template<typename Dtype, typename MItype, typename MOtype> void SwishLayer<Dtype, MItype, MOtype>::Backward_cpu( const vector<Blob<MOtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<MItype>*>& bottom) { if (propagate_down[0]) { const MItype* bottom_data = bottom[0]->cpu_data(); const MOtype* top_data = top[0]->cpu_data(); const MOtype* top_diff = top[0]->cpu_diff(); MItype* bottom_diff = bottom[0]->mutable_cpu_diff(); const int_tp count = bottom[0]->count(); Dtype beta = this->layer_param_.swish_param().beta(); for (int_tp i = 0; i < count; ++i) { const Dtype swish_x = top_data[i]; bottom_diff[i] = top_diff[i] * (beta * swish_x + sigmoid<Dtype, MItype, MOtype>(beta * bottom_data[i]) * (1. - beta * swish_x)); } } } #ifdef CPU_ONLY STUB_GPU(SwishLayer); #endif INSTANTIATE_CLASS_3T_GUARDED(SwishLayer, (half_fp), (half_fp), (half_fp)); INSTANTIATE_CLASS_3T_GUARDED(SwishLayer, (float), (float), (float)); INSTANTIATE_CLASS_3T_GUARDED(SwishLayer, (double), (double), (double)); REGISTER_LAYER_CLASS(Swish); REGISTER_LAYER_CLASS_INST(Swish, (half_fp), (half_fp), (half_fp)); REGISTER_LAYER_CLASS_INST(Swish, (float), (float), (float)); REGISTER_LAYER_CLASS_INST(Swish, (double), (double), (double)); } // namespace caffe
34.111111
78
0.686934
[ "vector" ]
30b36f4bab16884b7249689e715965e410e726fa
24,315
hh
C++
Kakadu/JP2_File_Reader.hh
pirl-lpl/libjp2
9815b55e8a5222018fe5f978ac0819e53aea5204
[ "Apache-2.0" ]
1
2019-07-31T19:47:53.000Z
2019-07-31T19:47:53.000Z
Kakadu/JP2_File_Reader.hh
pirl-lpl/libjp2
9815b55e8a5222018fe5f978ac0819e53aea5204
[ "Apache-2.0" ]
null
null
null
Kakadu/JP2_File_Reader.hh
pirl-lpl/libjp2
9815b55e8a5222018fe5f978ac0819e53aea5204
[ "Apache-2.0" ]
1
2022-03-11T05:40:11.000Z
2022-03-11T05:40:11.000Z
/* JP2_File_Reader HiROC CVS ID: $Id: JP2_File_Reader.hh,v 1.30 2012/04/26 02:55:48 castalia Exp $ Copyright (C) 2009-2012 Arizona Board of Regents on behalf of the Planetary Image Research Laboratory, Lunar and Planetary Laboratory at the University of Arizona. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *******************************************************************************/ #ifndef _JP2_File_Reader_ #define _JP2_File_Reader_ #include "JP2_Reader.hh" // PIRL++ #include "Dimensions.hh" #include "Reference_Counted_Pointer.hh" // Kakadu #include "jp2.h" #include "kdu_region_decompressor.h" #include <string> #include <sstream> #include <iomanip> namespace UA { namespace HiRISE { namespace Kakadu { // Forward references. class JP2_Box; /** A <i>JP2_File_Reader</i> reads image pixel data from a JPEG2000 JP2 standard format image file. This implementation employs the <a href="http://www.kakadusoftware.com/" target="_top">Kakadu Software</a> libraries. Programmer notes on the use of the Kakadu software: There are two possible sources of a JP2 file: A pathname for a local file, or a URL for a remote file provided by a JPIP server. If the source is a URL for a JPIP server (identified by a jpip:// or http:// protocol specifier; a file:// protocol is reverted to a pathname for a local file) a kdu_client is instantiated and its connect method is used to gain access to the remote file (a.k.a the resource). It is possible for the kdu_client to provide multiple channels for "compatible" URLs, but this capability has not yet been explored here. The kdu_client is a subclass of the kdu_cache which manages the data bins delivered by the JPIP server. The kdu_cache is a subclass of the kdu_compressed_source which is an abstract class providing access specific types of compressed sources. If the source is a pathname for a local file a jp2_family_src is instantiated and its open method is used to gain direct access to the local JP2 file. A kdu_cache can also be used with the open method, thus providing a point of commonality for handling either a local or remote source. The jp2_family_src object (named JP2_Stream here) may be used with the open method of a jp2_input_box to confirm that the first box contains the required JP2 signature. Then the box object may be used to step through all the boxes in the source using the open_next method. The jp2_family_src object is used to open a jp2_source object (named JP2_Source here) which provides full support for interacting with JP2 files. The jp2_source class is a subclass of jp2_input_box, so the JP2_Source may be used to scan all the JP2 boxes instead of using the JP2_Stream. The jp2_input_box class is a subclass of the kdu_compressed_source class. This would seem to suggest that a jp2_input_box opened on a jp2_family_src would be sufficient to provide the required kdu_compressed_source interface; however using the jp2_source appears to be the recommended approach from the Kakadu demo applications. Note that to open a jp2_source object a jp2_family_src (or jp2_input_box) object is required. The kdu_compressed_source is a key base class. It is required to open an input kdu_codestream which constructs the codestream management machinery used to render image data. There are various image data decompression classes, all of which require a kdu_compressed_source: The kdu_stripe_decompressor renders image stripes each of which is a contiguous sequence of image lines across the full width of the selected image region for all image components (bands). The kdu_region_deompressor allows selective regions and components of the image data to be rendered. The kdu_region_compositor is intended for very flexible rendering for image display purposes which limits the rendering to 8-bit per pixel RGB plus alpha image data. The hierarchy of object creation is: <dl> <dt>kdu_client.connect (URL) <dd>The JPIP_Client for a given source URL is constructed when a JP2_JPIP_Reader object is {@link JP2_JPIP_Reader::open(const std::string&) opened} for the first time. It is shared amongst copies of the JP2_JPIP_Reader object, with each copy obtaining a separate connection to the source via the JPIP_Client. A Data_Bin_Cache (kdu_cache) is object is attached to the JPIP_Client and acts an intermediary between the asynchronous network transfer mechanism of JP2 metadata and codestream packets from the JPIP server to the JPIP_Client, which deposits the data received in the Data_Bin_Cache, and the consumers of the data, which extracts data from the Data_Bin_Cache to obtain JP2 metadata and codestream packets for decompression and rendering. Each rendering engine has its own Data_Bin_Cache object, however each is attached to the same underlying JPIP_Client (itself a subclass of kdu_cache) where the incoming data is actually held. <dl> <dt>jp2_family_src.open (pathname or kdu_client) <dd>The JP2_Stream object (a jp2_threadsafe_family_src) is opened directly on a file containing JP2 data, or on Data_Bin_Cache that indirectly provides JP2 data. It manages access to the data from the source, whether a file or the data cache of a JPIP client, with a consistent interface. Each JP2_File_Reader has its own JP2_Stream object. <dl> <dt>jp2_source.open (jp2_family_src) <dd>The JP2_Source is opened on the JP2_Stream object. It is used to ensure that the JP2 metadata headers are all available, up to and including the main codestream header. At this point the JP2_Source can be used to create the codestream decompression and rendering machinery. Each JP2_File_Reader has its own JP2_Source object. <dl> <dt>kdu_codestream.create (jp2_source) <dd>The JPEG2000_Codestream, created using a JP2_Source object and an optional Thread_Group (kdu_thread_env), provides the codestream management machinery. Each JP2_File_Reader has its own JPEG2000_Codestream object. <dl> <dt>kdu_region_decompressor.start (kdu_codestream) <dd>The Decompressor is the rendering engine that gnerates image pixel data from a JPEG2000_Codestream using rendering control parameters for the rendering operation, and the optional Thread_Group for multi-threaded processing. This object is resuable. </dl> </dl> </dl> </dl> </dl> @author Bradford Castalia, UA/HiROC @version $Revision: 1.30 $ */ class JP2_File_Reader : public UA::HiRISE::JP2_Reader { public: /*============================================================================== Constants */ //! Class identification name with source code version and date. static const char* const ID; //! Decompression engine error exception signal value. static const kdu_core::kdu_exception READER_ERROR; /*============================================================================== Constructors */ /** Construct a JP2_File_Reader. The reader must be {@link open(const std::string&) opened} with a source. @see JP2_File_Reader(const std::string&) */ JP2_File_Reader (); /** Construct a JP2_File_Reader for a source JP2 file. <b>N.B.</b>: If the source can not be {@link is_open() successfully opened} the JP2_Reader will not be fully functional. @param source The pathname to a source file. @see open(const std::string&) */ explicit JP2_File_Reader (const std::string& source); /** Construct a copy of a JP2_File_Reader. @param JP2_file_reader The JP2_File_Reader to be copied. */ JP2_File_Reader (const JP2_File_Reader& JP2_file_reader); virtual ~JP2_File_Reader () throw(); /*============================================================================== Reader */ /** Clone this JP2_File_Reader. A copy of this JP2_File_Reader is constructed. @return A pointer to a copy of this JP2_File_Reader. */ virtual JP2_File_Reader* clone () const; /** Open the JP2_File_Reader on a source file. If the reader is not already open it is opened on the source file. @param source The pathname to a source file. @return The ID of the opened source. This will be zero if the reader is already open; otherwise it will be one. */ virtual int open (const std::string& source); /** Test if the reader is open. The reader is open if all three of its data stream management components - the JP2_Stream, JP2_Source and JPEG2000_Codestream - exist; i.e. the reader components have been opened/created but not closed/destroyed. @return true if the JP2_File_Reader has been successfully opened on the JP2 source and not yet closed; false otherwise. */ virtual bool is_open () const; /** Set the effective rendering resolution level and image region. The {@link resolution_level(unsigned int) resolution level} and {@link image_region(const Rectangle&) image region} interact to determine the {@link rendered_region() rendered image size} so they are set together. <b.N.B.</b>: If the reader has not been {@link open() opened} nothing is done. The effective resolution level is limited to the range 1 - {@link resolution_levels() resolution levels} and applied as an input restriction on the codestream rendering machinery. If the image region is empty the entire {@link image_size() image size} is used as the effective {@link image_region() image region}. Otherwise the dimensions of the image region are adjusted by the resolution level (divided by 2**(level - 1)), intersected with the image size at the rendering resolution and the resulting effective image region is applied as an input restriction on the codestream rendering machinery. Both the effective image region and {@link rendered_region() rendered image region} are set. <b>N.B.</b>: If the selected image region does not intersect with the image size an empty effective image region will result. @param resolution The rendering resolution level. @param region The selected image area to be rendered relative to the full resolution image. This will be clipped to the full image size. <b>N.B.</b>: If the region is empty the entire image will be selected. @return true if there was any change to the resolution or region; false otherwise. <b.N.B.</b>: If the data source is not open false is returned immediately. @throws JP2_Exception If a kdu_exception occured. */ virtual bool resolution_and_region (unsigned int resolution, const PIRL::Rectangle& region); /** Render the image data. The JP2 source is {@link open() opened} if this has not yet been done, and the reader is checked that it is {@link ready() ready}. Data buffers to hold horizontal stripes of rendered image data are allocated. The destination file is opened for writing. <b>N.B.</b>: If the file already exists the image data will be appended to the current content. @return A Cube indicated what was rendered. @throws JP2_Logic_Error If the reader is not ready(). @throws runtime_error If insufficient memory is available to allocate the rendered image data buffers. */ virtual Cube render (); /** Close access to the JP2 source. The JP2 source stream is closed and the rendering machinery resources associated with it are released. <b>N.B.</b>: The JP2 metadata describing the source and the reader's rendering configuration remain unchanged, so the source may be {@link open(const std::string&) opened} again for rendering using the previously set configuration. @param force Not used when closing a JP2_File_Reader. @see reset() */ virtual void close (bool force = false); /** Reset the reader to it's initial, default, state. The reader is {@link close(bool) closed}, any {@link deploy_processing_threads() processing threads} are released, and the rendering configuration and JP2 metadata are {@link JP2_Reader::reset() reset. */ virtual void reset (); /** Get the next available Kakadu reader error message. An error message will be pending delivery if this JP2_File_Reader throws a kdu_exception with a value of {@link #READER_ERROR). The expected response when this exception is caught is to use this method to obtain all available error messages from the Kakadu engine that threw the exception. The returned message string will contain at least a line identifying the exception value. All entries in the Kakadu error message queue, if any, are removed from the queue and appended to the message string before it is returned. @return A string containing an error message. */ std::string Kakadu_error_message (const kdu_core::kdu_exception& except); protected: //! Conceptual {@link data_request(Rectangle*, bool)} return values. enum { DATA_REQUEST_SATISFIED = -1, DATA_REQUEST_SUBMITTED = 1, DATA_REQUEST_REJECTED = 0 }; /** Provide a desription for a DATA_REQUEST_XXX return status value. @param status A {@link data_request(Rectangle*, bool)} return value. @return A string describing the status value. */ static std::string data_request_description (int status); /** Initiate a codestream data request for the contents of the region to be rendered. This method is a no-op for a JP2_File_Reader. It is provided for interface compatibility with a JP2_JPIP_Reader. @param region Ignored. @param preemptive Ignored. @return Always returns {@link #REQUEST_SATISFIED} because the data is available. */ virtual int data_request (Rectangle* region = NULL, bool preemptive = true); virtual int metadata_request (kdu_core::kdu_int32 box_type, bool preemptive = false); /** <i>Acquired_Data</i> describes the data that has been {@link data_aquisition(Acquired_Data*) acquired} from the last {@link data_request(Rectangle*, bool) data request}. The base Rectangle specifies the region of data that was acquired relative to the rendered resolution grid. The Resolution_Level member specifies the resolution level at which the data was acquired. */ struct Acquired_Data : public PIRL::Rectangle { //! The resolution level at which the data was acquired. int Resolution_Level; inline void acquired (unsigned int resolution_level, unsigned int x, unsigned int y, unsigned int width, unsigned int height) { Resolution_Level = resolution_level; position (x, y); size (width, height); } }; // Class Acquired_Data //! Bit flags for a {@link data_acquisition(Acquired_Data*)} return values. enum { DATA_ACQUISITION_COMPLETE = (1 << 0), DATA_ACQUISITION_INCOMPLETE = (1 << 1), DATA_ACQUISITION_REDUCED = (1 << 2), DATA_ACQUISITION_CANCELED = (1 << 3) }; /** Provide a desription for a DATA_ACQUISITION_XXX return status value. @param status A {@link data_acquisition(Acquired_Data*)} return value. @return A string describing the status value. */ static std::string data_acquisition_description (int status); /** Wait for an outstanding {@link data_request(Rectangle*, bool) data request} to complete. This method is a no-op (other than filling in the acquired data structure) for a JP2_File_Reader. It is provided for interface compatibility with a JP2_JPIP_Reader. @param acquired_data If non-null the Acquired_Data members will be filled with the description of the data that was acquired. @return Always returns DATA_ACQUISITION_COMPLETE. @see JP2_JPIP_Reader::data_acquistion(Acquired_Data*) */ virtual int data_acquisition (Acquired_Data* acquired_data = NULL); /*============================================================================ Helpers */ protected: /** Open and validate the JP2 source data stream. If the reader {@link is_open() is open} nothing is done. <b>N.B.</b>: The JP2_Stream object must have already been opened by the open method of the reader implementation; otherwise a JP2_Logic_Error exception will be thrown. If the JPEG2000_Codestream has been created (during a previous source opening procedure) it is destroyed. Likewise, if the JP2_Source has been opened it is closed. The JP2_Source is then opened on the JP2_Stream and the source headers are read. Failure to open the JP2_Source or read the headers - for a cached data source (i.e. a JPIP client for a JPIP server) up to ten attempts to read the headers, at one second intervals, are attempted - will cause a JP2_IO_Failure exception to be thrown. The first two header boxes in the source data stream must be JP2 Signature followed by a File Type. If these boxes are not found a JP2_Invalid_Argument exception is thrown. The JPEG2000_Codestream is created using the JP2_Source and any {@link deploy_processing_threads() data processing threads} deployed, and then set to be persistent for interactive (re)use. The JPEG2000_Codestream is then used to obtain the source image data characterization including the {@link JP2_Metadata::image_size() image size} and number of {@link JP2_Metadata::image_bands() image bands}, which are used to initialize the {@link JP2_Reader::image_region() image region} and {@link JP2_Reader::rendered_region() rendered region}; {@link JP2_Metadata::pixel_bits() pixel bits}, which are used to initialize the {@link rendered_pixel_bits() rendered pixel bits} if not already set; {@link JP2_Metadata::signed_data() signed data} condition; number of {@link resolution_levels() resolution levels} in the JPEG2000 codestream; {@link JP2_Metadata::producer_UUID() data producer UUID} and associated {@link JP2_Metadata::URL() URL} if present. If more than one image band is available each is checked to confirm that they all have the same dimensions, pixel bits and signed data condition; if differening data bands are present a JP2_Out_of_Range exception is thrown describing the problem. Finally, the basic image rendering configuration is initialized which prepares the reader to {@link render() render} the JPEG2000 codestream to image pixels. */ void open_source (); /** Initialize the JP2 metadata and rendering configuration. The JPEG2000_Codestream is used to obtain the source image data characterization including the {@link JP2_Metadata::image_size() image size} and number of {@link JP2_Metadata::image_bands() image bands}, which are used to initialize the {@link JP2_Reader::image_region() image region} and {@link JP2_Reader::rendered_region() rendered region}; {@link JP2_Metadata::pixel_bits() pixel bits}, which are used to initialize the {@link rendered_pixel_bits() rendered pixel bits} if not already set; {@link JP2_Metadata::signed_data() signed data} condition; number of {@link resolution_levels() resolution levels} in the JPEG2000 codestream; {@link JP2_Metadata::producer_UUID() data producer UUID} and associated {@link JP2_Metadata::URL() URL} if present. If more than one image band is available each is checked to confirm that they all have the same dimensions, pixel bits and signed data condition; if differening data bands are present a JP2_Out_of_Range exception is thrown describing the problem. At the same time that the JP2 metadata is initialzed the image rendering configuration is initialized from the JP2 metadata. This prepares the reader to {@link render() render} the JPEG2000 codestream to image pixels. @throws JP2_Out_of_Range If the image data bands do not all have the same dimensions. */ void initialize (); /** The JP2_Metadata is initialized. All JP2 boxes up to, but not including, the first codestream box are {@link load_box_content(JP2_Box&, unsigned char*) loaded} and each {@link JP2_Metadata::add_JP2_box (Type_Code, int, unsigned char*, long, long) box is added to the JP2_Metadata}. When the first codestream box is encountered its main header {@link ingest_codestream_segments(JP2_Box&) segments are added to the JP2_Metadata}. <b>N.B.</b>: After ingesting all the metadata its validity can be tested for {@link JP2_Metadata::is_complete() completeness} to ensure that all required information has been obtained from the data source. @return true if all metadata was successfully ingested; false if there was any problem loading JP2 box content. @throws JP2_Logic_Error If the metadata structure was found to be invalid for any reason. @throws invalid_argument If an invalid box value was encountered, probably because of data stream corruption. */ bool ingest_metadata (); /** Load the content of a JP2 box. The entire box content, starting with the first byte following the box header sequence and including any sub-boxes, is to be read into the content buffer. <b>N.B.</b>: The buffer must be large enough to hold the entire box content length, which can be determined from the get_remaining_bytes method. If the box has no content or has an indefinate length (get_remaining_bytes returns -1) that extends to the end of the source file then nothing will be done. @param box A JP2_Box reference. The box must be open and no content read (the read pointer positioned immediately following the header sequence). @param content A pointer to a buffer to receive the box content. <b>N.B.</b>: The buffer must be large enough to hold the entire box content, not including the header sequence. @return true if the box content was loaded into the content buffer; false if any problem occured. */ virtual bool load_box_content (JP2_Box& box, unsigned char* content); /** Codestream segments are added to the JP2_Metadata. The codestream main header segments up to, but not including, the first start-of-tile (SOT) segment are {@link JP2_Metadata::add_codestream_segment(Marker_Code, const unsigned char*, int, long) added to the JP2_Metadata}. <b>N.B.</b>: The codestream main header segments are presumed to be read accessible from the codestream box. @param codestream_box A reference to a JP2_Box for the image JPEG2000 codestream. The box must be open and no content read (the read pointer positioned immediately following the header sequence). @throws JP2_Logic_Error If the codestream structure was found to be invalid for any reason. @throws invalid_argument If an invalid segment value was encountered, probably because of data stream corruption. */ void ingest_codestream_segments (JP2_Box& codestream_box); /** Deploy JP2 codestream processing threads. If the Thread_Group for this reader has already been created or the number of {@link JP2_Reader::processing_threads() processing threads} to be used is less than two, nothing is done. A new Thread_Group is created and threads are added to it until the desired number of processing threads are present or the system refuses to provide more threads (in which case the number of reported processing threads is reduced accordingly). */ virtual void deploy_processing_threads (); /*============================================================================== Data */ protected: //------------------------------------------------------------------------------ // Kakadu classes used by both File and JPIP readers. //! JP2 file input stream. mutable kdu_supp::jp2_threadsafe_family_src JP2_Stream; //! JP2 content source. mutable kdu_supp::jp2_source JP2_Source; //! JPEG2000 codestream. mutable kdu_core::kdu_codestream JPEG2000_Codestream; //! Reusable codestream decompression machinery. mutable kdu_supp::kdu_region_decompressor Decompressor; // N.B.: Declared in kdu_region_decompressor.h kdu_supp::kdu_channel_mapping Channel_Mapping; kdu_core::kdu_coords Expand_Numerator, Expand_Denominator; /* Decompression processing threads. The Thread_Group is used by the rendering engine. */ kdu_core::kdu_thread_env *Thread_Group; kdu_core::kdu_thread_queue *Master_Queue; /* Kakadu error message queue. Note: The message queue object is thread safe. */ kdu_core::kdu_message_queue Error_Message_Queue; }; // Class JP2_File_Reader } // namespace Kakadu } // namespace HiRISE } // namespace UA #endif
37.639319
85
0.758421
[ "render", "object" ]
30bb7acb544a3fc17f72efc39ca075adbeb9fab5
6,939
cc
C++
code/Samples/Instancing/Instancing.cc
infancy/oryol
06b580116cc2e929b9e1a85920a74fb32d76493c
[ "MIT" ]
1,707
2015-01-01T14:56:08.000Z
2022-03-28T06:44:09.000Z
code/Samples/Instancing/Instancing.cc
infancy/oryol
06b580116cc2e929b9e1a85920a74fb32d76493c
[ "MIT" ]
256
2015-01-03T14:55:53.000Z
2020-09-09T10:43:46.000Z
code/Samples/Instancing/Instancing.cc
infancy/oryol
06b580116cc2e929b9e1a85920a74fb32d76493c
[ "MIT" ]
222
2015-01-05T00:20:54.000Z
2022-02-06T01:41:37.000Z
//------------------------------------------------------------------------------ // Instancing.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "Core/Main.h" #include "Core/Time/Clock.h" #include "Gfx/Gfx.h" #include "Assets/Gfx/ShapeBuilder.h" #include "Dbg/Dbg.h" #include "Input/Input.h" #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/random.hpp" #include "shaders.h" using namespace Oryol; class InstancingApp : public App { public: AppState::Code OnInit(); AppState::Code OnRunning(); AppState::Code OnCleanup(); void updateCamera(); void emitParticles(); void updateParticles(); // the static geometry is at mesh slot 0, and the instance data at slot 1 static const int geomMeshSlot = 0; static const int instMeshSlot = 1; DrawState drawState; glm::mat4 view; glm::mat4 proj; glm::mat4 model; Shader::vsParams vsParams; bool updateEnabled = true; int frameCount = 0; int curNumParticles = 0; TimePoint lastFrameTimePoint; static const int MaxNumParticles = 1024 * 1024; const int NumParticlesEmittedPerFrame = 100; glm::vec4 positions[MaxNumParticles]; glm::vec4 vectors[MaxNumParticles]; }; OryolMain(InstancingApp); //------------------------------------------------------------------------------ AppState::Code InstancingApp::OnInit() { // setup rendering system Gfx::Setup(GfxSetup::Window(800, 500, "Oryol Instancing Sample")); Dbg::Setup(); Input::Setup(); // check instancing extension if (!Gfx::QueryFeature(GfxFeature::Instancing)) { o_error("ERROR: instanced_arrays extension required!\n"); } // create static mesh at mesh slot 0 const glm::mat4 rot90 = glm::rotate(glm::mat4(), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); ShapeBuilder shapeBuilder; shapeBuilder.RandomColors = true; shapeBuilder.Layout = { { VertexAttr::Position, VertexFormat::Float3 }, { VertexAttr::Color0, VertexFormat::Float4 } }; shapeBuilder.Transform(rot90).Sphere(0.05f, 3, 2); auto shapeBuilderResult = shapeBuilder.Build(); this->drawState.Mesh[0] = Gfx::CreateResource(shapeBuilderResult); // create dynamic instance data mesh at mesh slot 1 auto instMeshSetup = MeshSetup::Empty(MaxNumParticles, Usage::Stream); instMeshSetup.Layout .EnableInstancing() .Add(VertexAttr::Instance0, VertexFormat::Float4); this->drawState.Mesh[1] = Gfx::CreateResource(instMeshSetup); // setup draw state for instanced rendering Id shd = Gfx::CreateResource(Shader::Setup()); auto ps = PipelineSetup::FromShader(shd); ps.Layouts[0] = shapeBuilder.Layout; ps.Layouts[1] = instMeshSetup.Layout; ps.RasterizerState.CullFaceEnabled = true; ps.DepthStencilState.DepthWriteEnabled = true; ps.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; this->drawState.Pipeline = Gfx::CreateResource(ps); // setup projection and view matrices const float fbWidth = (const float) Gfx::DisplayAttrs().FramebufferWidth; const float fbHeight = (const float) Gfx::DisplayAttrs().FramebufferHeight; this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f); return App::OnInit(); } //------------------------------------------------------------------------------ AppState::Code InstancingApp::OnRunning() { Duration updTime, bufTime, drawTime; this->frameCount++; // update block this->updateCamera(); if (this->updateEnabled) { TimePoint updStart = Clock::Now(); this->emitParticles(); this->updateParticles(); updTime = Clock::Since(updStart); TimePoint bufStart = Clock::Now(); Gfx::UpdateVertices(this->drawState.Mesh[instMeshSlot], this->positions, this->curNumParticles * sizeof(glm::vec4)); bufTime = Clock::Since(bufStart); } // render block TimePoint drawStart = Clock::Now(); Gfx::BeginPass(); Gfx::ApplyDrawState(this->drawState); Gfx::ApplyUniformBlock(this->vsParams); Gfx::Draw(0, this->curNumParticles); drawTime = Clock::Since(drawStart); Dbg::DrawTextBuffer(); Gfx::EndPass(); Gfx::CommitFrame(); // toggle particle update if ((Input::MouseAttached() && Input::MouseButtonDown(MouseButton::Left)) || (Input::TouchpadAttached() && Input::TouchTapped())) { this->updateEnabled = !this->updateEnabled; } Duration frameTime = Clock::LapTime(this->lastFrameTimePoint); Dbg::PrintF("\n %d instances\n\r upd=%.3fms\n\r bufUpd=%.3fms\n\r draw=%.3fms\n\r frame=%.3fms\n\r" " LMB/Tap: toggle particle updates", this->curNumParticles, updTime.AsMilliSeconds(), bufTime.AsMilliSeconds(), drawTime.AsMilliSeconds(), frameTime.AsMilliSeconds()); return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running; } //------------------------------------------------------------------------------ void InstancingApp::updateCamera() { float angle = this->frameCount * 0.01f; glm::vec3 pos(glm::sin(angle) * 10.0f, 2.5f, glm::cos(angle) * 10.0f); this->view = glm::lookAt(pos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); this->vsParams.mvp = this->proj * this->view * this->model; } //------------------------------------------------------------------------------ void InstancingApp::emitParticles() { for (int i = 0; i < NumParticlesEmittedPerFrame; i++) { if (this->curNumParticles < MaxNumParticles) { this->positions[this->curNumParticles] = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); glm::vec3 rnd = glm::ballRand(0.5f); rnd.y += 2.0f; this->vectors[this->curNumParticles] = glm::vec4(rnd, 0.0f); this->curNumParticles++; } } } //------------------------------------------------------------------------------ void InstancingApp::updateParticles() { const float frameTime = 1.0f / 60.0f; for (int i = 0; i < this->curNumParticles; i++) { auto& pos = this->positions[i]; auto& vec = this->vectors[i]; vec.y -= 1.0f * frameTime; pos += vec * frameTime; if (pos.y < -2.0f) { pos.y = -1.8f; vec.y = -vec.y; vec *= 0.8f; } } } //------------------------------------------------------------------------------ AppState::Code InstancingApp::OnCleanup() { Input::Discard(); Dbg::Discard(); Gfx::Discard(); return App::OnCleanup(); }
35.403061
125
0.558726
[ "mesh", "geometry", "render", "model", "transform" ]
30bcbc35f31af2f89fbe4a79f467188c8d97cb05
5,637
cc
C++
elements/wifi/availablerates.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/wifi/availablerates.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/wifi/availablerates.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
/* * availablerates.{cc,hh} -- Poor man's arp table * John Bicket * * Copyright (c) 2003 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/args.hh> #include <click/error.hh> #include <click/glue.hh> #include <click/straccum.hh> #include <clicknet/ether.h> #include "availablerates.hh" CLICK_DECLS AvailableRates::AvailableRates() { /* bleh */ static unsigned char bcast_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; _bcast = EtherAddress(bcast_addr); } AvailableRates::~AvailableRates() { } void * AvailableRates::cast(const char *n) { if (strcmp(n, "AvailableRates") == 0) return (AvailableRates *) this; else return 0; } int AvailableRates::parse_and_insert(String s, ErrorHandler *errh) { EtherAddress e; Vector<int> rates; Vector<String> args; cp_spacevec(s, args); if (args.size() < 2) { return errh->error("error param %s must have > 1 arg", s.c_str()); } bool default_rates = false; if (args[0] == "DEFAULT") { default_rates = true; _default_rates.clear(); } else { if (!EtherAddressArg().parse(args[0], e)) return errh->error("error param %s: must start with ethernet address", s.c_str()); } for (int x = 1; x< args.size(); x++) { int r; IntArg().parse(args[x], r); if (default_rates) { _default_rates.push_back(r); } else { rates.push_back(r); } } if (default_rates) { return 0; } DstInfo d = DstInfo(e); d._rates = rates; d._eth = e; _rtable.insert(e, d); return 0; } int AvailableRates::configure(Vector<String> &conf, ErrorHandler *errh) { int res = 0; _debug = false; for (int x = 0; x < conf.size(); x++) { res = parse_and_insert(conf[x], errh); if (res != 0) { return res; } } return res; } void AvailableRates::take_state(Element *e, ErrorHandler *) { AvailableRates *q = (AvailableRates *)e->cast("AvailableRates"); if (!q) return; _rtable = q->_rtable; _default_rates = _default_rates; } Vector<int> AvailableRates::lookup(EtherAddress eth) { if (!eth) { click_chatter("%s: lookup called with NULL eth!\n", name().c_str()); return Vector<int>(); } DstInfo *dst = _rtable.findp(eth); if (dst) { return dst->_rates; } if (_default_rates.size()) { return _default_rates; } return Vector<int>(); } int AvailableRates::insert(EtherAddress eth, Vector<int> rates) { if (!(eth)) { if (_debug) { click_chatter("AvailableRates %s: You fool, you tried to insert %s\n", name().c_str(), eth.unparse().c_str()); } return -1; } DstInfo *dst = _rtable.findp(eth); if (!dst) { _rtable.insert(eth, DstInfo(eth)); dst = _rtable.findp(eth); } dst->_eth = eth; dst->_rates.clear(); if (_default_rates.size()) { /* only add rates that are in the default rates */ for (int x = 0; x < rates.size(); x++) { for (int y = 0; y < _default_rates.size(); y++) { if (rates[x] == _default_rates[y]) { dst->_rates.push_back(rates[x]); } } } } else { dst->_rates = rates; } return 0; } enum {H_DEBUG, H_INSERT, H_REMOVE, H_RATES}; static String AvailableRates_read_param(Element *e, void *thunk) { AvailableRates *td = (AvailableRates *)e; switch ((uintptr_t) thunk) { case H_DEBUG: return String(td->_debug) + "\n"; case H_RATES: { StringAccum sa; if (td->_default_rates.size()) { sa << "DEFAULT "; for (int x = 0; x < td->_default_rates.size(); x++) { sa << " " << td->_default_rates[x]; } sa << "\n"; } for (AvailableRates::RIter iter = td->_rtable.begin(); iter.live(); iter++) { AvailableRates::DstInfo n = iter.value(); sa << n._eth.unparse() << " "; for (int x = 0; x < n._rates.size(); x++) { sa << " " << n._rates[x]; } sa << "\n"; } return sa.take_string(); } default: return String(); } } static int AvailableRates_write_param(const String &in_s, Element *e, void *vparam, ErrorHandler *errh) { AvailableRates *f = (AvailableRates *)e; String s = cp_uncomment(in_s); switch((intptr_t)vparam) { case H_DEBUG: { bool debug; if (!BoolArg().parse(s, debug)) return errh->error("debug parameter must be boolean"); f->_debug = debug; break; } case H_INSERT: return f->parse_and_insert(in_s, errh); case H_REMOVE: { EtherAddress e; if (!EtherAddressArg().parse(s, e)) return errh->error("remove parameter must be ethernet address"); f->_rtable.erase(e); break; } } return 0; } void AvailableRates::add_handlers() { add_read_handler("debug", AvailableRates_read_param, H_DEBUG); add_read_handler("rates", AvailableRates_read_param, H_RATES); add_write_handler("debug", AvailableRates_write_param, H_DEBUG); add_write_handler("insert", AvailableRates_write_param, H_INSERT); add_write_handler("remove", AvailableRates_write_param, H_REMOVE); } CLICK_ENDDECLS EXPORT_ELEMENT(AvailableRates)
22.914634
88
0.641121
[ "vector" ]
30c587480fa54eedc0f712c7547e146868341a9d
8,853
cpp
C++
sim_band_planner/src/simulate.cpp
Boeing/modular_navigation
1489fdf94079fd6b1d3a41d0fc18924f43805a52
[ "Apache-2.0" ]
7
2020-11-24T03:53:26.000Z
2022-02-23T08:13:59.000Z
sim_band_planner/src/simulate.cpp
Boeing/modular_navigation
1489fdf94079fd6b1d3a41d0fc18924f43805a52
[ "Apache-2.0" ]
null
null
null
sim_band_planner/src/simulate.cpp
Boeing/modular_navigation
1489fdf94079fd6b1d3a41d0fc18924f43805a52
[ "Apache-2.0" ]
7
2020-11-27T12:24:45.000Z
2022-02-23T08:14:02.000Z
#include <ros/assert.h> #include <sim_band_planner/simulate.h> #include <sstream> #include <vector> namespace sim_band_planner { double simulate(Band& path, const DistanceField& distance_field, const int num_iterations, const double collision_distance, const double nominal_force_gain, const double internal_force_gain, const double external_force_gain, const double rotation_gain, const double velocity_decay, const double alpha_start, const double alpha_decay) { const double dt = 1.0; double alpha = alpha_start; for (int it = 0; it < num_iterations; it++) { updateDistances(path, distance_field); // f = ... std::vector<Eigen::Vector3d> forces(path.nodes.size(), Eigen::Vector3d::Zero()); for (std::size_t i = 1; i < path.nodes.size() - 1; ++i) { const auto internal_force = internalForce(path.nodes[i - 1], path.nodes[i], path.nodes[i + 1], internal_force_gain); const auto rotation_force = rotationForce(path.nodes[i - 1], path.nodes[i], path.nodes[i + 1], rotation_gain, collision_distance); const auto external_force = externalForce(path.nodes[i], external_force_gain, collision_distance); const auto nominal_force = nominalForce(path.nodes[i], nominal_force_gain); forces[i] = (internal_force + rotation_force + external_force + nominal_force); ROS_ASSERT(forces[i].allFinite()); } // a = f / m const std::vector<Eigen::Vector3d> acc = forces; // v = v + a * dt; for (std::size_t i = 1; i < path.nodes.size() - 1; ++i) { ROS_ASSERT(acc[i].allFinite()); path.nodes[i].velocity += alpha * acc[i] * dt; path.nodes[i].velocity *= velocity_decay; } // s = vt for (std::size_t i = 1; i < path.nodes.size() - 2; ++i) { path.nodes[i].pose.pretranslate(dt * Eigen::Vector2d(path.nodes[i].velocity.topRows(2))); path.nodes[i].pose.rotate(Eigen::Rotation2Dd(dt * path.nodes[i].velocity[2])); } alpha -= alpha * alpha_decay; } updateDistances(path, distance_field); return alpha; } void updateDistances(Node& node, const DistanceField& distance_field) { double min_distance = std::numeric_limits<double>::max(); node.closest_point = 0; for (std::size_t i = 0; i < node.control_points.size(); ++i) { ControlPoint& control_point = node.control_points[i]; const Eigen::Vector2d position = node.pose.translation() + node.pose.linear() * control_point.offset; unsigned int mx; unsigned int my; if (distance_field.worldToMap(position.x(), position.y(), mx, my)) { control_point.distance_to_saddle = static_cast<double>(distance_field.distanceToSaddle(mx, my)); control_point.distance = static_cast<double>(distance_field.distance(mx, my)) * distance_field.resolution; control_point.gradient = control_point.distance > 0 ? distance_field.positiveGradient(mx, my) : distance_field.negativeGradient(mx, my); } else { control_point.distance_to_saddle = 0; control_point.distance = 0; control_point.gradient = Eigen::Vector2f::Zero(); } if (control_point.distance < min_distance) { node.closest_point = i; min_distance = control_point.distance; } } } void updateDistances(Band& path, const DistanceField& distance_field) { for (std::size_t i = 0; i < path.nodes.size(); ++i) { updateDistances(path.nodes[i], distance_field); } } Eigen::Vector3d internalForce(const Node& prev, const Node& curr, const Node& next, const double gain) { const Eigen::Vector2d d_1 = prev.pose.translation() - curr.pose.translation(); const Eigen::Vector2d d_2 = next.pose.translation() - curr.pose.translation(); const double d_1_norm = d_1.norm(); const double d_2_norm = d_2.norm(); ROS_ASSERT(std::isfinite(d_1_norm)); ROS_ASSERT(std::isfinite(d_2_norm)); const Eigen::Vector2d d_1_normalized = d_1_norm > 0 ? d_1 / d_1_norm : Eigen::Vector2d{0.0, 0.0}; const Eigen::Vector2d d_2_normalized = d_2_norm > 0 ? d_2 / d_2_norm : Eigen::Vector2d{0.0, 0.0}; Eigen::Vector3d _force = Eigen::Vector3d::Zero(); // straightening force if (d_1_norm > std::numeric_limits<double>::epsilon() && d_2_norm > std::numeric_limits<double>::epsilon()) { _force.topRows(2) = gain * (d_1_normalized + d_2_normalized); } if (d_1_norm > std::numeric_limits<double>::epsilon()) { // attracting force _force.topRows(2) += 2 * gain * d_1; } if (d_2_norm > std::numeric_limits<double>::epsilon()) { // attracting force _force.topRows(2) += 2 * gain * d_2; } ROS_ASSERT_MSG(_force.allFinite(), "internal force: %f %f %f", _force[0], _force[1], _force[2]); return _force; } Eigen::Vector3d rotationForce(const Node& prev, const Node& curr, const Node& next, const double rotation_gain, const double collision_distance) { const Eigen::Rotation2Dd rot_1 = Eigen::Rotation2Dd(prev.pose.linear().inverse() * curr.pose.linear()); const Eigen::Rotation2Dd rot_2 = Eigen::Rotation2Dd(next.pose.linear().inverse() * curr.pose.linear()); Eigen::Vector3d _force = Eigen::Vector3d::Zero(); // rotation equalising force _force[2] = -2 * rotation_gain * (rot_1.smallestAngle() + rot_2.smallestAngle()) / 2.0; // when close to objects rotate to avoid them otherwise rotate to face forward const ControlPoint& curr_min = curr.control_points[curr.closest_point]; // if (curr_min.distance > collision_distance) // { // // face forward (or backwards) force // if (d_2_norm > std::numeric_limits<double>::epsilon()) // { // const Eigen::Vector2d pose_dir = curr.pose.linear() * Eigen::Vector2d::UnitX(); // const double dot = pose_dir.dot(d_2_normalized); // const double det = pose_dir.x() * d_2_normalized.y() - pose_dir.y() * d_2_normalized.x(); // double fwd_angle = std::atan2(det, dot); // if (fwd_angle > M_PI / 2.0) // fwd_angle = M_PI - fwd_angle; // else if (fwd_angle < -M_PI / 2.0) // fwd_angle = -M_PI - fwd_angle; // _force[2] += rotation_gain * fwd_angle; // } // } // else if (curr_min.distance < collision_distance) { // control point torque double cp_torque = 0; double scale = 0.1 * std::min(1.0, curr_min.distance_to_saddle); if (curr_min.distance < 0) scale *= -1; const Eigen::Vector3d rotation_force = scale * Eigen::Vector3d(static_cast<double>(curr_min.gradient.x()), static_cast<double>(curr_min.gradient.y()), 0); const auto rot_offset = curr.pose.linear() * curr_min.offset; const Eigen::Vector3d offset_3d(rot_offset.x(), rot_offset.y(), 0); const auto tau = offset_3d.cross(rotation_force); cp_torque = -tau.z(); _force[2] += rotation_gain * cp_torque; } ROS_ASSERT_MSG(_force.allFinite(), "internal force: %f %f %f", _force[0], _force[1], _force[2]); return _force; } Eigen::Vector3d externalForce(const Node& curr, const double gain, const double collision_distance) { const ControlPoint& curr_min = curr.control_points[curr.closest_point]; Eigen::Vector3d _force; double decay = curr_min.distance < collision_distance ? std::min(4.0, collision_distance / curr_min.distance) : 0.0; decay *= std::min(1.0, std::max(0.1, curr_min.distance_to_saddle)); _force[0] = -gain * static_cast<double>(curr_min.gradient.x()) * decay; _force[1] = -gain * static_cast<double>(curr_min.gradient.y()) * decay; _force[2] = 0.0; ROS_ASSERT(_force.allFinite()); return _force; } Eigen::Vector3d nominalForce(const Node& curr, const double gain) { const Eigen::Vector2d dir = curr.nominal.translation() - curr.pose.translation(); const Eigen::Rotation2Dd rot = Eigen::Rotation2Dd(curr.nominal.linear().inverse() * curr.pose.linear()); const double dist = dir.norm(); ROS_ASSERT(std::isfinite(dist)); Eigen::Vector3d _force; _force[0] = gain * std::exp(dist) * dir.x(); _force[1] = gain * std::exp(dist) * dir.y(); _force[2] = -0.1 * gain * rot.smallestAngle(); ROS_ASSERT(_force.allFinite()); return _force; } } // namespace sim_band_planner
38.659389
120
0.616175
[ "vector" ]
30c897b8e11ea1b2e4c47a2282190b0344f30f72
7,113
cpp
C++
datastruct/stack/main.cpp
lugt/cprogram-oj
6d2de77846a19270da83354486629ed6cba16e9d
[ "Apache-2.0" ]
1
2018-10-10T13:39:22.000Z
2018-10-10T13:39:22.000Z
datastruct/stack/main.cpp
lugt/cprogram-oj
6d2de77846a19270da83354486629ed6cba16e9d
[ "Apache-2.0" ]
null
null
null
datastruct/stack/main.cpp
lugt/cprogram-oj
6d2de77846a19270da83354486629ed6cba16e9d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> #include <stack> #include <vector> #include <stdio.h> #include <stdlib.h> #include <memory.h> #define OK 0 #define FAIL 1 #define MAX_SIZE 10000 #define NULLPTR NULL #define TRUE true #define FALSE false #define Is_Print(cond, parm) if(cond) printf parm #define Df_do_seq(a, b, c) \ std::cin >> b; \ if(a.c(b - 1) >= 0){ \ a.print(); \ } #define Df_do_dseq(a, b1, b2, c) \ std::cin >> b1 >> b2; \ if(a.c(b1 - 1, b2) >= 0){ \ a.print(); \ } #define Df_do_ddseq(a, b1, b2, c) \ std::cin >> b1 >> b2; \ if(a.c(b1 - 1, b2 - 1) >= 0){ \ a.print(); \ } #define Df_do_fseq(a, b1, b2, c) \ std::cin >> b1 >> b2; \ if(a.c(b1, b2) >= 0){ \ a.print(); \ } typedef char CHAR; typedef int INT; typedef long INT64; typedef unsigned int UINT; typedef unsigned long UINT64; typedef char** CHPPTR; typedef char* CHPTR; typedef const char* CCHPTR; typedef bool BOOL; typedef std::string STRING; INT compare_int(const void* lhs, const void *rhs); inline BOOL Printing(){ return TRUE; } INT compare_int(const void* lhs, const void *rhs){ return *((INT *)lhs) - *((INT *)rhs); } template<typename T> class Stacks{ std::stack<T> stlist; }; template<typename T2> struct ListNode{ int pos; ListNode *head; ListNode *next; union { INT *intData; void *voidData; CHPTR charData; T2 *tData; UINT uintData; } kid; }; //typedef ListNode<INT> LNODE; typedef CHAR LNODE; typedef std::stack<LNODE> STLSTK; UINT64 Str_Push(STLSTK *list, CCHPTR str){ UINT64 i = 0; UINT64 len = strlen(str); for(i = 0; i < len; i++){ list->push(str[i]); } return len; } void Str_Print(STLSTK * list, UINT64 len){ UINT64 i = 0; for(i = 0 ; i < len ; i++ ){ CHAR st = list->top(); list->pop(); std::cout << st; } std::cout << std::endl; } INT Str_Check(STRING str, UINT max){ for(INT i = 0; i < str.size() ; i++){ if(str[i] > '0' + max){ return -1; } } return 0; } STRING outstr = ""; INT Str_Sequence_Check (STLSTK * orig, CCHPTR in, UINT64 len, CCHPTR out){ std::stringstream sstr; Is_Print(Printing(), (" Seq Check, [lhs] = %lu [rhs] = %s,\n", len, out)); UINT64 i = 0; UINT64 cur_in = 0; UINT64 cur_out = 0; while (len > 0 && cur_in != len){ Is_Print(Printing(), (" [Seq_Check]::[while] again, cur_in : %ld, cur_out: %ld\n", cur_in, cur_out)); Is_Print(Printing(), (" [Seq_Check]::[pushing] : %d \n", in[cur_in])); orig->push(in[cur_in++]); sstr << "in\n" ; CHAR st = orig->top(); Is_Print(Printing(), (" [Seq_Check]::while-check: out[%lu] <%c> == st:<%c> \n", cur_out, out[cur_out], st)); while(out[cur_out] == st){ Is_Print(Printing(), (" [Seq_Check]::popping : cur_in:%lu, cur_out:%lu, to_pop:%d, stack_size:%ld \n", cur_in, cur_out, orig->top(), orig->size())); orig->pop(); if(!orig->empty()) { st = orig->top(); Is_Print(Printing(), (" [Seq_Check]::inside-while-new-top, top:%c, size:%ld\n", st, orig->size())); }else{ st = '$'; } cur_out++; sstr << "out\n" ; if(cur_out >= len){ Is_Print(Printing(), (" [Seq_Check]::out-finished in:%lu, out:%lu \n", cur_in, cur_out)); break; } Is_Print(Printing(), (" [Seq_Check]::inside-while-check: out[%lu] <%c> == st:<%c> \n", cur_out, out[cur_out], st)); } } outstr = sstr.str(); if(cur_out < len) return -1; return 0; } CHAR Get_counter(CHAR in){ switch(in){ case '{': return '}'; case '[': return ']'; case '(': return ')'; case '}': return '{'; case ']': return '['; case ')': return '('; default: return '\n'; } } //============================================================================= // Main Entry // @param INT argc //============================================================================= int main(INT argc, CHPPTR argv) { INT n = 0; INT p = 0; INT num = 0; INT direct = 0; INT diff = 0; CHAR ch = 0; STLSTK my, out; CHPTR chbuf = new char[10000]; BOOL failed = FALSE; INT pos = 0; #if 0 length = Str_Push(&my, "something"); Is_Print(Printing(), ("sizeof(LNODE) == %d \n", sizeof(LNODE))); #endif std::cin >> n; while(n--){ memset(chbuf, 0, sizeof(char) * 10000); std::cin.getline(chbuf, 2000); pos = 0; p = (INT) (strlen(chbuf)); ch = chbuf[pos]; diff = 0; if(p == 0) { n++; continue; } pos++; Is_Print(Printing(), (" readline : == %s \n", chbuf)); while(ch != EOF && ch != '\n') { if(ch == '{' || ch == '[' || ch == '('){ Is_Print(Printing(), (" [main]::push, ch=%c, stack-size:%ld, pos:%d\n", ch, my.size(), pos)); my.push(ch); }else if(ch == '}' || ch == ']' || ch == ')'){ if(!my.empty()){ Is_Print(Printing(), (" [main]::check not-empty, ch=%c, pos:%d\n", ch, pos)); if(my.top() == Get_counter(ch)){ Is_Print(Printing(), (" [main]::check fit, stack-top:%c\n", my.top())); my.pop(); }else{ Is_Print(Printing(), (" [main]::not-fit because of missing lhs, stack-top:%c\n", my.top())); my.push(Get_counter(ch)); my.pop(); diff ++; } }else { Is_Print(Printing(), (" [main]::not-fit because of missing lhs, stack-top:%c\n", my.top())); my.push(Get_counter(ch)); my.pop(); diff ++; } } if(pos >= p) { Is_Print(Printing(), (" [main]::str finished for check\n")); break; } ch = (CHAR) chbuf[pos++]; } Is_Print(Printing(), (" [main]::calculating diff, my.size=:%ld\n", my.size())); diff += my.size(); std::cout << diff << "\n"; if(Printing()) { if (!failed && my.size() == 0) { std::cout << "0\n"; } else { std::cout << "error\n"; } } my = * new STLSTK(); } getchar(); getchar(); return 0; }
24.612457
109
0.432026
[ "vector" ]
30d2f41a41391fc568d0cec5354183597d879b9e
20,599
cpp
C++
VideoScriptEditor/VideoScriptEditor.PreviewRenderer/ScriptVideoService.cpp
danjoconnell/VideoScriptEditor
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
[ "MIT" ]
null
null
null
VideoScriptEditor/VideoScriptEditor.PreviewRenderer/ScriptVideoService.cpp
danjoconnell/VideoScriptEditor
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
[ "MIT" ]
null
null
null
VideoScriptEditor/VideoScriptEditor.PreviewRenderer/ScriptVideoService.cpp
danjoconnell/VideoScriptEditor
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
[ "MIT" ]
1
2021-02-04T16:43:57.000Z
2021-02-04T16:43:57.000Z
#include "pch.h" #include "ScriptVideoService.h" using namespace System; using namespace System::Collections::Generic; using namespace System::ComponentModel; using namespace VideoScriptEditor::Extensions; using namespace VideoScriptEditor::Models; using namespace VideoScriptEditor::Models::Primitives; using namespace VideoScriptEditor::PreviewRenderer; using System::Drawing::Size; using System::Diagnostics::Debug; namespace VideoScriptEditor::Services::ScriptVideo { ScriptVideoService::ScriptVideoService(Services::Dialog::ISystemDialogService^ systemDialogService) : ScriptVideoServiceBase(), _internalContext(gcnew ScriptVideoContext(this, systemDialogService)) { try { _nativeController = new PreviewRenderer::Unmanaged::ScriptVideoController(); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(stdException); } } ScriptVideoService::~ScriptVideoService() { // Deallocate the native object on a destructor delete _nativeController; } ScriptVideoService::!ScriptVideoService() { // Deallocate the native object on the finalizer just in case no destructor is called delete _nativeController; } void ScriptVideoService::SetPresentationWindow(System::IntPtr windowHandle) { try { _nativeController->SetDirect3D9DeviceWindow(static_cast<HWND>(windowHandle.ToPointer())); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } } void ScriptVideoService::ApplyMaskingPreviewToSourceRender() { _internalContext->ApplyMaskingPreviewToSourceRender = true; RenderUnmanagedSourceFrameSurface(); } void ScriptVideoService::RemoveMaskingPreviewFromSourceRender() { _internalContext->ApplyMaskingPreviewToSourceRender = false; RenderUnmanagedSourceFrameSurface(); } void ScriptVideoService::LoadUnmanagedAviSynthScriptFromFile(String^ scriptFileName) { std::string scriptFileNameNative; MarshalString(scriptFileName, scriptFileNameNative); PreviewRenderer::Unmanaged::LoadedScriptVideoInfo loadedScriptVideoInfo = { 0 }; try { loadedScriptVideoInfo = _nativeController->LoadAviSynthScriptFromFile(scriptFileNameNative); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(stdException); } if (!loadedScriptVideoInfo.HasVideo) { throw gcnew IO::InvalidDataException(String::Format("AviSynth script '{0}' doesn't output a video", scriptFileName)); } if (_internalContext->ScriptFileSource != scriptFileName) { _internalContext->SetScriptFileSourceInternal(scriptFileName); } _internalContext->SetVideoPropertiesFromUnmanagedStruct(loadedScriptVideoInfo); } void ScriptVideoService::InitializeUnmanagedPreviewRenderSurface() { VideoSizeOptions outputPreviewSize = _internalContext->OutputPreviewSize; PreviewRenderer::Unmanaged::VideoSizeInfo previewVideoSizeOptions; previewVideoSizeOptions.SizeMode = VideoResizeModeToUnmanagedVideoSizeMode(outputPreviewSize.ResizeMode); previewVideoSizeOptions.Width = outputPreviewSize.PixelWidth; previewVideoSizeOptions.Height = outputPreviewSize.PixelHeight; try { _nativeController->InitializePreviewRenderSurface(previewVideoSizeOptions); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } } void ScriptVideoService::PushNewSourceRenderSurfaceToSubscribers() { IDirect3DSurface9Ptr renderSurfaceComPtr; try { _nativeController->GetSourceFrameDirect3D9RenderSurface(renderSurfaceComPtr); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } OnNewSourceRenderSurface(IntPtr(renderSurfaceComPtr.GetInterfacePtr())); } void ScriptVideoService::PushNewPreviewRenderSurfaceToSubscribers() { IDirect3DSurface9Ptr renderSurfaceComPtr; try { _nativeController->GetPreviewFrameDirect3D9RenderSurface(renderSurfaceComPtr); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(comError); } OnNewPreviewRenderSurface(IntPtr(renderSurfaceComPtr.GetInterfacePtr())); } void ScriptVideoService::RenderUnmanagedFrameSurfaces(int frameNumber) { try { _nativeController->RenderFrameSurfaces(frameNumber, _internalContext->ApplyMaskingPreviewToSourceRender); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(GetRenderFrameErrorMessage(frameNumber), comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(GetRenderFrameErrorMessage(frameNumber), stdException); } } void ScriptVideoService::RenderUnmanagedPreviewFrameSurface() { try { _nativeController->RenderPreviewFrameSurface(_internalContext->ApplyMaskingPreviewToSourceRender); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(RenderPreviewFrameErrorMessage, comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(RenderPreviewFrameErrorMessage, stdException); } OnSurfaceRendered(SurfaceRenderPipeline::OutputPreview); } void ScriptVideoService::SetUnmanagedMaskingPreviewItems(System::Collections::Generic::IEnumerable<SegmentKeyFrameLerpDataItem>^ maskingKeyFrameLerpDataItems) { auto& unmanagedMaskingPreviewItems = _nativeController->get_MaskingPreviewItems(); bool geometryGroupNeedsUpdate = false; std::vector<int> activeTrackNumbers; for each (SegmentKeyFrameLerpDataItem keyFrameLerpDataItem in maskingKeyFrameLerpDataItems) { activeTrackNumbers.push_back(keyFrameLerpDataItem.TrackNumber); // Get existing or insert new item keyed on Track number auto& unmanagedMaskPreviewItemPair = unmanagedMaskingPreviewItems[keyFrameLerpDataItem.TrackNumber]; if (SetUnmanagedMaskDataItemFromLerpedKeyFrames(keyFrameLerpDataItem, unmanagedMaskPreviewItemPair.first)) { // Unmanaged data item was changed try { _nativeController->UpdateMaskingGeometry(unmanagedMaskPreviewItemPair); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(SetMaskingPreviewItemsErrorMessage, comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(SetMaskingPreviewItemsErrorMessage, stdException); } geometryGroupNeedsUpdate = true; } } // Remove any excess items not keyed to an active Track number if (_nativeController->RemoveInactiveMaskingPreviewItems(activeTrackNumbers) > 0) { geometryGroupNeedsUpdate = true; } if (geometryGroupNeedsUpdate) { try { _nativeController->UpdateMaskingGeometryGroup(); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(SetMaskingPreviewItemsErrorMessage, comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(SetMaskingPreviewItemsErrorMessage, stdException); } } } void ScriptVideoService::SetUnmanagedCroppingPreviewItems(System::Collections::Generic::IEnumerable<SegmentKeyFrameLerpDataItem>^ croppingKeyFrameLerpDataItems) { using namespace Models::Cropping; auto& unmanagedCroppingPreviewItems = _nativeController->get_CroppingPreviewItems(); std::vector<int> activeTrackNumbers; for each (SegmentKeyFrameLerpDataItem keyFrameLerpDataItem in croppingKeyFrameLerpDataItems) { activeTrackNumbers.push_back(keyFrameLerpDataItem.TrackNumber); CropKeyFrameModel^ cropKeyFrameAtOrBefore = dynamic_cast<CropKeyFrameModel^>(keyFrameLerpDataItem.KeyFrameAtOrBefore); Debug::Assert(cropKeyFrameAtOrBefore != nullptr); double cropLeft, cropTop, cropWidth, cropHeight, cropAngle; if (keyFrameLerpDataItem.KeyFrameAfter == nullptr || keyFrameLerpDataItem.LerpAmount == 0.0) { cropLeft = cropKeyFrameAtOrBefore->Left; cropTop = cropKeyFrameAtOrBefore->Top; cropWidth = cropKeyFrameAtOrBefore->Width; cropHeight = cropKeyFrameAtOrBefore->Height; cropAngle = cropKeyFrameAtOrBefore->Angle; } else { CropKeyFrameModel^ cropKeyFrameAfter = dynamic_cast<CropKeyFrameModel^>(keyFrameLerpDataItem.KeyFrameAfter); Debug::Assert(cropKeyFrameAfter != nullptr); cropLeft = MathExtensions::LerpTo(cropKeyFrameAtOrBefore->Left, cropKeyFrameAfter->Left, keyFrameLerpDataItem.LerpAmount); cropTop = MathExtensions::LerpTo(cropKeyFrameAtOrBefore->Top, cropKeyFrameAfter->Top, keyFrameLerpDataItem.LerpAmount); cropWidth = MathExtensions::LerpTo(cropKeyFrameAtOrBefore->Width, cropKeyFrameAfter->Width, keyFrameLerpDataItem.LerpAmount); cropHeight = MathExtensions::LerpTo(cropKeyFrameAtOrBefore->Height, cropKeyFrameAfter->Height, keyFrameLerpDataItem.LerpAmount); cropAngle = MathExtensions::LerpTo(cropKeyFrameAtOrBefore->Angle, cropKeyFrameAfter->Angle, keyFrameLerpDataItem.LerpAmount); } // Get existing or insert new item keyed on Track number VideoScriptEditor::Unmanaged::CropSegmentFrameDataItem& unmanagedCropPreviewItem = unmanagedCroppingPreviewItems[keyFrameLerpDataItem.TrackNumber]; unmanagedCropPreviewItem.Left = cropLeft; unmanagedCropPreviewItem.Top = cropTop; unmanagedCropPreviewItem.Width = cropWidth; unmanagedCropPreviewItem.Height = cropHeight; // Round to correct Angle precision rounding errors (e.g. 90 degrees double angle can end up being a tiny fraction above 90.0) unmanagedCropPreviewItem.Angle = Math::Round(cropAngle, MathExtensions::FloatingPointPrecision); } // Remove any excess items not keyed to an active Track number _nativeController->RemoveInactiveCroppingPreviewItems(activeTrackNumbers); } void ScriptVideoService::CloseScriptCore() { ScriptVideoServiceBase::CloseScriptCore(); _internalContext->ApplyMaskingPreviewToSourceRender = false; _internalContext->SetScriptFileSourceInternal(String::Empty); _nativeController->ResetEnvironmentAndRenderer(); } void ScriptVideoService::RenderUnmanagedSourceFrameSurface() { bool applyMaskingPreview = _internalContext->ApplyMaskingPreviewToSourceRender && _internalContext->HasVideo && _internalContext->Project != nullptr && _internalContext->Project->Masking->Shapes->Count > 0; try { _nativeController->RenderSourceFrameSurface(_internalContext->FrameNumber, applyMaskingPreview); } catch (const _com_error& comError) { throw gcnew PreviewRendererException(GetRenderFrameErrorMessage(_internalContext->FrameNumber), comError); } catch (const std::exception& stdException) { throw gcnew PreviewRendererException(GetRenderFrameErrorMessage(_internalContext->FrameNumber), stdException); } OnSurfaceRendered(SurfaceRenderPipeline::SourceVideo); } bool ScriptVideoService::SetUnmanagedMaskDataItemFromLerpedKeyFrames(SegmentKeyFrameLerpDataItem% managedKeyFrameLerpData, std::shared_ptr<VideoScriptEditor::Unmanaged::MaskSegmentFrameDataItemBase>& unmanagedDataItemPtr) { using namespace Models::Masking::Shapes; Debug::Assert(managedKeyFrameLerpData.KeyFrameAtOrBefore != nullptr); bool unmanagedDataItemWasSet = false; PolygonMaskShapeKeyFrameModel^ fromPolygonMaskShapeFrame = nullptr; RectangleMaskShapeKeyFrameModel^ fromRectangleMaskShapeFrame = nullptr; EllipseMaskShapeKeyFrameModel^ fromEllipseMaskShapeFrame = nullptr; if ((fromPolygonMaskShapeFrame = dynamic_cast<PolygonMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAtOrBefore)) != nullptr) { PolygonMaskShapeKeyFrameModel^ toPolygonMaskShapeFrame = dynamic_cast<PolygonMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAfter); std::vector<VideoScriptEditor::Unmanaged::PointD> unmanagedPolygonPoints; unmanagedPolygonPoints.reserve(fromPolygonMaskShapeFrame->Points->Count); for (int i = 0; i < fromPolygonMaskShapeFrame->Points->Count; i++) { PointD managedPoint = (toPolygonMaskShapeFrame == nullptr || managedKeyFrameLerpData.LerpAmount == 0.0) ? fromPolygonMaskShapeFrame->Points[i] : PointD::Lerp(fromPolygonMaskShapeFrame->Points[i], toPolygonMaskShapeFrame->Points[i], managedKeyFrameLerpData.LerpAmount); unmanagedPolygonPoints.emplace_back(managedPoint.X, managedPoint.Y); } std::shared_ptr<VideoScriptEditor::Unmanaged::MaskPolygonSegmentFrameDataItem> unmanagedPolygonPtr = std::dynamic_pointer_cast<VideoScriptEditor::Unmanaged::MaskPolygonSegmentFrameDataItem>(unmanagedDataItemPtr); if (!unmanagedPolygonPtr) { unmanagedDataItemPtr.reset(new VideoScriptEditor::Unmanaged::MaskPolygonSegmentFrameDataItem(std::move(unmanagedPolygonPoints))); unmanagedDataItemWasSet = true; } else if (unmanagedPolygonPtr->Points != unmanagedPolygonPoints) { unmanagedPolygonPtr->Points = std::move(unmanagedPolygonPoints); unmanagedDataItemWasSet = true; } } else if ((fromRectangleMaskShapeFrame = dynamic_cast<RectangleMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAtOrBefore)) != nullptr) { double rectLeft, rectTop, rectWidth, rectHeight; RectangleMaskShapeKeyFrameModel^ toRectangleMaskShapeFrame = dynamic_cast<RectangleMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAfter); if (toRectangleMaskShapeFrame == nullptr || managedKeyFrameLerpData.LerpAmount == 0.0) { rectLeft = fromRectangleMaskShapeFrame->Left; rectTop = fromRectangleMaskShapeFrame->Top; rectWidth = fromRectangleMaskShapeFrame->Width; rectHeight = fromRectangleMaskShapeFrame->Height; } else { rectLeft = MathExtensions::LerpTo(fromRectangleMaskShapeFrame->Left, toRectangleMaskShapeFrame->Left, managedKeyFrameLerpData.LerpAmount); rectTop = MathExtensions::LerpTo(fromRectangleMaskShapeFrame->Top, toRectangleMaskShapeFrame->Top, managedKeyFrameLerpData.LerpAmount); rectWidth = MathExtensions::LerpTo(fromRectangleMaskShapeFrame->Width, toRectangleMaskShapeFrame->Width, managedKeyFrameLerpData.LerpAmount); rectHeight = MathExtensions::LerpTo(fromRectangleMaskShapeFrame->Height, toRectangleMaskShapeFrame->Height, managedKeyFrameLerpData.LerpAmount); } std::shared_ptr<VideoScriptEditor::Unmanaged::MaskRectangleSegmentFrameDataItem> unmanagedRectanglePtr = std::dynamic_pointer_cast<VideoScriptEditor::Unmanaged::MaskRectangleSegmentFrameDataItem>(unmanagedDataItemPtr); if (!unmanagedRectanglePtr) { unmanagedDataItemPtr.reset(new VideoScriptEditor::Unmanaged::MaskRectangleSegmentFrameDataItem(rectLeft, rectTop, rectWidth, rectHeight)); unmanagedDataItemWasSet = true; } else if (unmanagedRectanglePtr->Left != rectLeft || unmanagedRectanglePtr->Top != rectTop || unmanagedRectanglePtr->Width != rectWidth || unmanagedRectanglePtr->Height != rectHeight) { unmanagedRectanglePtr->Left = rectLeft; unmanagedRectanglePtr->Top = rectTop; unmanagedRectanglePtr->Width = rectWidth; unmanagedRectanglePtr->Height = rectHeight; unmanagedDataItemWasSet = true; } } else if ((fromEllipseMaskShapeFrame = dynamic_cast<EllipseMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAtOrBefore)) != nullptr) { PointD ellipseCenterPoint; double ellipseRadiusX, ellipseRadiusY; EllipseMaskShapeKeyFrameModel^ toEllipseMaskShapeFrame = dynamic_cast<EllipseMaskShapeKeyFrameModel^>(managedKeyFrameLerpData.KeyFrameAfter); if (toEllipseMaskShapeFrame == nullptr || managedKeyFrameLerpData.LerpAmount == 0.0) { ellipseCenterPoint = fromEllipseMaskShapeFrame->CenterPoint; ellipseRadiusX = fromEllipseMaskShapeFrame->RadiusX; ellipseRadiusY = fromEllipseMaskShapeFrame->RadiusY; } else { ellipseCenterPoint = PointD::Lerp(fromEllipseMaskShapeFrame->CenterPoint, toEllipseMaskShapeFrame->CenterPoint, managedKeyFrameLerpData.LerpAmount); ellipseRadiusX = MathExtensions::LerpTo(fromEllipseMaskShapeFrame->RadiusX, toEllipseMaskShapeFrame->RadiusX, managedKeyFrameLerpData.LerpAmount); ellipseRadiusY = MathExtensions::LerpTo(fromEllipseMaskShapeFrame->RadiusY, toEllipseMaskShapeFrame->RadiusY, managedKeyFrameLerpData.LerpAmount); } std::shared_ptr<VideoScriptEditor::Unmanaged::MaskEllipseSegmentFrameDataItem> unmanagedEllipsePtr = std::dynamic_pointer_cast<VideoScriptEditor::Unmanaged::MaskEllipseSegmentFrameDataItem>(unmanagedDataItemPtr); if (!unmanagedEllipsePtr) { unmanagedDataItemPtr.reset(new VideoScriptEditor::Unmanaged::MaskEllipseSegmentFrameDataItem(VideoScriptEditor::Unmanaged::PointD(ellipseCenterPoint.X, ellipseCenterPoint.Y), ellipseRadiusX, ellipseRadiusY)); unmanagedDataItemWasSet = true; } else if (unmanagedEllipsePtr->CenterPoint.X != ellipseCenterPoint.X || unmanagedEllipsePtr->CenterPoint.Y != ellipseCenterPoint.Y || unmanagedEllipsePtr->RadiusX != ellipseRadiusX || unmanagedEllipsePtr->RadiusY != ellipseRadiusY) { unmanagedEllipsePtr->CenterPoint.X = ellipseCenterPoint.X; unmanagedEllipsePtr->CenterPoint.Y = ellipseCenterPoint.Y; unmanagedEllipsePtr->RadiusX = ellipseRadiusX; unmanagedEllipsePtr->RadiusY = ellipseRadiusY; unmanagedDataItemWasSet = true; } } return unmanagedDataItemWasSet; } }
46.082774
230
0.670421
[ "object", "vector" ]
30d49f754cfd5db72a76badcddd6852a324d6d2a
951
cpp
C++
src/plugins/render/nodes/font.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/render/nodes/font.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/render/nodes/font.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include "datatypes/font.h" #include <possumwood_sdk/datatypes/filename.h> #include <possumwood_sdk/node_implementation.h> #include <boost/filesystem.hpp> namespace { dependency_graph::InAttr<possumwood::Filename> a_filename; dependency_graph::OutAttr<possumwood::Font> a_font; dependency_graph::State compute(dependency_graph::Values& data) { const boost::filesystem::path filename = data.get(a_filename).filename(); if(!boost::filesystem::exists(filename) || filename.empty()) throw std::runtime_error("Filename " + filename.string() + " not found."); possumwood::Font font; font.load(filename); data.set(a_font, font); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_filename, "font_def_file"); meta.addAttribute(a_font, "font"); meta.addInfluence(a_filename, a_font); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("render/font", init); } // namespace
23.775
76
0.753943
[ "render" ]
30e3d9d4a730e6004abe800e1320d8d6bf19ab0a
10,870
cpp
C++
test/src/ExtensionTests.cpp
rhymu8354/Smtp
f5464632e04baac7bc3daa17b0507218e329e7a7
[ "MIT" ]
1
2022-02-11T18:28:52.000Z
2022-02-11T18:28:52.000Z
test/src/ExtensionTests.cpp
rhymu8354/Smtp
f5464632e04baac7bc3daa17b0507218e329e7a7
[ "MIT" ]
null
null
null
test/src/ExtensionTests.cpp
rhymu8354/Smtp
f5464632e04baac7bc3daa17b0507218e329e7a7
[ "MIT" ]
1
2022-02-11T18:28:57.000Z
2022-02-11T18:28:57.000Z
/** * @file ExtensionTests.cpp * * This module contains the unit tests of the Smtp::Client class. * * © 2019 by Richard Walters */ #include "Common.hpp" #include <algorithm> #include <future> #include <gtest/gtest.h> #include <memory> #include <MessageHeaders/MessageHeaders.hpp> #include <Smtp/Client.hpp> #include <stdint.h> #include <string> #include <SystemAbstractions/NetworkEndpoint.hpp> #include <TlsDecorator/TlsDecorator.hpp> #include <vector> namespace { struct FooExtension : public Smtp::Client::Extension { // Properties std::string parameters; bool wasReset = false; // Smtp::Client::Extension virtual void Configure(const std::string& parameters) override { this->parameters = parameters; } virtual void Reset() override { wasReset = true; } virtual std::string ModifyMessage( const Smtp::Client::MessageContext& context, const std::string& input ) override { if (input.substr(0, 4) == "MAIL") { return input + " foo=bar"; } else { return input; } } }; struct BarPreMessageExtension : public Smtp::Client::Extension { // Properties bool performedExtraStage = false; std::function< void(const std::string& data) > onSendMessage; std::function< void(bool success) > onStageComplete; // Smtp::Client::Extension virtual std::string ModifyMessage( const Smtp::Client::MessageContext& context, const std::string& input ) override { return input; } virtual bool IsExtraProtocolStageNeededHere( const Smtp::Client::MessageContext& context ) override { if ( performedExtraStage || (context.protocolStage != Smtp::Client::ProtocolStage::ReadyToSend) ) { return false; } performedExtraStage = true; return true; } virtual void GoAhead( std::function< void(const std::string& data) > onSendMessage, std::function< void(bool success) > onStageComplete ) override { this->onSendMessage = onSendMessage; this->onStageComplete = onStageComplete; onSendMessage("PogChamp\r\n"); } virtual bool HandleServerMessage( const Smtp::Client::MessageContext& context, const Smtp::Client::ParsedMessage& message ) override { if (message.code != 250) { return false; } onStageComplete(true); return true; } }; struct BarAfterSenderDeclaredExtension : public Smtp::Client::Extension { // Properties bool softFailureOnServerMessage = false; bool performedExtraStage = false; std::function< void(const std::string& data) > onSendMessage; std::function< void(bool success) > onStageComplete; // Smtp::Client::Extension virtual std::string ModifyMessage( const Smtp::Client::MessageContext& context, const std::string& input ) override { return input; } virtual bool IsExtraProtocolStageNeededHere( const Smtp::Client::MessageContext& context ) override { if ( performedExtraStage || (context.protocolStage != Smtp::Client::ProtocolStage::DeclaringSender) ) { return false; } performedExtraStage = true; return true; } virtual void GoAhead( std::function< void(const std::string& data) > onSendMessage, std::function< void(bool success) > onStageComplete ) override { this->onSendMessage = onSendMessage; this->onStageComplete = onStageComplete; } virtual bool HandleServerMessage( const Smtp::Client::MessageContext& context, const Smtp::Client::ParsedMessage& message ) override { onStageComplete(!softFailureOnServerMessage); return true; } }; } namespace SmtpTests { /** * This is the test fixture for these tests, providing common * setup and teardown for each test. */ struct ExtensionTests : public Common { }; TEST_F(ExtensionTests, ExtensionProtocolStageSuccess) { auto readyOrBroken = client.GetReadyOrBrokenFuture(); const auto extension = std::make_shared< BarPreMessageExtension >(); client.RegisterExtension("BAR", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend(false)); EXPECT_FALSE(FutureReady(readyOrBroken, std::chrono::milliseconds(100))); auto& connection = *clients[0].connection; auto messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "PogChamp\r\n", }), messages ); SendTextMessage(connection, "250 OK\r\n"); EXPECT_TRUE(FutureReady(readyOrBroken, std::chrono::milliseconds(1000))); EXPECT_TRUE(readyOrBroken.get()); readyOrBroken = client.GetReadyOrBrokenFuture(); MessageHeaders::MessageHeaders headers; headers.AddHeader("From", "<alex@example.com>"); const std::string body = ( "Hello, World!" ); auto sendWasCompleted = client.SendMail(headers, body); messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "MAIL FROM:<alex@example.com>\r\n", }), messages ); EXPECT_FALSE(FutureReady(readyOrBroken)); } TEST_F(ExtensionTests, ExtensionProtocolStageHardFailure) { auto readyOrBroken = client.GetReadyOrBrokenFuture(); const auto extension = std::make_shared< BarPreMessageExtension >(); client.RegisterExtension("BAR", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend(false)); EXPECT_FALSE(FutureReady(readyOrBroken, std::chrono::milliseconds(100))); auto& connection = *clients[0].connection; auto messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "PogChamp\r\n", }), messages ); SendTextMessage(connection, "535 Go away\r\n"); EXPECT_TRUE(FutureReady(readyOrBroken, std::chrono::milliseconds(1000))); EXPECT_FALSE(readyOrBroken.get()); } TEST_F(ExtensionTests, ExtensionSoftFailureOnServerMessage) { const auto extension = std::make_shared< BarAfterSenderDeclaredExtension >(); extension->softFailureOnServerMessage = true; client.RegisterExtension("BAR", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend()); auto& connection = *clients[0].connection; MessageHeaders::MessageHeaders headers; headers.AddHeader("From", "<alex@example.com>"); headers.AddHeader("To", "<bob@example.com>"); const std::string body = ( "Hello, World!" ); auto sendWasCompleted = client.SendMail(headers, body); auto readyOrBroken = client.GetReadyOrBrokenFuture(); auto messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "MAIL FROM:<alex@example.com>\r\n", }), messages ); EXPECT_FALSE(FutureReady(readyOrBroken, std::chrono::milliseconds(100))); EXPECT_FALSE(FutureReady(sendWasCompleted, std::chrono::milliseconds(100))); SendTextMessage(connection, "250 OK\r\n"); EXPECT_TRUE(FutureReady(readyOrBroken, std::chrono::milliseconds(1000))); EXPECT_TRUE(readyOrBroken.get()); EXPECT_TRUE(FutureReady(sendWasCompleted, std::chrono::milliseconds(1000))); EXPECT_FALSE(sendWasCompleted.get()); } TEST_F(ExtensionTests, SupportedExtensionGetsToModifyMessagesInAnyStage) { auto readyOrBroken = client.GetReadyOrBrokenFuture(); const auto extension = std::make_shared< FooExtension >(); client.RegisterExtension("FOO", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend()); auto& connection = *clients[0].connection; MessageHeaders::MessageHeaders headers; headers.AddHeader("From", "<alex@example.com>"); headers.AddHeader("To", "<bob@example.com>"); const std::string body = ( "Hello, World!" ); auto sendWasCompleted = client.SendMail(headers, body); auto messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "MAIL FROM:<alex@example.com> foo=bar\r\n", }), messages ); SendTextMessage(connection, "250 OK\r\n"); messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "RCPT TO:<bob@example.com>\r\n", }), messages ); EXPECT_TRUE(FutureReady(readyOrBroken)); EXPECT_TRUE(readyOrBroken.get()); } TEST_F(ExtensionTests, UnsupportedExtensionDoesNotGetToModifyMessagesInAnyStage) { auto readyOrBroken = client.GetReadyOrBrokenFuture(); const auto extension = std::make_shared< FooExtension >(); client.RegisterExtension("SPAM", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend()); MessageHeaders::MessageHeaders headers; headers.AddHeader("From", "<alex@example.com>"); const std::string body = ( "Hello, World!" ); auto sendWasCompleted = client.SendMail(headers, body); const auto messages = AwaitMessages(0, 1); EXPECT_EQ( std::vector< std::string >({ "MAIL FROM:<alex@example.com>\r\n", }), messages ); EXPECT_TRUE(FutureReady(readyOrBroken)); EXPECT_TRUE(readyOrBroken.get()); } TEST_F(ExtensionTests, SupportedExtensionGivenParameters) { const auto extension = std::make_shared< FooExtension >(); client.RegisterExtension("FOO", extension); ASSERT_TRUE(EstablishConnectionPrepareToSend()); EXPECT_EQ("Poggers", extension->parameters); } TEST_F(ExtensionTests, ExtensionResetAtStart) { const auto extension = std::make_shared< FooExtension >(); client.RegisterExtension("FOO", extension); StartServer(false); ASSERT_TRUE(EstablishConnection(false)); EXPECT_TRUE(extension->wasReset); } }
33.757764
90
0.597516
[ "vector" ]
30f4a07dd14473e6030d667205e5be25780e2d4d
1,408
cpp
C++
Classes/src/modeldata/Reference.cpp
MichaelMahn/c3t2c3b
17f36d4c06e309a717224a9273743de5854d5d07
[ "MIT" ]
2
2016-10-04T06:45:06.000Z
2021-04-06T16:43:40.000Z
Classes/src/modeldata/Reference.cpp
MichaelMahn/c3t2c3b
17f36d4c06e309a717224a9273743de5854d5d07
[ "MIT" ]
null
null
null
Classes/src/modeldata/Reference.cpp
MichaelMahn/c3t2c3b
17f36d4c06e309a717224a9273743de5854d5d07
[ "MIT" ]
null
null
null
#include "Reference.h" #include "FileIO.h" //#include <stdio.h> namespace fbxconv { Reference::Reference(): _ref(nullptr), _xref(""), _type(0), _offset(0), _fPosition(0.f) { } Reference::Reference(std::string xref, ObjRef* ref): _ref(ref), _xref(xref), _type(ref->tpyeid), _offset(0), _fPosition(0.f) { } void Reference::writeBinary(FILE* file) { saveFilePosition(file); write(_xref, file); write(_type,file); write(_offset, file); } bool Reference::updateOffset(FILE* file) { long newOffset = _ref->fPosition; return updateOffset(file,newOffset); } bool Reference::updateOffset(FILE* file, long newOffset) { if(getFilePosition() > 0) { // save the current offset long saveOffset = ftell(file); // update the offset data for us _offset = newOffset; // seek this Reference object in the file. fseek(file, getFilePosition(), SEEK_SET); //Skip over the id string skipString(file); // Skip TypeID unsigned int skipUint(file); // write over the old offset. write(_offset, file); // restore the offset. fseek(file, saveOffset, SEEK_SET); return true; } return false; } ObjRef* Reference::getRef() { return _ref; } unsigned int Reference::getFilePosition() { return (unsigned int)_fPosition; } void Reference::saveFilePosition(FILE* file) { _fPosition = ftell(file); } }
16.564706
57
0.65554
[ "object" ]
30f9128898ed0bfcf22fe974db925bd1db297ec4
10,303
cpp
C++
calibration/spherecalib/spherecalib.cpp
dgrover/flyCAVE
30cdef7ed3535a93f303387c1c78dc9224d413c8
[ "MIT" ]
1
2016-01-08T07:33:24.000Z
2016-01-08T07:33:24.000Z
calibration/spherecalib/spherecalib.cpp
dgrover/flyCAVE
30cdef7ed3535a93f303387c1c78dc9224d413c8
[ "MIT" ]
null
null
null
calibration/spherecalib/spherecalib.cpp
dgrover/flyCAVE
30cdef7ed3535a93f303387c1c78dc9224d413c8
[ "MIT" ]
null
null
null
#include "stdafx.h" int xOffset = 1920; int yOffset = 0; double viewWidth = 912/3; double viewHeight = 1140*2; double radius = 1.0; double defaultDistance = (radius + 8.0); double centerDistance = defaultDistance; double sideDistance = defaultDistance; double defaultCull = 0.0; double centerCull = defaultCull; double sideCull = defaultCull; double loadedCenterDistance = defaultDistance; double loadedCenterCull = defaultCull; double loadedSideDistance = defaultDistance; double loadedSideCull = defaultCull; double camHorLoc = 0; double camVertLoc = radius*-1.0; double transInc = 0.1; double depth = 0; int loadedSideVPOffset = 0; int loadedCenterVPOffset = 0; int sideVPOffset = 0; int centerVPOffset = 0; osg::Vec4 backgroundColor = osg::Vec4(0, 0, 0, 1); osg::Vec3d up = osg::Vec3d(0, 0, 1); //up vector const char* imageFileName = "images//numberline.gif"; const char* displayFile = "displaySettings_flycave2.txt"; osgViewer::Viewer viewer; void printInfo(); osg::ref_ptr<osg::Geode> createShapes(); void setStartingViews(); void setup(); void run(); class keyboardHandler : public osgGA::GUIEventHandler { public: virtual bool handle(const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&); }; bool keyboardHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { switch (ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN) : { switch (ea.getKey()) { case 'w': centerDistance = centerDistance - transInc; break; case 'W': sideDistance = sideDistance - transInc; break; case 's': centerDistance = centerDistance + transInc; break; case 'S': sideDistance = sideDistance + transInc; break; case 'a': centerCull = centerCull - transInc; break; case'A': sideCull = sideCull - transInc; break; case 'd': centerCull = centerCull + transInc; break; case'D': sideCull = sideCull + transInc; break; case ' ': centerDistance = loadedCenterDistance; centerCull = loadedCenterCull; sideDistance= loadedSideDistance; sideCull = loadedSideCull; sideVPOffset = loadedSideVPOffset; centerVPOffset = loadedCenterVPOffset; break; case '.': centerDistance = defaultDistance; centerCull = defaultCull; sideDistance = defaultDistance; sideCull = defaultCull; sideVPOffset = 0; centerVPOffset = 0; break; case '+': transInc = transInc*2.0; break; case '-': transInc = transInc / 2.0; break; case 'p': printInfo(); break; case 'q': centerVPOffset++; break; case 'e': centerVPOffset--; break; case 'Q': sideVPOffset++; break; case 'E': sideVPOffset--; break; default: return false; break; } return true; } default: return false; break; } } osg::ref_ptr<osg::Geode> createShapes() { osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet(); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); osg::ref_ptr<osg::Image> image = new osg::Image(); image = osgDB::readImageFile(imageFileName); if (image) { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D(image); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); osg::ref_ptr<osg::TexMat> texmat = new osg::TexMat; stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON); texture->setUnRefImageDataAfterApply(true); } geode->setStateSet(stateset); geode->setCullingActive(true); osg::ref_ptr<osg::CullFace> cull = new osg::CullFace(osg::CullFace::Mode::BACK); stateset->setAttributeAndModes(cull, osg::StateAttribute::ON); osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints; hints->setDetailRatio(2.0f); hints->setCreateBody(false); hints->setCreateBackFace(true); hints->setCreateFrontFace(true); hints->setCreateNormals(false); hints->setCreateTop(false); hints->setCreateBottom(false); osg::ref_ptr<osg::Sphere> sph = new osg::Sphere(osg::Vec3d(0.0, 0.0, 0.0), radius); osg::ref_ptr<osg::ShapeDrawable> sphere = new osg::ShapeDrawable(sph, hints); sphere->setUseDisplayList(false); geode->addDrawable(sphere); return geode; } void printInfo() { printf("**********\n"); printf("Center Distance: %f\n", centerDistance); printf("Center Cull Amount: %f\n", centerCull); printf("Center Viewport Offset: %i\n", centerVPOffset); printf("Side Distance: %f\n", sideDistance); printf("Side Cull Amount: %f\n", sideCull); printf("Side Viewport Offset: %i\n", sideVPOffset); printf("**********\n\n"); } void writeInfo() { FILE * file = fopen(displayFile, "w"); fprintf(file, "%f\n", centerDistance); fprintf(file, "%f\n", centerCull); fprintf(file, "%i\n", centerVPOffset); fprintf(file, "%f\n", sideDistance); fprintf(file, "%f\n", sideCull); fprintf(file, "%i\n", sideVPOffset); fclose(file); } void setStartingViews() { std::ifstream file(displayFile, std::ios::in); if (file.is_open()) { file >> loadedCenterDistance; file >> loadedCenterCull; file >> loadedCenterVPOffset; file >> loadedSideDistance; file >> loadedSideCull; file >> loadedSideVPOffset; centerDistance = loadedCenterDistance; centerCull = loadedCenterCull; centerVPOffset = loadedCenterVPOffset; sideDistance = loadedSideDistance; sideCull = loadedSideCull; sideVPOffset = loadedSideVPOffset; file.close(); } else { centerDistance = defaultDistance; centerCull = defaultCull; centerVPOffset = 0; sideDistance = defaultDistance; sideCull = defaultCull; sideVPOffset = 0; } } void setup() { osg::ref_ptr<osg::Group> root = new osg::Group; root->addChild(createShapes()); viewer.addEventHandler(new keyboardHandler()); viewer.setSceneData(root); setStartingViews(); osg::ref_ptr<osg::GraphicsContext::Traits> masterTraits = new osg::GraphicsContext::Traits; GLenum buffer = masterTraits->doubleBuffer ? GL_BACK : GL_FRONT; viewer.getCamera()->setDrawBuffer(buffer); viewer.getCamera()->setReadBuffer(buffer); viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); viewer.getCamera()->setCullingMode(osg::CullSettings::ENABLE_ALL_CULLING); viewer.getCamera()->setClearColor(osg::Vec4(0, 0, 0, 1)); // black background viewer.getCamera()->setProjectionMatrix(osg::Matrixd::identity()); viewer.setCameraManipulator(NULL); osg::ref_ptr<osg::Camera> centerCam = new osg::Camera; osg::ref_ptr<osg::GraphicsContext::Traits> centerTraits = new osg::GraphicsContext::Traits; centerTraits->x = xOffset + viewWidth; centerTraits->y = yOffset; centerTraits->width = viewWidth; centerTraits->height = viewHeight; centerTraits->windowDecoration = false; centerTraits->doubleBuffer = true; centerTraits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> centerGC = osg::GraphicsContext::createGraphicsContext(centerTraits.get()); centerCam->setGraphicsContext(centerGC.get()); osg::ref_ptr<osg::Viewport> centerVP = new osg::Viewport(0, 0, centerTraits->width, centerTraits->height); centerCam->setViewport(centerVP); viewer.addSlave(centerCam); osg::ref_ptr<osg::Camera> leftCam = new osg::Camera; osg::ref_ptr<osg::GraphicsContext::Traits> leftTraits = new osg::GraphicsContext::Traits; leftTraits->x = xOffset; leftTraits->y = yOffset; leftTraits->width = viewWidth; leftTraits->height = viewHeight; leftTraits->windowDecoration = false; leftTraits->doubleBuffer = true; leftTraits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> leftGC = osg::GraphicsContext::createGraphicsContext(leftTraits.get()); leftCam->setGraphicsContext(leftGC.get()); osg::ref_ptr<osg::Viewport> leftVP = new osg::Viewport(0, 0, leftTraits->width, leftTraits->height); leftCam->setViewport(leftVP); viewer.addSlave(leftCam); osg::ref_ptr<osg::Camera> rightCam = new osg::Camera; osg::ref_ptr<osg::GraphicsContext::Traits> rightTraits = new osg::GraphicsContext::Traits; rightTraits->x = xOffset + viewWidth * 2; rightTraits->y = yOffset; rightTraits->width = viewWidth; rightTraits->height = viewHeight; rightTraits->windowDecoration = false; rightTraits->doubleBuffer = true; rightTraits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> rightGC = osg::GraphicsContext::createGraphicsContext(rightTraits.get()); rightCam->setGraphicsContext(rightGC.get()); osg::ref_ptr<osg::Viewport> rightVP = new osg::Viewport(0, 0, rightTraits->width, rightTraits->height); rightCam->setViewport(rightVP); viewer.addSlave(rightCam); } void run() { osg::Matrix reflection = osg::Matrixd::scale(-1, 1, 1); osg::Matrix leftRotation = osg::Matrixd::rotate(osg::DegreesToRadians(90.0), osg::Vec3(0, 0, 1)); osg::Matrix rightRotation = osg::Matrixd::rotate(osg::DegreesToRadians(-90.0), osg::Vec3(0, 0, 1)); osg::Matrix leftCombined = leftRotation*reflection; osg::Matrix rightCombined = rightRotation*reflection; while (!viewer.done()) { viewer.getSlave(0)._camera->setViewport(centerVPOffset, 0, viewWidth, viewHeight); viewer.getSlave(0)._viewOffset = osg::Matrixd::lookAt(osg::Vec3d(camHorLoc, centerDistance, camVertLoc), osg::Vec3d(camHorLoc, depth, camVertLoc), osg::Vec3d(0, 0, 1)); viewer.getSlave(0)._projectionOffset = osg::Matrixd::perspective(40.0, 1280.0/4800.0, centerDistance - radius, centerDistance - centerCull); viewer.getSlave(1)._camera->setViewport(-sideVPOffset, 0, viewWidth, viewHeight); viewer.getSlave(1)._viewOffset = leftCombined*osg::Matrixd::lookAt(osg::Vec3d(camHorLoc, sideDistance, camVertLoc), osg::Vec3d(camHorLoc, depth, camVertLoc), osg::Vec3d(0, 0, 1)); viewer.getSlave(1)._projectionOffset = osg::Matrixd::perspective(40.0, 1280.0 / 4800.0, sideDistance - radius, sideDistance - sideCull); viewer.getSlave(2)._camera->setViewport(sideVPOffset, 0, viewWidth, viewHeight); viewer.getSlave(2)._viewOffset = rightCombined*osg::Matrixd::lookAt(osg::Vec3d(camHorLoc, sideDistance, camVertLoc), osg::Vec3d(camHorLoc, depth, camVertLoc), osg::Vec3d(0, 0, 1)); viewer.getSlave(2)._projectionOffset = osg::Matrixd::perspective(40.0, 1280.0 / 4800.0, sideDistance - radius, sideDistance - sideCull); viewer.frame(); } printInfo(); writeInfo(); } int _tmain(int argc, _TCHAR* argv[]) { setup(); run(); return 0; }
29.10452
182
0.722605
[ "vector" ]
30fda7de4dde27375e53b366ad20ab6028f25ac9
5,901
cpp
C++
Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/GeomUtils/src/pcm/GuPCMContactSphereBox.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/GeomUtils/src/pcm/GuPCMContactSphereBox.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/GeomUtils/src/pcm/GuPCMContactSphereBox.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. //#include "GuGJKWrapper.h" #include "GuVecBox.h" #include "GuVecSphere.h" #include "GuGeometryUnion.h" #include "GuContactMethodImpl.h" #include "GuContactBuffer.h" namespace physx { namespace Gu { bool pcmContactSphereBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); using namespace Ps::aos; // Get actual shape data const PxSphereGeometry& shapeSphere = shape0.get<const PxSphereGeometry>(); const PxBoxGeometry& shapeBox = shape1.get<const PxBoxGeometry>(); // //const PsTransformV transf0(transform0); const Vec3V sphereOrigin = V3LoadA(&transform0.p.x); //const PsTransformV transf1(transform1); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV radius = FLoad(shapeSphere.radius); const PsTransformV transf1(p1, q1); const FloatV cDist = FLoad(params.mContactDistance); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); //translate sphere center into the box space const Vec3V sphereCenter = transf1.transformInv(sphereOrigin); const Vec3V nBoxExtents = V3Neg(boxExtents); //const FloatV radSq = FMul(radius, radius); const FloatV inflatedSum = FAdd(radius, cDist); const FloatV sqInflatedSum = FMul(inflatedSum, inflatedSum); const Vec3V p = V3Clamp(sphereCenter, nBoxExtents, boxExtents); const Vec3V v = V3Sub(sphereCenter, p); const FloatV lengthSq = V3Dot(v, v); PX_ASSERT(contactBuffer.count < ContactBuffer::MAX_CONTACTS); if(FAllGrtr(sqInflatedSum, lengthSq))//intersect { //check whether the spherCenter is inside the box const BoolV bInsideBox = V3IsGrtrOrEq(boxExtents, V3Abs(sphereCenter)); // PT: TODO: ??? revisit this, why do we have both BAllEqTTTT and BAllTrue3? if(BAllEqTTTT(BAllTrue3(bInsideBox)))//sphere center inside the box { //Pick directions and sign const Vec3V absP = V3Abs(p); const Vec3V distToSurface = V3Sub(boxExtents, absP);//dist from embedded center to box surface along 3 dimensions. const FloatV x = V3GetX(distToSurface); const FloatV y = V3GetY(distToSurface); const FloatV z = V3GetZ(distToSurface); const Vec3V xV = V3Splat(x); const Vec3V zV = V3Splat(z); //find smallest element of distToSurface const BoolV con0 = BAllTrue3(V3IsGrtrOrEq(distToSurface, zV)); const BoolV con1 = BAllTrue3(V3IsGrtrOrEq(distToSurface, xV)); const Vec3V sign = V3Sign(p); const Vec3V tmpX = V3Mul(V3UnitX(), sign); const Vec3V tmpY = V3Mul(V3UnitY(), sign); const Vec3V tmpZ = V3Mul(V3UnitZ(), sign); const Vec3V locNorm= V3Sel(con0, tmpZ, V3Sel(con1, tmpX, tmpY));////local coords contact normal const FloatV dist = FNeg(FSel(con0, z, FSel(con1, x, y))); //separation so far is just the embedding of the center point; we still have to push out all of the radius. const Vec3V point = sphereOrigin; const Vec3V normal = transf1.rotate(locNorm); const FloatV penetration = FSub(dist, radius); Gu::ContactPoint& contact = contactBuffer.contacts[contactBuffer.count++]; V4StoreA(Vec4V_From_Vec3V(normal), &contact.normal.x); V4StoreA(Vec4V_From_Vec3V(point), &contact.point.x); FStore(penetration, &contact.separation); contact.internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX; //context.mContactBuffer.contact(point, normal, penetration); } else { //get the closest point from the center to the box surface const FloatV recipLength = FRsqrt(lengthSq); const FloatV length = FRecip(recipLength); const Vec3V locNorm = V3Scale(v, recipLength); const FloatV penetration = FSub(length, radius); const Vec3V normal = transf1.rotate(locNorm); const Vec3V point = transf1.transform(p); PX_ASSERT(contactBuffer.count < ContactBuffer::MAX_CONTACTS); Gu::ContactPoint& contact = contactBuffer.contacts[contactBuffer.count++]; V4StoreA(Vec4V_From_Vec3V(normal), &contact.normal.x); V4StoreA(Vec4V_From_Vec3V(point), &contact.point.x); FStore(penetration, &contact.separation); contact.internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX; //context.mContactBuffer.contact(point, normal, penetration); } return true; } return false; } }//Gu }//physx
37.348101
117
0.754109
[ "shape", "transform" ]
a5018d29a2ac19a120150af1df2cbc493e6426c7
5,865
hpp
C++
tutorials/RNN/TextDataset.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
tutorials/RNN/TextDataset.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
tutorials/RNN/TextDataset.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <algorithm> #include <cstring> #include <string.h> #include "../../WICWIU_src/Tensor.hpp" //#include "../../WICWIU_src/DataLoader.hpp" // 왜 추가한거지? Dataset때문에 추가한거 같음... 추측임 using namespace std; enum OPTION { ONEHOT, //CBOW }; void MakeOneHotVector(int* onehotvector, int vocab_size, int index){ for(int i=0; i<vocab_size; i++){ if(i==index) onehotvector[i] = 1; else onehotvector[i] = 0; } } //: public Dataset<DTYPE>{ template<typename DTYPE> class TextDataset { private: char* vocab ; char* TextData; int vocab_size; int text_length; Tensor<DTYPE>* input; Tensor<DTYPE>* label; OPTION option; int VOCAB_LENGTH; public: TextDataset(string File_Path, int vocab_length, OPTION pOption) { vocab = NULL; TextData = NULL; vocab_size = 0; text_length = 0; input = NULL; label = NULL; option = pOption; VOCAB_LENGTH = vocab_length; Alloc(File_Path); } virtual ~TextDataset() { Delete(); } //왜 굳이 virtual인거지? void Alloc(string File_Path); void Delete(); void FileReader(string pFile_Path); void MakeVocab(); void MakeInputData(); void MakeLabelData(); int char2index(char c); char index2char(int index); Tensor<DTYPE>* GetInputData(); Tensor<DTYPE>* GetLabelData(); int GetTextLength(); int GetVocabLength(); //virtual std::vector<Tensor<DTYPE> *>* GetData(int idx); //virtual int GetLength(); }; template<typename DTYPE> void TextDataset<DTYPE>::Alloc(string File_Path) { vocab = new char[VOCAB_LENGTH]; //File_Reader FileReader(File_Path); //make_vocab MakeVocab(); //make_Input_data MakeInputData(); //make_label_data MakeLabelData(); } template<typename DTYPE> void TextDataset<DTYPE>::Delete() { delete []vocab; delete []TextData; } template<typename DTYPE> void TextDataset<DTYPE>::FileReader(string pFile_Path) { ifstream fin; fin.open(pFile_Path); if(fin.is_open()){ //파일 사이즈 구하기 fin.seekg(0, ios::end); text_length = fin.tellg(); fin.seekg(0, ios::beg); //포인터를 다시 시작위치로 바꿈 //파일 길이만큼 할당 TextData = new char[text_length]; //파일 읽기 fin.read(TextData, text_length); //여기에 NULL 추가 // std::cout<<TextData<<'\n'; //소문자로 변환 for(int i=0; i<text_length; i++) TextData[i] = tolower(TextData[i]); // std::cout<<TextData<<'\n'; } fin.close(); } template<typename DTYPE> void TextDataset<DTYPE>::MakeVocab(){ int flag = 0; for(int i=0; i<text_length; i++){ flag = 0; vocab_size = (int)strlen(vocab); for(int j=0; j<vocab_size; j++){ if(vocab[j]==TextData[i]) flag = 1; } if(flag==0){ vocab[vocab_size] = TextData[i]; } } vocab_size = (int)strlen(vocab)+1; //for(int i=0; i<vocab_size; i++) // std::cout<<i<<"번째 vocab :"<<int(vocab[i])<<'\n'; sort(vocab, vocab+vocab_size-1); } template<typename DTYPE> void TextDataset<DTYPE>::MakeInputData(){ if(option == ONEHOT){ int* onehotvector = new int[vocab_size]; input = new Tensor<DTYPE>(text_length, 1, 1, 1, vocab_size); for(int i=0; i<text_length; i++){ MakeOneHotVector(onehotvector, vocab_size, char2index(TextData[i])); for(int j=0; j<vocab_size; j++){ (*input)[Index5D(input->GetShape(), i, 0, 0, 0, j)] = onehotvector[j]; } } } } template<typename DTYPE> void TextDataset<DTYPE>::MakeLabelData(){ if(option == ONEHOT){ int* onehotvector = new int[vocab_size]; label = new Tensor<float>(text_length, 1, 1, 1, vocab_size); for(int i=0; i<text_length; i++){ //마지막 data if(i==text_length-1){ MakeOneHotVector(onehotvector, vocab_size, vocab_size-1); for(int j=0; j<vocab_size; j++){ (*label)[Index5D(label->GetShape(), i, 0, 0, 0, j)] = onehotvector[j]; } continue; } MakeOneHotVector(onehotvector, vocab_size, char2index(TextData[i+1])); for(int j=0; j<vocab_size; j++){ (*label)[Index5D(label->GetShape(), i, 0, 0, 0, j)] = onehotvector[j]; } } } } template<typename DTYPE> int TextDataset<DTYPE>::char2index(char c){ for(int index=0; index<vocab_size; index++){ if(vocab[index]==c) return index; } return -1; } template<typename DTYPE> char TextDataset<DTYPE>::index2char(int index){ return vocab[index]; } template<typename DTYPE> Tensor<DTYPE>* TextDataset<DTYPE>::GetInputData(){ return input; } template<typename DTYPE> Tensor<DTYPE>* TextDataset<DTYPE>::GetLabelData(){ return label; } template<typename DTYPE> int TextDataset<DTYPE>::GetTextLength(){ return text_length; } template<typename DTYPE> int TextDataset<DTYPE>::GetVocabLength(){ return vocab_size; }
23.649194
92
0.518159
[ "vector" ]
a505d6808635d13e6b1450bd26d12f3213fbcd09
273
hpp
C++
NWNXLib/API/Mac/API/Matrix.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Mac/API/Matrix.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/Matrix.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <cstdint> #include "Quaternion.hpp" #include "Vector.hpp" namespace NWNXLib { namespace API { struct Matrix { Vector x; Vector y; Vector z; Quaternion getquaternion(); }; Quaternion Matrix__getquaternion(Matrix* thisPtr); } }
10.5
50
0.688645
[ "vector" ]
a508317b86033c09758e9ad17f1541e47c4bfd25
1,971
cpp
C++
sdk/messages/tests/tensor.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
sdk/messages/tests/tensor.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
sdk/messages/tests/tensor.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "messages/tensor.hpp" #include <vector> #include "capnp/message.h" #include "gtest/gtest.h" namespace isaac { TEST(Tensor, Tensor3iToFromProto) { Tensor3i tensor(23, 49, 18); ::capnp::MallocMessageBuilder message; std::vector<SharedBuffer> buffers; ToProto(std::move(tensor), message.initRoot<TensorProto>(), buffers); ::capnp::SegmentArrayMessageReader reader(message.getSegmentsForOutput()); TensorConstView3i view; EXPECT_TRUE(FromProto(reader.getRoot<TensorProto>(), buffers, view)); EXPECT_EQ(view.dimensions(), tensor.dimensions()); } TEST(Tensor, UniversalTensorToFromProto) { Tensor3i tensor(23, 49, 18); ::capnp::MallocMessageBuilder message; std::vector<SharedBuffer> buffers; ToProto(std::move(tensor), message.initRoot<TensorProto>(), buffers); ::capnp::SegmentArrayMessageReader reader(message.getSegmentsForOutput()); CpuUniversalTensorConstView dynamic_view; EXPECT_TRUE(FromProto(reader.getRoot<TensorProto>(), buffers, dynamic_view)); EXPECT_EQ(dynamic_view.dimensions(), tensor.dimensions()); EXPECT_EQ(dynamic_view.element_type(), ElementType::kInt32); } TEST(Tensor, Tensor3iToFromProtoFailure) { Tensor3i tensor(23, 49, 18); ::capnp::MallocMessageBuilder message; std::vector<SharedBuffer> buffers; ToProto(std::move(tensor), message.initRoot<TensorProto>(), buffers); ::capnp::SegmentArrayMessageReader reader(message.getSegmentsForOutput()); TensorConstView3f view; EXPECT_FALSE(FromProto(reader.getRoot<TensorProto>(), buffers, view)); } } // namespace isaac
33.40678
79
0.775748
[ "vector" ]
a512ff650a76f8e9cc7d5998c09987a8e63ac487
24,243
cpp
C++
test/unit/ut_all_or_none.cpp
Macfly/liquibook
d03b8eec2dbeddf2348175ddb7c18367315ca446
[ "BSD-3-Clause" ]
8
2015-04-22T11:01:59.000Z
2021-03-30T08:34:22.000Z
test/unit/ut_all_or_none.cpp
Macfly/liquibook
d03b8eec2dbeddf2348175ddb7c18367315ca446
[ "BSD-3-Clause" ]
null
null
null
test/unit/ut_all_or_none.cpp
Macfly/liquibook
d03b8eec2dbeddf2348175ddb7c18367315ca446
[ "BSD-3-Clause" ]
4
2017-01-20T02:59:04.000Z
2020-07-04T08:52:24.000Z
// Copyright (c) 2012, 2013 Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE liquibook_AllOrNone #include <boost/test/unit_test.hpp> #include "ut_utils.h" namespace liquibook { using impl::SimpleOrder; typedef FillCheck<SimpleOrder*> SimpleFillCheck; OrderConditions AON(oc_all_or_none); BOOST_AUTO_TEST_CASE(TestRegBidMatchAon) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1252, 100); SimpleOrder ask1(false, 1251, 100); // AON SimpleOrder ask0(false, 1251, 200); // AON, but skipped SimpleOrder bid1(true, 1251, 100); SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 2, 300)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 100, 125100); SimpleFillCheck fc2(&ask1, 100, 125100); BOOST_REQUIRE(add_and_verify(order_book, &bid1, true, true)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 200)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestRegBidMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1251, 700); SimpleOrder ask1(false, 1251, 100); // AON SimpleOrder ask0(false, 1251, 100); // AON SimpleOrder bid1(true, 1251, 400); SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 3, 900)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid1, 400, 1251 * 400); SimpleFillCheck fc1(&ask0, 100, 1251 * 100); SimpleFillCheck fc2(&ask1, 100, 1251 * 100); SimpleFillCheck fc3(&ask2, 200, 1251 * 200); BOOST_REQUIRE(add_and_verify(order_book, &bid1, true, true)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 500)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonBidNoMatch) { SimpleOrderBook order_book; SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 100); SimpleOrder bid1(true, 1251, 300); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 0, 0); SimpleFillCheck fc2(&ask0, 0, 0); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1251, 1, 300)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonBidMatchReg) { SimpleOrderBook order_book; SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 400); SimpleOrder bid1(true, 1251, 300); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 300, 1251 * 300); SimpleFillCheck fc2(&ask0, 300, 1251 * 300); BOOST_REQUIRE(add_and_verify(order_book, &bid1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonBidMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask3(false, 1252, 100); SimpleOrder ask2(false, 1252, 100); SimpleOrder ask1(false, 1251, 400); // AON no match SimpleOrder ask0(false, 1251, 400); SimpleOrder bid1(true, 0, 600); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask3, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(4, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 2, 800)); BOOST_REQUIRE(dc.verify_ask(1252, 2, 200)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 600, 750800); SimpleFillCheck fc2(&ask0, 400, 1251 * 400); SimpleFillCheck fc3(&ask2, 100, 1252 * 100); SimpleFillCheck fc4(&ask3, 100, 1252 * 100); BOOST_REQUIRE(add_and_verify(order_book, &bid1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 400)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonBidNoMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1252, 400); // AON no match SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 400); SimpleOrder bid1(true, 0, 600); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false, false, AON)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 2, 500)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 0, 0); SimpleFillCheck fc2(&ask0, 0, 0); SimpleFillCheck fc3(&ask1, 0, 0); SimpleFillCheck fc4(&ask2, 0, 0); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 2, 500)); } BOOST_AUTO_TEST_CASE(TestAonBidMatchAon) { SimpleOrderBook order_book; SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 300); // AON SimpleOrder bid1(true, 1251, 300); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 300)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 300, 1251 * 300); SimpleFillCheck fc2(&ask0, 300, 1251 * 300); BOOST_REQUIRE(add_and_verify(order_book, &bid1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestRegAskMatchAon) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1251, 100); SimpleOrder bid1(true, 1251, 200); // AON, but skipped SimpleOrder bid2(true, 1251, 100); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &bid2, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 2, 300)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid2, 100, 125100); SimpleFillCheck fc2(&ask1, 100, 125100); BOOST_REQUIRE(add_and_verify(order_book, &ask1, true, true)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1251, 1, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestRegAskMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1250, 400); SimpleOrder bid1(true, 1251, 100); // AON SimpleOrder bid2(true, 1251, 100); // AON SimpleOrder bid0(true, 1250, 700); // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &bid2, false, false, AON)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 2, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid1, 100, 1251 * 100); SimpleFillCheck fc1(&bid2, 100, 1251 * 100); SimpleFillCheck fc2(&bid0, 200, 1250 * 200); SimpleFillCheck fc3(&ask1, 400, 500200); BOOST_REQUIRE(add_and_verify(order_book, &ask1, true, true)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 500)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonAskNoMatch) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1251, 400); // AON SimpleOrder bid1(true, 1251, 100); SimpleOrder bid2(true, 1251, 100); SimpleOrder bid0(true, 1250, 700); // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 2, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid1, 0, 0); SimpleFillCheck fc1(&bid2, 0, 0); SimpleFillCheck fc2(&bid0, 0, 0); SimpleFillCheck fc3(&ask1, 0, 0); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false, false, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1251, 2, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonAskMatchReg) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1251, 100); // AON SimpleOrder bid1(true, 1251, 100); SimpleOrder bid0(true, 1250, 700); // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 1, 100)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid1, 100, 125100); SimpleFillCheck fc3(&ask1, 100, 125100); BOOST_REQUIRE(add_and_verify(order_book, &ask1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonAskMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1250, 600); // AON SimpleOrder bid1(true, 1251, 100); // AON SimpleOrder bid2(true, 1251, 100); SimpleOrder bid3(true, 1251, 100); SimpleOrder bid0(true, 1250, 700); // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &bid2, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid3, false)); // Verify sizes BOOST_REQUIRE_EQUAL(4, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 3, 300)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 700)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid1, 100, 125100); SimpleFillCheck fc1(&bid2, 100, 125100); SimpleFillCheck fc2(&bid3, 100, 125100); SimpleFillCheck fc3(&bid0, 300, 1250 * 300); SimpleFillCheck fc4(&ask1, 600, 750300); BOOST_REQUIRE(add_and_verify(order_book, &ask1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonAskNoMatchMulti) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1250, 600); // AON SimpleOrder bid1(true, 1251, 100); // AON SimpleOrder bid2(true, 1251, 400); SimpleOrder bid0(true, 1250, 400); // AON no match // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &bid2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 2, 500)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // No match { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc0(&bid0, 0, 0); SimpleFillCheck fc1(&bid1, 0, 0); SimpleFillCheck fc2(&bid2, 0, 0); SimpleFillCheck fc3(&ask1, 0, 0); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false, false, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1251, 2, 500)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 400)); BOOST_REQUIRE(dc.verify_ask(1250, 1, 600)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(3, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestAonAskMatchAon) { SimpleOrderBook order_book; SimpleOrder ask0(false, 1252, 100); SimpleOrder ask1(false, 1251, 200); // AON SimpleOrder bid1(true, 1251, 200); // AON SimpleOrder bid0(true, 1250, 400); // No match BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_bid(1251, 1, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 400)); // Match complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&bid1, 200, 1251 * 200); SimpleFillCheck fc3(&ask1, 200, 1251 * 200); BOOST_REQUIRE(add_and_verify(order_book, &ask1, true, true, AON)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 400)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestReplaceAonBidSmallerMatch) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1253, 100); SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 100); SimpleOrder bid1(true, 1251, 200); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 1, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc2(&ask0, 100, 125100); BOOST_REQUIRE(replace_and_verify( order_book, &bid1, -100, PRICE_UNCHANGED, impl::os_complete, 100)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestReplaceAonBidPriceMatch) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1253, 100); SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 100); SimpleOrder bid1(true, 1251, 200); // AON SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 1, 200)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc1(&ask0, 100, 125100); SimpleFillCheck fc2(&ask1, 100, 125200); BOOST_REQUIRE(replace_and_verify( order_book, &bid1, 0, 1252, impl::os_complete, 200)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(1, order_book.asks().size()); } BOOST_AUTO_TEST_CASE(TestReplaceBidLargerMatchAon) { SimpleOrderBook order_book; SimpleOrder ask2(false, 1253, 100); SimpleOrder ask1(false, 1252, 100); SimpleOrder ask0(false, 1251, 200); // AON SimpleOrder bid1(true, 1251, 100); SimpleOrder bid0(true, 1250, 100); // No match BOOST_REQUIRE(add_and_verify(order_book, &bid0, false)); BOOST_REQUIRE(add_and_verify(order_book, &bid1, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask0, false, false, AON)); BOOST_REQUIRE(add_and_verify(order_book, &ask1, false)); BOOST_REQUIRE(add_and_verify(order_book, &ask2, false)); // Verify sizes BOOST_REQUIRE_EQUAL(2, order_book.bids().size()); BOOST_REQUIRE_EQUAL(3, order_book.asks().size()); // Verify depth DepthCheck dc(order_book.depth()); BOOST_REQUIRE(dc.verify_bid(1251, 1, 100)); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1251, 1, 200)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Match - complete { BOOST_REQUIRE_NO_THROW( SimpleFillCheck fc2(&ask0, 200, 200 * 1251); BOOST_REQUIRE(replace_and_verify( order_book, &bid1, 100, PRICE_UNCHANGED, impl::os_complete, 200)); ); } // Verify depth dc.reset(); BOOST_REQUIRE(dc.verify_bid(1250, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1252, 1, 100)); BOOST_REQUIRE(dc.verify_ask(1253, 1, 100)); // Verify sizes BOOST_REQUIRE_EQUAL(1, order_book.bids().size()); BOOST_REQUIRE_EQUAL(2, order_book.asks().size()); } } // Namespace
32.025099
75
0.711174
[ "object" ]
a51671c9d0119aea2b6a3d8af0992a0a12f3dd71
17,085
cc
C++
vm_tools/cicerone/tremplin_listener_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
vm_tools/cicerone/tremplin_listener_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
vm_tools/cicerone/tremplin_listener_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2018 The Chromium OS 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 "vm_tools/cicerone/tremplin_listener_impl.h" #include <arpa/inet.h> #include <inttypes.h> #include <stdio.h> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include <base/bind.h> #include <base/logging.h> #include <base/strings/string_util.h> #include <base/threading/thread_task_runner_handle.h> #include "vm_tools/cicerone/service.h" namespace vm_tools { namespace cicerone { TremplinListenerImpl::TremplinListenerImpl( base::WeakPtr<vm_tools::cicerone::Service> service) : service_(service), task_runner_(base::ThreadTaskRunnerHandle::Get()) {} void TremplinListenerImpl::OverridePeerAddressForTesting( const std::string& testing_peer_address) { base::AutoLock lock_scope(testing_peer_address_lock_); testing_peer_address_ = testing_peer_address; } grpc::Status TremplinListenerImpl::TremplinReady( grpc::ServerContext* ctx, const vm_tools::tremplin::TremplinStartupInfo* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } bool result = false; base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::ConnectTremplin, service_, cid, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Received TremplinReady but could not find matching VM: " << ctx->peer(); return grpc::Status(grpc::FAILED_PRECONDITION, "Cannot find VM for TremplinListener"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateCreateStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerCreationProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } bool result = false; base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); if (request->status() == tremplin::ContainerCreationProgress::DOWNLOADING) { task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::LxdContainerDownloading, service_, cid, request->container_name(), request->download_progress(), &result, &event)); } else { vm_tools::cicerone::Service::CreateStatus status; switch (request->status()) { case tremplin::ContainerCreationProgress::CREATED: status = vm_tools::cicerone::Service::CreateStatus::CREATED; break; case tremplin::ContainerCreationProgress::DOWNLOAD_TIMED_OUT: status = vm_tools::cicerone::Service::CreateStatus::DOWNLOAD_TIMED_OUT; break; case tremplin::ContainerCreationProgress::CANCELLED: status = vm_tools::cicerone::Service::CreateStatus::CANCELLED; break; case tremplin::ContainerCreationProgress::FAILED: status = vm_tools::cicerone::Service::CreateStatus::FAILED; break; default: status = vm_tools::cicerone::Service::CreateStatus::UNKNOWN; break; } task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::LxdContainerCreated, service_, cid, request->container_name(), status, request->failure_reason(), &result, &event)); } event.Wait(); if (!result) { LOG(ERROR) << "Received UpdateCreateStatus RPC but could not find matching VM: " << ctx->peer(); return grpc::Status(grpc::FAILED_PRECONDITION, "Cannot find VM for TremplinListener"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateDeletionStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerDeletionProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } bool result = false; base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::LxdContainerDeleted, service_, cid, request->container_name(), request->status(), request->failure_reason(), &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Received UpdateDeletionStatus RPC but could not find matching VM: " << ctx->peer(); return grpc::Status(grpc::FAILED_PRECONDITION, "Cannot find VM for TremplinListener"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateStartStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerStartProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } bool result = false; base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); vm_tools::cicerone::Service::StartStatus status; switch (request->status()) { case tremplin::ContainerStartProgress::STARTED: status = vm_tools::cicerone::Service::StartStatus::STARTED; break; case tremplin::ContainerStartProgress::CANCELLED: status = vm_tools::cicerone::Service::StartStatus::CANCELLED; break; case tremplin::ContainerStartProgress::FAILED: status = vm_tools::cicerone::Service::StartStatus::FAILED; break; default: status = vm_tools::cicerone::Service::StartStatus::UNKNOWN; break; } task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::LxdContainerStarting, service_, cid, request->container_name(), status, request->failure_reason(), &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Received UpdateStartStatus RPC but could not find matching VM: " << ctx->peer(); return grpc::Status(grpc::FAILED_PRECONDITION, "Cannot find VM for TremplinListener"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateExportStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerExportProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } ExportLxdContainerProgressSignal progress_signal; if (!ExportLxdContainerProgressSignal::Status_IsValid( static_cast<int>(request->status()))) { return grpc::Status(grpc::FAILED_PRECONDITION, "Invalid status field in protobuf request"); } progress_signal.set_status( static_cast<ExportLxdContainerProgressSignal::Status>(request->status())); progress_signal.set_container_name(request->container_name()); progress_signal.set_failure_reason(request->failure_reason()); progress_signal.set_total_input_files(request->total_input_files()); progress_signal.set_total_input_bytes(request->total_input_bytes()); progress_signal.set_input_files_streamed(request->input_files_streamed()); progress_signal.set_input_bytes_streamed(request->input_bytes_streamed()); progress_signal.set_bytes_exported(request->bytes_exported()); base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::ContainerExportProgress, service_, cid, &progress_signal, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Failure updating container export progress"; return grpc::Status(grpc::FAILED_PRECONDITION, "Failure in UpdateExportStatus"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateImportStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerImportProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } ImportLxdContainerProgressSignal progress_signal; if (!ImportLxdContainerProgressSignal::Status_IsValid( static_cast<int>(request->status()))) { return grpc::Status(grpc::FAILED_PRECONDITION, "Invalid status field in protobuf request"); } progress_signal.set_status( static_cast<ImportLxdContainerProgressSignal::Status>(request->status())); progress_signal.set_container_name(request->container_name()); progress_signal.set_progress_percent(request->progress_percent()); progress_signal.set_progress_speed(request->progress_speed()); progress_signal.set_failure_reason(request->failure_reason()); progress_signal.set_architecture_device(request->architecture_device()); progress_signal.set_architecture_container(request->architecture_container()); progress_signal.set_available_space(request->disk_space_available_bytes()); progress_signal.set_min_required_space(request->disk_space_required_bytes()); base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::ContainerImportProgress, service_, cid, &progress_signal, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Failure updating container import progress"; return grpc::Status(grpc::FAILED_PRECONDITION, "Failure in UpdateImportStatus"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::ContainerShutdown( grpc::ServerContext* ctx, const vm_tools::tremplin::ContainerShutdownInfo* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } if (request->container_name().empty()) { return grpc::Status(grpc::INVALID_ARGUMENT, "`container_name` cannot be empty"); } // Calls coming from tremplin are trusted to use container_name rather than // container_token. std::string container_token = ""; base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::ContainerShutdown, service_, request->container_name(), container_token, cid, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Error in tremplin listener ContainerShutdown for " << request->container_name(); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateListeningPorts( grpc::ServerContext* ctx, const vm_tools::tremplin::ListeningPortInfo* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } std::map<std::string, std::vector<uint16_t>> listening_tcp4_ports; for (auto& pair : request->container_ports()) { std::vector<uint16_t> target_ports; for (int i = 0; i < pair.second.listening_tcp4_ports_size(); i++) { target_ports.push_back(pair.second.listening_tcp4_ports(i)); } listening_tcp4_ports[pair.first] = target_ports; } base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::UpdateListeningPorts, service_, std::move(listening_tcp4_ports), cid, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Error in tremplin listener UpdateListeningPorts"; } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpgradeContainerStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::UpgradeContainerProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } UpgradeContainerProgressSignal progress_signal; if (!UpgradeContainerProgressSignal::Status_IsValid( static_cast<int>(request->status()))) { return grpc::Status(grpc::FAILED_PRECONDITION, "Invalid status field in protobuf request"); } progress_signal.set_status( static_cast<UpgradeContainerProgressSignal::Status>(request->status())); progress_signal.set_container_name(request->container_name()); progress_signal.set_failure_reason(request->failure_reason()); progress_signal.mutable_progress_messages()->CopyFrom( request->progress_messages()); base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::ContainerUpgradeProgress, service_, cid, &progress_signal, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Failure sending upgrade container progress"; return grpc::Status(grpc::FAILED_PRECONDITION, "Failure in UgradeContainertatus"); } return grpc::Status::OK; } grpc::Status TremplinListenerImpl::UpdateStartLxdStatus( grpc::ServerContext* ctx, const vm_tools::tremplin::StartLxdProgress* request, vm_tools::tremplin::EmptyMessage* response) { uint32_t cid = ExtractCidFromPeerAddress(ctx); if (cid == 0) { return grpc::Status(grpc::FAILED_PRECONDITION, "Failed parsing vsock cid for TremplinListener"); } StartLxdProgressSignal progress_signal; if (!StartLxdProgressSignal::Status_IsValid( static_cast<int>(request->status()))) { return grpc::Status(grpc::FAILED_PRECONDITION, "Invalid status field in protobuf request"); } progress_signal.set_status( static_cast<StartLxdProgressSignal::Status>(request->status())); progress_signal.set_failure_reason(request->failure_reason()); base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); bool result = false; task_runner_->PostTask( FROM_HERE, base::Bind(&vm_tools::cicerone::Service::StartLxdProgress, service_, cid, &progress_signal, &result, &event)); event.Wait(); if (!result) { LOG(ERROR) << "Failure sending start lxd progress"; return grpc::Status(grpc::FAILED_PRECONDITION, "Failure in StartLxdStatus"); } return grpc::Status::OK; } // Returns 0 on failure, otherwise returns the 32-bit vsock cid. uint32_t TremplinListenerImpl::ExtractCidFromPeerAddress( grpc::ServerContext* ctx) { uint32_t cid = 0; std::string peer_address = ctx->peer(); { base::AutoLock lock_scope(testing_peer_address_lock_); if (!testing_peer_address_.empty()) { peer_address = testing_peer_address_; } } if (sscanf(peer_address.c_str(), "vsock:%" SCNu32, &cid) != 1) { LOG(WARNING) << "Failed to parse peer address " << peer_address; return 0; } return cid; } } // namespace cicerone } // namespace vm_tools
38.221477
80
0.683465
[ "vector" ]
a517675220ff3a0c73fc76d7251e02ee114c6d6c
303
hpp
C++
src/Pieces.hpp
optisimon/office-space-tetris
11bb1b196a35e05471f84b76cc9d5bf76d22d779
[ "MIT" ]
null
null
null
src/Pieces.hpp
optisimon/office-space-tetris
11bb1b196a35e05471f84b76cc9d5bf76d22d779
[ "MIT" ]
null
null
null
src/Pieces.hpp
optisimon/office-space-tetris
11bb1b196a35e05471f84b76cc9d5bf76d22d779
[ "MIT" ]
null
null
null
#pragma once #include "GridWithOffset.hpp" #include <vector> std::vector<GridWithOffset> getSquare(); std::vector<GridWithOffset> getRod(); std::vector<GridWithOffset> getT(); std::vector<GridWithOffset> getN(); std::vector<GridWithOffset> getZ(); std::vector<GridWithOffset> getRandomPiece();
15.947368
45
0.745875
[ "vector" ]
a51e73fde3f05edc31812e2932b137bc0f66fe72
11,225
cpp
C++
openfpga/src/annotation/annotate_bitstream_setting.cpp
avesus/OpenFPGA
c1dab2168655d41eb59d4923156dabd253ffbd3e
[ "MIT" ]
246
2020-12-03T08:49:29.000Z
2022-03-28T21:19:55.000Z
openfpga/src/annotation/annotate_bitstream_setting.cpp
developeralgo8888/OpenFPGA
067f2eaaad03945896b9a7cc21cd9f361bf1546d
[ "MIT" ]
261
2020-12-03T00:23:54.000Z
2022-03-31T10:00:37.000Z
openfpga/src/annotation/annotate_bitstream_setting.cpp
developeralgo8888/OpenFPGA
067f2eaaad03945896b9a7cc21cd9f361bf1546d
[ "MIT" ]
66
2020-12-12T09:05:53.000Z
2022-03-28T07:51:41.000Z
/******************************************************************** * This file includes functions that are used to annotate pb_type * from VPR to OpenFPGA *******************************************************************/ #include <cmath> #include <iterator> /* Headers from openfpgashell library */ #include "command_exit_codes.h" /* Headers from vtrutil library */ #include "vtr_assert.h" #include "vtr_log.h" /* Headers from openfpgautil library */ #include "openfpga_tokenizer.h" #include "pb_type_utils.h" #include "annotate_bitstream_setting.h" /* begin namespace openfpga */ namespace openfpga { /******************************************************************** * Annotate bitstream setting based on VPR device information * - Find the pb_type and link to the bitstream source * - Find the pb_type and link to the bitstream content *******************************************************************/ static int annotate_bitstream_pb_type_setting(const BitstreamSetting& bitstream_setting, const DeviceContext& vpr_device_ctx, VprBitstreamAnnotation& vpr_bitstream_annotation) { for (const auto& bitstream_pb_type_setting_id : bitstream_setting.pb_type_settings()) { /* Get the full name of pb_type */ std::vector<std::string> target_pb_type_names; std::vector<std::string> target_pb_mode_names; target_pb_type_names = bitstream_setting.parent_pb_type_names(bitstream_pb_type_setting_id); target_pb_type_names.push_back(bitstream_setting.pb_type_name(bitstream_pb_type_setting_id)); target_pb_mode_names = bitstream_setting.parent_mode_names(bitstream_pb_type_setting_id); /* Pb type information are located at the logic_block_types in the device context of VPR * We iterate over the vectors and find the pb_type matches the parent_pb_type_name */ bool link_success = false; for (const t_logical_block_type& lb_type : vpr_device_ctx.logical_block_types) { /* By pass nullptr for pb_type head */ if (nullptr == lb_type.pb_type) { continue; } /* Check the name of the top-level pb_type, if it does not match, we can bypass */ if (target_pb_type_names[0] != std::string(lb_type.pb_type->name)) { continue; } /* Match the name in the top-level, we go further to search the pb_type in the graph */ t_pb_type* target_pb_type = try_find_pb_type_with_given_path(lb_type.pb_type, target_pb_type_names, target_pb_mode_names); if (nullptr == target_pb_type) { continue; } /* Found one, build annotation */ if (std::string("eblif") != bitstream_setting.pb_type_bitstream_source(bitstream_pb_type_setting_id)) { /* Invalid source, error out! */ VTR_LOG_ERROR("Invalid bitstream source '%s' for pb_type '%s' which is defined in bitstream setting\n", bitstream_setting.pb_type_bitstream_source(bitstream_pb_type_setting_id).c_str(), target_pb_type_names[0].c_str()); return CMD_EXEC_FATAL_ERROR; } /* Depending on the bitstream type, annotate through different entrances * - For regular bitstream, set bitstream content, flags etc. * - For mode-select bitstream, set mode-select bitstream content, flags etc. */ if (false == bitstream_setting.is_mode_select_bitstream(bitstream_pb_type_setting_id)) { vpr_bitstream_annotation.set_pb_type_bitstream_source(target_pb_type, VprBitstreamAnnotation::e_bitstream_source_type::BITSTREAM_SOURCE_EBLIF); vpr_bitstream_annotation.set_pb_type_bitstream_content(target_pb_type, bitstream_setting.pb_type_bitstream_content(bitstream_pb_type_setting_id)); vpr_bitstream_annotation.set_pb_type_bitstream_offset(target_pb_type, bitstream_setting.bitstream_offset(bitstream_pb_type_setting_id)); } else { VTR_ASSERT_SAFE(false == bitstream_setting.is_mode_select_bitstream(bitstream_pb_type_setting_id)); vpr_bitstream_annotation.set_pb_type_mode_select_bitstream_source(target_pb_type, VprBitstreamAnnotation::e_bitstream_source_type::BITSTREAM_SOURCE_EBLIF); vpr_bitstream_annotation.set_pb_type_mode_select_bitstream_content(target_pb_type, bitstream_setting.pb_type_bitstream_content(bitstream_pb_type_setting_id)); vpr_bitstream_annotation.set_pb_type_mode_select_bitstream_offset(target_pb_type, bitstream_setting.bitstream_offset(bitstream_pb_type_setting_id)); } link_success = true; } /* If fail to link bitstream setting to architecture, error out immediately */ if (false == link_success) { VTR_LOG_ERROR("Fail to find a pb_type '%s' which is defined in bitstream setting from VPR architecture description\n", target_pb_type_names[0].c_str()); return CMD_EXEC_FATAL_ERROR; } } return CMD_EXEC_SUCCESS; } /******************************************************************** * Annotate bitstream setting based on VPR device information * - Find the interconnect and link to the default path id *******************************************************************/ static int annotate_bitstream_interconnect_setting(const BitstreamSetting& bitstream_setting, const DeviceContext& vpr_device_ctx, const VprDeviceAnnotation& vpr_device_annotation, VprBitstreamAnnotation& vpr_bitstream_annotation) { for (const auto& bitstream_interc_setting_id : bitstream_setting.interconnect_settings()) { /* Get the full name of pb_type */ std::vector<std::string> target_pb_type_names; std::vector<std::string> target_pb_mode_names; target_pb_type_names = bitstream_setting.parent_pb_type_names(bitstream_interc_setting_id); target_pb_mode_names = bitstream_setting.parent_mode_names(bitstream_interc_setting_id); /* Kick out the last mode so that we can use an existing function search the pb_type in graph */ std::string expected_physical_mode_name = target_pb_mode_names.back(); target_pb_mode_names.pop_back(); std::string interconnect_name = bitstream_setting.interconnect_name(bitstream_interc_setting_id); std::string expected_input_path = bitstream_setting.default_path(bitstream_interc_setting_id); /* Pb type information are located at the logic_block_types in the device context of VPR * We iterate over the vectors and find the pb_type matches the parent_pb_type_name */ bool link_success = false; for (const t_logical_block_type& lb_type : vpr_device_ctx.logical_block_types) { /* By pass nullptr for pb_type head */ if (nullptr == lb_type.pb_type) { continue; } /* Check the name of the top-level pb_type, if it does not match, we can bypass */ if (target_pb_type_names[0] != std::string(lb_type.pb_type->name)) { continue; } /* Match the name in the top-level, we go further to search the pb_type in the graph */ t_pb_type* target_pb_type = try_find_pb_type_with_given_path(lb_type.pb_type, target_pb_type_names, target_pb_mode_names); if (nullptr == target_pb_type) { continue; } /* Found one, build annotation */ t_mode* physical_mode = vpr_device_annotation.physical_mode(target_pb_type); VTR_ASSERT(nullptr != physical_mode); /* Ensure that the annotation is only applicable to physical mode */ if (std::string(physical_mode->name) != expected_physical_mode_name) { VTR_LOG_ERROR("The physical mode '%s' under pb_type '%s' does not match in the bitstream setting '%s'!\n", physical_mode->name, target_pb_type->name, expected_physical_mode_name.c_str()); return CMD_EXEC_FATAL_ERROR; } /* Find the interconnect name under the physical mode of a physical pb_type */ t_interconnect* pb_interc = find_pb_mode_interconnect(physical_mode, interconnect_name.c_str()); if (nullptr == pb_interc) { VTR_LOG_ERROR("Unable to find interconnect '%s' under physical mode '%s' of pb_type '%s'!\n", interconnect_name.c_str(), physical_mode->name, target_pb_type->name); return CMD_EXEC_FATAL_ERROR; } /* Find the default path and spot the path id from the input string recorded */ StringToken input_string_tokenizer(std::string(pb_interc->input_string)); std::vector<std::string> input_paths = input_string_tokenizer.split(' '); size_t input_path_id = input_paths.size(); for (size_t ipath = 0; ipath < input_paths.size(); ++ipath) { if (expected_input_path == input_paths[ipath]) { input_path_id = ipath; break; } } /* If the input_path id is invalid, error out! */ if (input_path_id == input_paths.size()) { VTR_LOG_ERROR("Invalid default path '%s' for interconnect '%s' which inputs are '%s'\n", expected_input_path.c_str(), interconnect_name.c_str(), pb_interc->input_string); return CMD_EXEC_FATAL_ERROR; } vpr_bitstream_annotation.set_interconnect_default_path_id(pb_interc, input_path_id); link_success = true; } /* If fail to link bitstream setting to architecture, error out immediately */ if (false == link_success) { VTR_LOG_ERROR("Fail to find an interconnect '%s' with default path '%s', which is defined in bitstream setting from VPR architecture description\n", interconnect_name.c_str(), expected_input_path.c_str()); return CMD_EXEC_FATAL_ERROR; } } return CMD_EXEC_SUCCESS; } /******************************************************************** * Annotate bitstream setting based on VPR device information * - Fill pb_type -related mapping * - Fill interconnect -related mapping *******************************************************************/ int annotate_bitstream_setting(const BitstreamSetting& bitstream_setting, const DeviceContext& vpr_device_ctx, const VprDeviceAnnotation& vpr_device_annotation, VprBitstreamAnnotation& vpr_bitstream_annotation) { int status = CMD_EXEC_SUCCESS; status = annotate_bitstream_pb_type_setting(bitstream_setting, vpr_device_ctx, vpr_bitstream_annotation); if (status == CMD_EXEC_FATAL_ERROR) { return status; } status = annotate_bitstream_interconnect_setting(bitstream_setting, vpr_device_ctx, vpr_device_annotation, vpr_bitstream_annotation); return status; } } /* end namespace openfpga */
47.970085
166
0.648285
[ "vector" ]
a51f97a524376ad57053eaac76aac4598db5ed5f
3,501
cpp
C++
September_2020_challange/Day 6.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
September_2020_challange/Day 6.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
September_2020_challange/Day 6.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
/* Problem Name : Image Overlap Description : Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images. (Note also that a translation does not include any kind of rotation.) What is the largest possible overlap? Example 1: Input: A = [[1,1,0],[0,1,0],[0,1,0]] B = [[0,0,0],[0,1,1],[0,0,1]] Output: 3 Explanation: We slide A to right by 1 unit and down by 1 unit. Notes: 1 <= A.length = A[0].length = B.length = B[0].length <= 30 0 <= A[i][j], B[i][j] <= 1 */ // Approach i simply run loop for every possible move in right and down direction and simultaneously in Up left direction and which ever gives maximum i save that O(n4) // Code int calcRD(vector<vector<int>>& a, vector<vector<int>>& b, int x, int y){ int n = a.size(); int count = 0; for(int i = x, c = 0; c<n && i<n; i++, c++){ for(int j = y, d = 0; d<n && j<n; j++, d++){ count += a[c][d] && b[i][j]; } } cout<<count; return count; } int calcLU(vector<vector<int>>& a, vector<vector<int>>& b, int x, int y){ int n = a.size(); int count = 0; for(int i = x, c = 0; c<n && i<n; i++, c++){ for(int j = y, d = 0; d<n && j<n; j++, d++){ count += a[i][j] && b[c][d]; } } // cout<<count; return count; } int largestOverlap(vector<vector<int>>& a, vector<vector<int>>& b) { int n = a.size(); int count = 0; for(int i = 0; i<n; i++){ for(int j = 0; j<n; j++){ count = max(count, max(calcRD(a, b, i, j), calcLU(a, b, i, j))); } } return count; } // Better but same complexity solution class Solution { protected int shiftAndCount(int xShift, int yShift, int[][] M, int[][] R) { int count = 0; int rRow = 0; // count the cells of ones in the overlapping zone. for (int mRow = yShift; mRow < M.length; ++mRow) { int rCol = 0; for (int mCol = xShift; mCol < M.length; ++mCol) { if (M[mRow][mCol] == 1 && M[mRow][mCol] == R[rRow][rCol]) count += 1; rCol += 1; } rRow += 1; } return count; } public int largestOverlap(int[][] A, int[][] B) { int maxOverlaps = 0; for (int yShift = 0; yShift < A.length; ++yShift) for (int xShift = 0; xShift < A.length; ++xShift) { // move one of the matrice up and left and vice versa. // (equivalent to move the other matrix down and right) maxOverlaps = Math.max(maxOverlaps, shiftAndCount(xShift, yShift, A, B)); maxOverlaps = Math.max(maxOverlaps, shiftAndCount(xShift, yShift, B, A)); } return maxOverlaps; } } // As we see we are doing extra work for cell with 0 again and again to avoid that we can use linear transformation // Other is using convonution overlapping
40.241379
168
0.512996
[ "vector" ]
a5230f4dc10492f7cc1bb9d50296a4e6e0e3ecf4
2,235
cpp
C++
CocoaEngine/cpp/cocoa/core/Application.cpp
PixelRifts/Cocoa
35bd8e5d2fb4dcd64e583e9889a7d01aa915d6dc
[ "MIT" ]
35
2021-01-01T15:51:44.000Z
2022-03-30T00:57:04.000Z
CocoaEngine/cpp/cocoa/core/Application.cpp
PixelRifts/Cocoa
35bd8e5d2fb4dcd64e583e9889a7d01aa915d6dc
[ "MIT" ]
3
2021-02-17T07:42:53.000Z
2021-08-09T20:13:49.000Z
CocoaEngine/cpp/cocoa/core/Application.cpp
PixelRifts/Cocoa
35bd8e5d2fb4dcd64e583e9889a7d01aa915d6dc
[ "MIT" ]
4
2021-02-10T12:58:38.000Z
2021-04-29T06:01:54.000Z
#include "externalLibs.h" #include "cocoa/core/Core.h" #include "cocoa/core/Application.h" #include "cocoa/renderer/DebugDraw.h" #include "cocoa/core/Entity.h" namespace Cocoa { // Stub methods static void AppOnUpdate(SceneData& scene, float dt) { } static void AppOnAttach(SceneData& scene) { } static void AppOnRender(SceneData& scene) { } static void AppOnEvent(SceneData& scene, Event& e) { } Application::Application() { m_Running = true; std::string title = std::string("Test Window"); Log::Info("Initializing GLAD functions in DLL."); m_Window = CWindow::Create(1920, 1080, title); s_Instance = this; m_Window->SetEventCallback(std::bind(&Application::OnEvent, this, std::placeholders::_1)); } Application::~Application() { } void Application::Run() { if (!m_AppData.AppOnAttach) { m_AppData.AppOnAttach = AppOnAttach; } if (!m_AppData.AppOnEvent) { m_AppData.AppOnEvent = AppOnEvent; } if (!m_AppData.AppOnRender) { m_AppData.AppOnRender = AppOnRender; } if (!m_AppData.AppOnUpdate) { m_AppData.AppOnUpdate = AppOnUpdate; } m_AppData.AppOnAttach(m_CurrentScene); while (m_Running) { float time = (float)glfwGetTime(); float dt = time - m_LastFrameTime; m_LastFrameTime = time; BeginFrame(); m_AppData.AppOnUpdate(m_CurrentScene, dt); m_AppData.AppOnRender(m_CurrentScene); EndFrame(); m_Window->OnUpdate(); m_Window->Render(); } // TODO: Should this be a thing? (probably, add support at some point...) //for (Layer* layer : m_Layers) //{ // layer->OnDetach(); //} m_Window->Destroy(); } bool Application::OnWindowClose(WindowCloseEvent& e) { m_Running = false; return true; } void Application::OnEvent(Event& e) { EventDispatcher dispatcher(e); dispatcher.Dispatch<WindowCloseEvent>(std::bind(&Application::OnWindowClose, this, std::placeholders::_1)); m_AppData.AppOnEvent(m_CurrentScene, e); } void Application::Stop() { m_Running = false; } CWindow* Application::GetWindow() const { return m_Window; } Application* Application::s_Instance = nullptr; Application* Application::Get() { if (!s_Instance) { Log::Error("Cannot get application. It is nullptr."); } return s_Instance; } }
22.575758
109
0.697987
[ "render" ]
a523709046dcfea1e3f827ca8d94c345b3c9abde
1,116
cpp
C++
leetcode1248.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode1248.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode1248.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
class Solution { public: int numberOfSubarrays(vector<int>& nums, int k) { int res = 0; vector<int> left(nums.size(), 1); vector<int> right(nums.size(), 1); int tmp = 1; for(int k = 0; k < nums.size(); i++) { if(nums[k] % 2 == 0) tmp++; else { left[k] = tmp; tmp = 1; } } tmp = 1; for(int k = nums.size() - 1; k >= 0; k--) { if(nums[k] % 2 == 0) tmp++; else { right[k] = tmp; tmp = 1; } } int cnt = 1; int i = 0; int j = 0; while(nums[i] % 2 == 0) i++; j = i; while(j < nums.size()) { if(cnt == k) { res += (left[i] * right[j]); i++; while(i <= j && nums[i] % 2 == 0) i++; cnt--; } if(nums[++j] % 2 == 1) cnt++; } return res; } };
21.882353
53
0.285842
[ "vector" ]
a52479af427c32396eefadb4b9422a6340469357
630
cc
C++
src/abc004/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc004/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc004/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<string> res = {"213456", "231456", "234156", "234516", "234561", "324561", "342561", "345261", "345621", "345612", "435612", "453612", "456312", "456132", "456123", "546123", "564123", "561423", "561243", "561234", "651234", "615234", "612534", "612354", "612345", "162345", "126345", "123645", "123465", "123456"}; #ifndef _debug int main() { ll n; cin >> n; cout << res[(n - 1ll) % (ll)res.size()] << endl; return 0; } #endif
33.157895
72
0.487302
[ "vector" ]
a52822f20c8d7021783144e188cfa686fd89d872
1,477
cpp
C++
src/legal_moves.cpp
kz04px/libataxx
b61bfb303b424893c233c2e8f42f47b14e2fc1a1
[ "MIT" ]
6
2019-10-23T15:58:39.000Z
2020-12-28T20:49:25.000Z
src/legal_moves.cpp
kz04px/libataxx
b61bfb303b424893c233c2e8f42f47b14e2fc1a1
[ "MIT" ]
1
2022-02-21T02:28:56.000Z
2022-02-21T15:28:59.000Z
src/legal_moves.cpp
kz04px/libataxx
b61bfb303b424893c233c2e8f42f47b14e2fc1a1
[ "MIT" ]
1
2019-10-11T21:07:19.000Z
2019-10-11T21:07:19.000Z
#include "libataxx/libataxx.hpp" #include "libataxx/move.hpp" namespace libataxx { [[nodiscard]] int Position::legal_moves(Move *movelist) const noexcept { assert(movelist); if (gameover()) { return 0; } int num_moves = 0; // Single moves const Bitboard singles = us().singles() & empty(); for (const auto &to : singles) { movelist[num_moves] = Move(to); num_moves++; } // Double moves for (const auto &from : us()) { const Bitboard destinations = Bitboard{from}.doubles() & empty(); for (const auto &to : destinations) { movelist[num_moves] = Move(from, to); num_moves++; } } if (num_moves == 0) { movelist[0] = Move::nullmove(); num_moves++; } return num_moves; } [[nodiscard]] std::vector<Move> Position::legal_moves() const noexcept { if (gameover()) { return {}; } std::vector<Move> moves; // Single moves const Bitboard singles = us().singles() & empty(); for (const auto &to : singles) { moves.emplace_back(to); } // Double moves for (const auto &from : us()) { const Bitboard destinations = Bitboard{from}.doubles() & empty(); for (const auto &to : destinations) { moves.emplace_back(from, to); } } if (moves.empty()) { moves.push_back(Move::nullmove()); } return moves; } } // namespace libataxx
21.720588
73
0.559242
[ "vector" ]
a52b5b9ac5a359d87c1e4ee1144be712972b98b4
33,104
cpp
C++
scene/gui/label.cpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
scene/gui/label.cpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
scene/gui/label.cpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
/*************************************************************************/ /* label.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "label.h" #include "core/print_string.h" #include "core/project_settings.h" #include "core/translation.h" #include "label_transitions.h" #define _RemoveCacheList(wc) \ while (wc) { \ WordList *current = wc; \ wc = current->next; \ memdelete(current); \ }; \ wc = nullptr void Label::set_autowrap(bool p_autowrap) { if (autowrap == p_autowrap) { return; } autowrap = p_autowrap; word_cache_dirty = true; update(); if (clip) { minimum_size_changed(); } } bool Label::has_autowrap() const { return autowrap; } void Label::set_uppercase(bool p_uppercase) { uppercase = p_uppercase; word_cache_dirty = true; update(); } bool Label::is_uppercase() const { return uppercase; } int Label::get_line_height() const { return get_font("font")->get_height(); } void Label::_notification(int p_what) { if (p_what == NOTIFICATION_TRANSLATION_CHANGED) { if (is_transition_enabled()) { String new_text = tr(transition_text.text); if (new_text == transition_text.xl_text) { return; //nothing new } transition_text.xl_text = new_text; } else { String new_text = tr(text); if (new_text == xl_text) return; //nothing new xl_text = new_text; } regenerate_word_cache(); update(); } else if (p_what == NOTIFICATION_DRAW) { if (clip) { VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(), true); } if (word_cache_dirty) { regenerate_word_cache(); } if (_transition_dirty || _cache_changed) { if (is_transition_enabled()) _transition_controller->init_transition(this, transition_duration, ease_func_table[transition_ease], &transition_text.word_cache, &word_cache); _cache_changed = _transition_dirty = false; } std::vector<WordCache *> draw_set{ &word_cache }; if (is_transition_active()) { draw_set = _transition_controller->get_draw_cache(); } if (draw_set.empty()) { // nothing to draw return; } RID ci = get_canvas_item(); Size2 string_size; Size2 size = get_size(); Ref<StyleBox> style = get_stylebox("normal"); Ref<Font> font = get_font("font"); Color font_color = get_color("font_color"); Color font_color_shadow = get_color("font_color_shadow"); bool use_outline = get_constant("shadow_as_outline"); Point2 shadow_ofs(get_constant("shadow_offset_x"), get_constant("shadow_offset_y")); const int line_spacing = get_constant("line_spacing"); Color font_outline_modulate = get_color("font_outline_modulate"); style->draw(ci, Rect2(Point2(0, 0), get_size())); VisualServer::get_singleton()->canvas_item_set_distance_field_mode(get_canvas_item(), font.is_valid() && font->is_distance_field_hint()); const int font_h = font->get_height() + line_spacing + vertical_spacing; const int lines_visible_rc = (size.y + line_spacing) / font_h; const real_t space_w = font->get_char_size(' ').width + horizontal_spacing; int chars_total = 0; int vbegin = 0, vsep = 0; FontDrawer drawer(font, font_outline_modulate); size_t draw_index = 0; draw_loop: const WordCache *cc = draw_set[draw_index]; const WordList *wc = cc->words; int lines_visible = MAX(lines_visible_rc, cc->line_count); if (max_lines_visible >= 0 && lines_visible > max_lines_visible) { lines_visible = max_lines_visible; } int line = 0, line_to = lines_skipped + (lines_visible > 0 ? lines_visible : 1); float total_h = 0; if (!wc) { // nothing to draw goto draw_next; } total_h += lines_visible * font_h; total_h += style->get_margin(MARGIN_TOP) + style->get_margin(MARGIN_BOTTOM); if (lines_visible > 0) { switch (valign) { case VALIGN_TOP: { //nothing } break; case VALIGN_CENTER: { vbegin = (size.y - (total_h - line_spacing)) / 2; vsep = 0; } break; case VALIGN_BOTTOM: { vbegin = size.y - (total_h - line_spacing); vsep = 0; } break; case VALIGN_FILL: { vbegin = 0; if (lines_visible > 1) { vsep = (size.y - (total_h - line_spacing)) / (lines_visible - 1); } else { vsep = 0; } } break; default: { WARN_PRINT("Invalid valign enumeration."); } } } while (wc) { /* quickly handle lines not meant to be drawn */ if (line >= line_to) { break; } if (line < lines_skipped) { while (wc && wc->char_pos >= 0) { wc = wc->next; } if (wc) { wc = wc->next; } line++; continue; } /* handle lines normally */ if (wc->char_pos < 0) { //empty line wc = wc->next; line++; continue; } const WordList *from = wc; // first word const WordList *to = wc; // last word int taken = 0; int spaces = 0; while (to && to->char_pos >= 0) { taken += to->pixel_width; if (to->space_count) { spaces += to->space_count; } to = to->next; } bool can_fill = to && to->char_pos == WordList::CHAR_WRAPLINE; float x_ofs = 0; switch (align) { case ALIGN_FILL: case ALIGN_LEFT: { x_ofs = style->get_offset().x; } break; case ALIGN_CENTER: { x_ofs = int(size.width - (taken + spaces * space_w)) / 2; } break; case ALIGN_RIGHT: { x_ofs = int(size.width - style->get_margin(MARGIN_RIGHT) - (taken + spaces * space_w)); } break; default: { WARN_PRINT("Invalid align enumeration."); } } float y_ofs = style->get_offset().y; y_ofs += (line - lines_skipped) * font_h + font->get_ascent(); y_ofs += vbegin + line * vsep; while (from != to) { // draw a word int pos = from->char_pos; if (from->char_pos < 0) { ERR_PRINT("BUG"); return; } if (from->space_count) { /* spacing */ x_ofs += space_w * from->space_count; if (can_fill && align == ALIGN_FILL && spaces) { x_ofs += int((size.width - (taken + space_w * spaces)) / spaces); } } if (font_color_shadow.a > 0) { int chars_total_shadow = chars_total; //save chars drawn real_t x_ofs_shadow = x_ofs; for (int i = 0; i < from->word_len; i++) { if (visible_chars < 0 || chars_total_shadow < visible_chars) { CharType c = cc->cache_text[i + pos]; CharType n = cc->cache_text[i + pos + 1]; if (uppercase) { c = String::char_uppercase(c); n = String::char_uppercase(n); } if (const CharTransform *xform = _transition_controller->get_char_xform(cc, i + pos)) { const real_t move = drawer.draw_char(ci, *xform, Point2(x_ofs_shadow, y_ofs) + shadow_ofs, c, n, font_color_shadow); if (use_outline) { drawer.draw_char(ci, *xform, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, shadow_ofs.y), c, n, font_color_shadow); drawer.draw_char(ci, *xform, Point2(x_ofs_shadow, y_ofs) + Vector2(shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow); drawer.draw_char(ci, *xform, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow); } x_ofs_shadow += move; } else { const real_t move = drawer.draw_char(ci, Point2(x_ofs_shadow, y_ofs) + shadow_ofs, c, n, font_color_shadow); if (use_outline) { drawer.draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, shadow_ofs.y), c, n, font_color_shadow); drawer.draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow); drawer.draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow); } x_ofs_shadow += move; } chars_total_shadow++; } } } const int last_char = from->word_len - 1; for (int i = 0; i < from->word_len; i++) { if (visible_chars < 0 || chars_total < visible_chars) { CharType c = cc->cache_text[i + pos]; CharType n = cc->cache_text[i + pos + 1]; if (uppercase) { c = String::char_uppercase(c); n = String::char_uppercase(n); } if (const CharTransform *xform = _transition_controller->get_char_xform(cc, i + pos)) { x_ofs += drawer.draw_char(ci, *xform, Point2(x_ofs, y_ofs), c, n, font_color); } else { x_ofs += drawer.draw_char(ci, Point2(x_ofs, y_ofs), c, n, font_color); } if (i < last_char) { x_ofs += horizontal_spacing; } chars_total++; } } from = from->next; } wc = to ? to->next : nullptr; line++; } draw_next: if (++draw_index == draw_set.size()) return; else goto draw_loop; } else if (p_what == NOTIFICATION_THEME_CHANGED) { word_cache_dirty = true; update(); } else if (p_what == NOTIFICATION_RESIZED) { word_cache_dirty = true; } else if (p_what == NOTIFICATION_INTERNAL_PROCESS) { if (is_transition_active()) { const real_t dt = get_process_delta_time(); if (_transition_controller->update(dt, ease_func_table[transition_ease])) { if (text != transition_text.text || xl_text != transition_text.xl_text) { _clear_pending_animations(); if (!autowrap || !clip) { //helps speed up some labels that may change a lot, as no resizing is requested. Do not change. minimum_size_changed(); } _change_notify(); } } update(); } } } Size2 Label::get_minimum_size() const { Size2 min_style = get_stylebox("normal")->get_minimum_size(); // don't want to mutable everything if (word_cache_dirty) { const_cast<Label *>(this)->regenerate_word_cache(); } if (autowrap) { return Size2(1, clip ? 1 : word_cache.minsize.height) + min_style; } else { Size2 ms = word_cache.minsize; if (clip) { ms.width = 1; } return ms + min_style; } } int Label::get_longest_line_width(const String &s) const { Ref<Font> font = get_font("font"); real_t max_line_width = 0; real_t line_width = 0; for (int i = 0; i < s.size(); i++) { CharType current = s[i]; if (uppercase) { current = String::char_uppercase(current); } if (current < 32) { if (line_width) { line_width -= horizontal_spacing; // remove last spacing } if (current == '\n') { if (line_width > max_line_width) { max_line_width = line_width; } line_width = 0; } } else { real_t char_width = font->get_char_size(current, s[i + 1]).width + horizontal_spacing; line_width += char_width; } } if (line_width > max_line_width) { max_line_width = line_width; } // ceiling to ensure autowrapping does not cut text return Math::ceil(max_line_width); } int Label::get_line_count() const { if (!is_inside_tree()) { return 1; } if (word_cache_dirty) { const_cast<Label *>(this)->regenerate_word_cache(); } return word_cache.line_count; } int Label::get_visible_line_count() const { int line_spacing = get_constant("line_spacing"); int font_h = get_font("font")->get_height() + line_spacing; int lines_visible = (get_size().height - get_stylebox("normal")->get_minimum_size().height + line_spacing) / font_h; if (lines_visible > word_cache.line_count) { lines_visible = word_cache.line_count; } if (max_lines_visible >= 0 && lines_visible > max_lines_visible) { lines_visible = max_lines_visible; } return lines_visible; } void Label::_dump_word_cache(const WordCache &cache) const { print_line("WordCache dump:"); print_line("cached text: " + cache.cache_text); WordList *wc = cache.words; while (wc) { print_line(vformat(" '" + cache.cache_text.substr(wc->char_pos, wc->word_len) + "' char_pos=%d,line=%d,line_pos=%d,len=%d,spc=%d", wc->char_pos, wc->line, wc->line_pos, wc->word_len, wc->space_count)); wc = wc->next; } print_line(vformat("total chars in cache: %d", cache.total_char_cache)); print_line(vformat("lines count: %d", cache.line_count)); print_line("---------------------"); } // Notice: space_count is the number of spaces before the word // Notice: spaces before end of the line/return are skipped Label::WordCache Label::calculate_word_cache(const Ref<Font> &font, const String &label_text) const { WordCache cache; cache.line_count = 1; cache.total_char_cache = 0; cache.cache_text = label_text; if (autowrap) { Ref<StyleBox> style = get_stylebox("normal"); cache.width = MAX(get_size().width, get_custom_minimum_size().width) - style->get_minimum_size().width; } else { cache.width = get_longest_line_width(label_text); } real_t current_word_size = 0; int word_pos = 0; int line_pos = 0; real_t line_width = 0; int space_count = 0; real_t space_width = font->get_char_size(' ').width + horizontal_spacing; WordList *root = nullptr, *last = nullptr; for (int i = 0; i <= label_text.length(); i++) { CharType current = i < label_text.length() ? label_text[i] : L' '; //always a space at the end, so the algo. works if (uppercase) { current = String::char_uppercase(current); } // ranges taken from https://en.wikipedia.org/wiki/Plane_(Unicode) // if your language is not well supported, consider helping improve // the unicode support in Godot. bool separatable = (current >= 0x2E08 && current <= 0x9FFF) || // CJK scripts and symbols. (current >= 0xAC00 && current <= 0xD7FF) || // Hangul Syllables and Hangul Jamo Extended-B. (current >= 0xF900 && current <= 0xFAFF) || // CJK Compatibility Ideographs. (current >= 0xFE30 && current <= 0xFE4F) || // CJK Compatibility Forms. (current >= 0xFF65 && current <= 0xFF9F) || // Halfwidth forms of katakana (current >= 0xFFA0 && current <= 0xFFDC) || // Halfwidth forms of compatibility jamo characters for Hangul (current >= 0x20000 && current <= 0x2FA1F) || // CJK Unified Ideographs Extension B ~ F and CJK Compatibility Ideographs Supplement. (current >= 0x30000 && current <= 0x3134F); // CJK Unified Ideographs Extension G. bool insert_newline = false; real_t char_width = 0; if (current < 33) { if (current_word_size > 0) { WordList *wc = memnew(WordList); if (root) { last->next = wc; } else { root = wc; } last = wc; wc->pixel_width = current_word_size - horizontal_spacing; // remove last horizontal_spacing wc->char_pos = word_pos; wc->word_len = i - word_pos; wc->line = cache.line_count - 1; wc->line_pos = line_pos - wc->word_len; wc->space_count = space_count; current_word_size = 0; space_count = 0; } else if ((i == xl_text.length() || current == '\n') && last != nullptr && space_count != 0) { //in case there are trailing white spaces we add a placeholder word cache with just the spaces WordList *wc = memnew(WordList); if (root) { last->next = wc; } else { root = wc; } last = wc; wc->pixel_width = 0; wc->char_pos = 0; wc->word_len = 0; wc->space_count = space_count; current_word_size = 0; space_count = 0; } if (current == '\n') { insert_newline = true; } else if (current != ' ') { cache.total_char_cache++; } line_pos++; if (i < label_text.length() && label_text[i] == ' ') { if (line_width > 0 || last == nullptr || last->char_pos != WordList::CHAR_WRAPLINE) { space_count++; line_width += space_width; } else { space_count = 0; } } } else { // latin characters if (current_word_size == 0) { word_pos = i; } char_width = font->get_char_size(current, label_text[i + 1]).width + horizontal_spacing; current_word_size += char_width; line_width += char_width; line_pos++; cache.total_char_cache++; // allow autowrap to cut words when they exceed line width if (autowrap && (current_word_size > word_cache.width)) { separatable = true; } } if ((autowrap && (line_width - horizontal_spacing >= word_cache.width) && ((last && last->char_pos >= 0) || separatable)) || insert_newline) { if (separatable) { if (current_word_size > 0) { WordList *wc = memnew(WordList); if (root) { last->next = wc; } else { root = wc; } last = wc; wc->pixel_width = current_word_size - char_width - horizontal_spacing; wc->char_pos = word_pos; wc->word_len = i - word_pos; wc->line = cache.line_count - 1; wc->line_pos = line_pos - wc->word_len; wc->space_count = space_count; current_word_size = char_width; word_pos = i; } } WordList *wc = memnew(WordList); if (root) { last->next = wc; } else { root = wc; } last = wc; wc->pixel_width = 0; wc->char_pos = insert_newline ? WordList::CHAR_NEWLINE : WordList::CHAR_WRAPLINE; wc->line = cache.line_count - 1; cache.line_count++; line_width = current_word_size; line_pos = 0; space_count = 0; } } cache.words = root; return cache; } int Label::get_line_size(const WordCache &cache, int line) const { int line_size = 0; WordList *wc = cache.words; while (wc && wc->line != line) wc = wc->next; while (wc && wc->char_pos >= 0) { line_size += wc->space_count + wc->word_len; // including spaces wc = wc->next; } return line_size; } void Label::regenerate_word_cache() { Ref<Font> font = get_font("font"); _RemoveCacheList(word_cache.words); word_cache = calculate_word_cache(font, xl_text); if (!autowrap) { word_cache.minsize.width = word_cache.width; } const int line_spacing = get_constant("line_spacing"); if (max_lines_visible > 0 && word_cache.line_count > max_lines_visible) { word_cache.minsize.height = (font->get_height() * max_lines_visible) + (line_spacing * (max_lines_visible - 1)); } else { word_cache.minsize.height = (font->get_height() * word_cache.line_count) + (line_spacing * (word_cache.line_count - 1)); } _RemoveCacheList(transition_text.word_cache.words); transition_text.word_cache = calculate_word_cache(font, transition_text.xl_text); if (!autowrap || !clip) { //helps speed up some labels that may change a lot, as no resizing is requested. Do not change. minimum_size_changed(); } word_cache_dirty = false; _cache_changed = true; } void Label::_clear_pending_animations() { // reset animation text = transition_text.text; transition_text.text = ""; xl_text = transition_text.xl_text; transition_text.xl_text = ""; // swap caches: _RemoveCacheList(word_cache.words); word_cache = transition_text.word_cache; transition_text.word_cache = WordCache(); } void Label::set_align(Align p_align) { ERR_FAIL_INDEX(p_align, AlignCount); align = p_align; update(); } Label::Align Label::get_align() const { return align; } void Label::set_valign(VAlign p_align) { ERR_FAIL_INDEX(p_align, VAlignCount); valign = p_align; update(); } Label::VAlign Label::get_valign() const { return valign; } void Label::set_text(const String &p_string) { if (text == p_string) { return; } if (is_transition_enabled()) { if (is_transition_active()) _clear_pending_animations(); // finish now current animation transition_text.text = p_string; transition_text.xl_text = tr(p_string); } else { text = p_string; xl_text = tr(p_string); } if (percent_visible < 1) { visible_chars = get_total_character_count() * percent_visible; } word_cache_dirty = true; update(); } void Label::set_clip_text(bool p_clip) { clip = p_clip; update(); minimum_size_changed(); } bool Label::is_clipping_text() const { return clip; } String Label::get_text() const { return text; } void Label::set_visible_characters(int p_amount) { visible_chars = p_amount; if (get_total_character_count() > 0) { percent_visible = (float)p_amount / (float)word_cache.total_char_cache; } _change_notify("percent_visible"); update(); } int Label::get_visible_characters() const { return visible_chars; } void Label::set_percent_visible(float p_percent) { if (p_percent < 0 || p_percent >= 1) { visible_chars = -1; percent_visible = 1; } else { visible_chars = get_total_character_count() * p_percent; percent_visible = p_percent; } _change_notify("visible_chars"); update(); } float Label::get_percent_visible() const { return percent_visible; } void Label::set_lines_skipped(int p_lines) { ERR_FAIL_COND(p_lines < 0); lines_skipped = p_lines; update(); } int Label::get_lines_skipped() const { return lines_skipped; } void Label::set_max_lines_visible(int p_lines) { max_lines_visible = p_lines; update(); } int Label::get_max_lines_visible() const { return max_lines_visible; } int Label::get_total_character_count() const { if (word_cache_dirty) { const_cast<Label *>(this)->regenerate_word_cache(); } return word_cache.total_char_cache; } void Label::set_horizontal_spacing(float p_offset) { if (horizontal_spacing != p_offset) { horizontal_spacing = p_offset; word_cache_dirty = true; update(); } } float Label::get_horizontal_spacing() const { return horizontal_spacing; } void Label::set_vertical_spacing(float p_offset) { if (vertical_spacing != p_offset) { vertical_spacing = p_offset; word_cache_dirty = true; update(); } } float Label::get_vertical_spacing() const { return vertical_spacing; } void Label::set_transition_duration(float p_duration) { if (p_duration != transition_duration) { transition_duration = p_duration; update(); } } float Label::get_transition_duration() const { return transition_duration; } void Label::set_transition_effect(TransitionEffect p_effect) { ERR_FAIL_INDEX(p_effect, TRANSITIONEFFECT_COUNT); if (p_effect != transition_effect) { transition_effect = p_effect; _transition_controller = AnimationControllerFactory(p_effect); if (p_effect == TRANSITIONEFFECT_NONE) { set_process_internal(false); _clear_pending_animations(); } else { set_process_internal(true); _transition_dirty = true; } update(); } } Label::TransitionEffect Label::get_transition_effect() const { return transition_effect; } void Label::set_transition_ease(TransitionEase p_ease) { if (p_ease != transition_ease) { transition_ease = p_ease; update(); } } Label::TransitionEase Label::get_transition_ease() const { return transition_ease; } bool Label::is_transition_active() const { return !_transition_controller->is_done(); } bool Label::is_transition_enabled() const { return transition_effect != TRANSITIONEFFECT_NONE; } void Label::_bind_methods() { ClassDB::bind_method(D_METHOD("set_align", "align"), &Label::set_align); ClassDB::bind_method(D_METHOD("get_align"), &Label::get_align); ClassDB::bind_method(D_METHOD("set_valign", "valign"), &Label::set_valign); ClassDB::bind_method(D_METHOD("get_valign"), &Label::get_valign); ClassDB::bind_method(D_METHOD("set_text", "text"), &Label::set_text); ClassDB::bind_method(D_METHOD("get_text"), &Label::get_text); ClassDB::bind_method(D_METHOD("set_transition_duration"), &Label::set_transition_duration); ClassDB::bind_method(D_METHOD("get_transition_duration"), &Label::get_transition_duration); ClassDB::bind_method(D_METHOD("set_transition_ease"), &Label::set_transition_ease); ClassDB::bind_method(D_METHOD("get_transition_ease"), &Label::get_transition_ease); ClassDB::bind_method(D_METHOD("set_transition_effect"), &Label::set_transition_effect); ClassDB::bind_method(D_METHOD("get_transition_effect"), &Label::get_transition_effect); ClassDB::bind_method(D_METHOD("is_transition_active"), &Label::is_transition_active); ClassDB::bind_method(D_METHOD("set_autowrap", "enable"), &Label::set_autowrap); ClassDB::bind_method(D_METHOD("has_autowrap"), &Label::has_autowrap); ClassDB::bind_method(D_METHOD("set_clip_text", "enable"), &Label::set_clip_text); ClassDB::bind_method(D_METHOD("is_clipping_text"), &Label::is_clipping_text); ClassDB::bind_method(D_METHOD("set_uppercase", "enable"), &Label::set_uppercase); ClassDB::bind_method(D_METHOD("is_uppercase"), &Label::is_uppercase); ClassDB::bind_method(D_METHOD("set_horizontal_spacing", "px"), &Label::set_horizontal_spacing); ClassDB::bind_method(D_METHOD("get_horizontal_spacing"), &Label::get_horizontal_spacing); ClassDB::bind_method(D_METHOD("set_vertical_spacing", "px"), &Label::set_vertical_spacing); ClassDB::bind_method(D_METHOD("get_vertical_spacing"), &Label::get_vertical_spacing); ClassDB::bind_method(D_METHOD("get_line_height"), &Label::get_line_height); ClassDB::bind_method(D_METHOD("get_line_count"), &Label::get_line_count); ClassDB::bind_method(D_METHOD("get_visible_line_count"), &Label::get_visible_line_count); ClassDB::bind_method(D_METHOD("get_total_character_count"), &Label::get_total_character_count); ClassDB::bind_method(D_METHOD("set_visible_characters", "amount"), &Label::set_visible_characters); ClassDB::bind_method(D_METHOD("get_visible_characters"), &Label::get_visible_characters); ClassDB::bind_method(D_METHOD("set_percent_visible", "percent_visible"), &Label::set_percent_visible); ClassDB::bind_method(D_METHOD("get_percent_visible"), &Label::get_percent_visible); ClassDB::bind_method(D_METHOD("set_lines_skipped", "lines_skipped"), &Label::set_lines_skipped); ClassDB::bind_method(D_METHOD("get_lines_skipped"), &Label::get_lines_skipped); ClassDB::bind_method(D_METHOD("set_max_lines_visible", "lines_visible"), &Label::set_max_lines_visible); ClassDB::bind_method(D_METHOD("get_max_lines_visible"), &Label::get_max_lines_visible); BIND_ENUM_CONSTANT(ALIGN_LEFT); BIND_ENUM_CONSTANT(ALIGN_CENTER); BIND_ENUM_CONSTANT(ALIGN_RIGHT); BIND_ENUM_CONSTANT(ALIGN_FILL); BIND_ENUM_CONSTANT(VALIGN_TOP); BIND_ENUM_CONSTANT(VALIGN_CENTER); BIND_ENUM_CONSTANT(VALIGN_BOTTOM); BIND_ENUM_CONSTANT(VALIGN_FILL); BIND_ENUM_CONSTANT(TRANSITIONEASE_NONE); BIND_ENUM_CONSTANT(TRANSITIONEASE_LINEAR_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_LINEAR_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_LINEAR_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_SINE_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_SINE_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_SINE_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_CIRC_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_CIRC_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_CIRC_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_CUBIC_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_CUBIC_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_CUBIC_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_QUAD_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_QUAD_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_QUAD_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_EXPO_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_EXPO_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_EXPO_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_BACK_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_BACK_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_BACK_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_BOUNCE_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_BOUNCE_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_BOUNCE_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_ELASTIC_IN); BIND_ENUM_CONSTANT(TRANSITIONEASE_ELASTIC_OUT); BIND_ENUM_CONSTANT(TRANSITIONEASE_ELASTIC_INOUT); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_NONE); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_UP); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_DOWN); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_UP_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_DOWN_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_WHEEL_UP); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_WHEEL_DOWN); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_WHEEL_UP_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_WHEEL_DOWN_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_REVEAL_UP); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_REVEAL_DOWN); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_REVEAL_UP_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_REVEAL_DOWN_NEW); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_ROTATE_V); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_ROTATE_H); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_ROTATE_V_SEQ); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_ROTATE_H_SEQ); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_UP_SEQ); BIND_ENUM_CONSTANT(TRANSITIONEFFECT_SLIDE_DOWN_SEQ); ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text"); ADD_PROPERTY(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align"); ADD_PROPERTY(PropertyInfo(Variant::INT, "valign", PROPERTY_HINT_ENUM, "Top,Center,Bottom,Fill"), "set_valign", "get_valign"); ADD_GROUP("Transition", "transition_"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "transition_duration"), "set_transition_duration", "get_transition_duration"); ADD_PROPERTY(PropertyInfo(Variant::INT, "transition_ease", PROPERTY_HINT_ENUM, EASE_FUNC), "set_transition_ease", "get_transition_ease"); ADD_PROPERTY(PropertyInfo(Variant::INT, "transition_effect", PROPERTY_HINT_ENUM, "None,SlideUp,SlideDown,SlideUpNew,SlideDownNew,WheelUp,WheelDown,WheelUpNew,WheelDownNew,RevelUp,RevelDown,RevelUpNew,RevelDownNew,RotateV,RotateH,RotateVSeq,RotateHSeq,SlideUpSeq,SlideDownSeq"), "set_transition_effect", "get_transition_effect"); ADD_GROUP("", ""); ADD_GROUP("Extra Spacing", "extra_spacing_"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "extra_spacing_horizontal", PROPERTY_HINT_RANGE, "-10,10,0.5"), "set_horizontal_spacing", "get_horizontal_spacing"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "extra_spacing_vertical", PROPERTY_HINT_RANGE, "-10,10,0.5"), "set_vertical_spacing", "get_vertical_spacing"); ADD_GROUP("", ""); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autowrap"), "set_autowrap", "has_autowrap"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "is_clipping_text"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uppercase"), "set_uppercase", "is_uppercase"); ADD_PROPERTY(PropertyInfo(Variant::INT, "visible_characters", PROPERTY_HINT_RANGE, "-1,128000,1", PROPERTY_USAGE_EDITOR), "set_visible_characters", "get_visible_characters"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "percent_visible", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_percent_visible", "get_percent_visible"); ADD_PROPERTY(PropertyInfo(Variant::INT, "lines_skipped", PROPERTY_HINT_RANGE, "0,999,1"), "set_lines_skipped", "get_lines_skipped"); ADD_PROPERTY(PropertyInfo(Variant::INT, "max_lines_visible", PROPERTY_HINT_RANGE, "-1,999,1"), "set_max_lines_visible", "get_max_lines_visible"); } Label::Label(const String &p_text) { align = ALIGN_LEFT; valign = VALIGN_TOP; xl_text = ""; word_cache_dirty = true; autowrap = false; vertical_spacing = 0; horizontal_spacing = 0; set_v_size_flags(0); clip = false; transition_text.xl_text = ""; transition_duration = 1.0; transition_ease = TRANSITIONEASE_NONE; transition_effect = TRANSITIONEFFECT_NONE; _transition_controller = AnimationControllerFactory(TRANSITIONEFFECT_NONE); _transition_dirty = false; _cache_changed = false; set_mouse_filter(MOUSE_FILTER_IGNORE); visible_chars = -1; percent_visible = 1; lines_skipped = 0; max_lines_visible = -1; set_text(p_text); uppercase = false; set_v_size_flags(SIZE_SHRINK_CENTER); } Label::~Label() { _RemoveCacheList(word_cache.words); _RemoveCacheList(transition_text.word_cache.words); }
32.582677
329
0.689917
[ "vector" ]
a52c7c235324d51eb2408230b08f10b03e2ed7e0
677
cpp
C++
src/state.cpp
Ikaguia/idj-pinguim
fd07be94b440057ab2ec9bf80931bc3f2b588cd3
[ "MIT" ]
1
2017-04-03T14:37:36.000Z
2017-04-03T14:37:36.000Z
src/state.cpp
Ikaguia/idj-pinguim
fd07be94b440057ab2ec9bf80931bc3f2b588cd3
[ "MIT" ]
null
null
null
src/state.cpp
Ikaguia/idj-pinguim
fd07be94b440057ab2ec9bf80931bc3f2b588cd3
[ "MIT" ]
null
null
null
#include <state.hpp> State::State():popRequested{false},quitRequested{false}{ } void State::AddObject(GameObject* obj){ objectArray.emplace_back(obj); } bool State::PopRequested(){ return popRequested; } bool State::QuitRequested(){ return quitRequested; } void State::AddSound(string file,int times){ Sound *s = new Sound(file); sounds.push_back(unique_ptr<Sound>(s)); s->Play(times); } void State::UpdateArray(float time){ int i=0; while(i<(int)objectArray.size()){ objectArray[i]->Update(time); if(objectArray[i]->IsDead())objectArray.erase(objectArray.begin() + i); else i++; } } void State::RenderArray(){ for(const auto &i:objectArray)i->Render(); }
19.911765
73
0.70901
[ "render" ]
a52d518c2f143353131934b886a0bb6592f48fdd
1,336
cpp
C++
Codeforces/Round-450-Div2/D.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
Codeforces/Round-450-Div2/D.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
Codeforces/Round-450-Div2/D.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
// DP, Number Theory // 5 // 27-11-2020 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); const int mod = 1e9 + 7; auto add = [&] (int a, int b) { return (a + b) % mod; }; auto sub = [&] (int a, int b) { return (a - b + mod) % mod; }; auto mul = [&] (int a, int b) { return (1LL * a * b) % mod; }; auto modPow = [&] (int a, int b) { int ret = 1; while (b) { if (b & 1) ret = mul(ret, a); a = mul(a, a); b >>= 1; } return ret; }; int x, y; cin >> x >> y; if (y % x) { cout << 0 << '\n'; return (0); } y /= x; map <int, int> dp; function <int(int)> rec = [&] (int x) -> int { if (dp.count(x)) return dp[x]; int ret = modPow(2, x - 1); for (int d = 1; d * d <= x; d++) { if (x % d) continue; if (d != 1) ret = sub(ret, rec(x / d)); if (d * d != x) ret = sub(ret, rec(d)); } return dp[x] = ret; }; cout << rec(y) << '\n'; return (0); }
22.644068
64
0.497754
[ "vector" ]
a53305e65e9c67d5db4ea8eb8e2818a032096bef
15,269
cpp
C++
Source/TPSOnline/Private/Characters/PlayerCharacter.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
2
2022-01-20T19:29:43.000Z
2022-01-26T15:01:32.000Z
Source/TPSOnline/Private/Characters/PlayerCharacter.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
42
2022-01-15T09:20:06.000Z
2022-02-01T19:28:04.000Z
Source/TPSOnline/Private/Characters/PlayerCharacter.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
null
null
null
// Copyright 2022 Danial Kamali. All Rights Reserved. #include "Characters/PlayerCharacter.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" #include "Components/TimelineComponent.h" #include "Components/SlateWrapperTypes.h" #include "GameFramework/CharacterMovementComponent.h" #include "Components/InputComponent.h" #include "Components/HealthComponent.h" #include "Components/StaminaComponent.h" #include "Core/CustomPlayerController.h" #include "Core/CustomPlayerState.h" #include "Core/DeathmatchGameMode.h" #include "Actors/PickupActor.h" #include "Actors/AmmoPickupActor.h" #include "Actors/WeaponPickupActor.h" #include "GameFramework/Controller.h" #include "Interfaces/CharacterAnimationInterface.h" #include "Kismet/GameplayStatics.h" #include "Kismet/KismetMathLibrary.h" #include "Net/UnrealNetwork.h" #include "UI/PlayerHUD.h" APlayerCharacter::APlayerCharacter() { GetMesh()->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Create a camera boom (pulls in towards the player if there is a collision) SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("Camera Boom")); SpringArm->SetupAttachment(RootComponent); SpringArm->SetComponentTickEnabled(false); SpringArm->SocketOffset.Y = 50.0f; SpringArm->ProbeSize = 5.0; SpringArm->bUsePawnControlRotation = true; // Rotate the arm based on the controller SpringArm->bEnableCameraLag = true; // Create a follow camera Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); Camera->SetupAttachment(SpringArm, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation Camera->SetComponentTickEnabled(false); Camera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm AimTimeline = CreateDefaultSubobject<UTimelineComponent>(TEXT("Aim Timeline")); // Initialize variables LookUpPitch = 0.0f; BaseTurnRate = 45.0f; BaseLookUpRate = 45.0f; TimeLineDirection = ETimelineDirection::Forward; bDoOnceCrouch = true; bCharacterAnimationInterface = false; CurrentCamera = Camera; } void APlayerCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty> &OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // Replicate to everyone DOREPLIFETIME(APlayerCharacter, PlayerControllerRef); DOREPLIFETIME(APlayerCharacter, LookUpPitch); } void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &APlayerCharacter::AttemptJump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &APlayerCharacter::StartSprint); PlayerInputComponent->BindAction("Sprint", IE_Released, this, &APlayerCharacter::StopSprint); PlayerInputComponent->BindAction("Crouch", IE_Pressed, this, &APlayerCharacter::ToggleCrouch); PlayerInputComponent->BindAction("Interact", IE_Pressed, this, &APlayerCharacter::Interact); PlayerInputComponent->BindAction("Drop", IE_Pressed, this, &APlayerCharacter::DropCurrentWeapon); PlayerInputComponent->BindAction("Reload", IE_Pressed, this, &APlayerCharacter::ReloadWeapon); PlayerInputComponent->BindAction("Aim", IE_Pressed, this, &APlayerCharacter::StartAim); PlayerInputComponent->BindAction("Aim", IE_Released, this, &APlayerCharacter::StopAim); PlayerInputComponent->BindAction("FireWeapon", IE_Pressed, this, &APlayerCharacter::StartFireWeapon); PlayerInputComponent->BindAction("FireWeapon", IE_Released, this, &APlayerCharacter::StopFireWeapon); PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "Turn" handles devices that provide an absolute delta, such as a mouse. // "TurnRate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &APlayerCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APlayerCharacter::UpdateControllerPitch); PlayerInputComponent->BindAxis("LookUpRate", this, &APlayerCharacter::LookUpAtRate); } void APlayerCharacter::BeginPlay() { Super::BeginPlay(); if (GetLocalRole() == ROLE_AutonomousProxy) { AnimInstance = GetMesh()->GetAnimInstance(); if (AnimInstance && AnimInstance->GetClass()->ImplementsInterface(UCharacterAnimationInterface::StaticClass())) { bCharacterAnimationInterface = true; } UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMin = -80.0f; UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMax = 50.0f; PlayerHUD = Cast<APlayerHUD>(PlayerControllerRef->GetHUD()); if (PlayerHUD) { PlayerHUD->Initialize(); } if (AimFloatCurve) { FOnTimelineFloat AimTimeLineProgress{}; AimTimeLineProgress.BindUFunction(this, FName("AimTimeLineUpdate")); AimTimeline->AddInterpFloat(AimFloatCurve, AimTimeLineProgress, FName("Alpha")); FOnTimelineEvent AimTimelineFinishEvent{}; AimTimelineFinishEvent.BindUFunction(this, FName("AimTimeLineFinished")); AimTimeline->SetTimelineFinishedFunc(AimTimelineFinishEvent); } } } void APlayerCharacter::PossessedBy(AController* NewController) { Super::PossessedBy(NewController); PlayerControllerRef = Cast<APlayerController>(NewController); } void APlayerCharacter::MoveForward(float Value) { if (Controller && Value != 0.0f) { // Zero out pitch and roll, only move on plane, find out which way is forward const FRotator YawRotation(0, Controller->GetControlRotation().Yaw, 0); // Get forward vector const FVector NewDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(NewDirection, Value * MovementScale); } } void APlayerCharacter::MoveRight(float Value) { if (Controller && Value != 0.0f) { // Zero out pitch and roll, only move on plane, find out which way is right const FRotator YawRotation(0, Controller->GetControlRotation().Yaw, 0); // Get right vector const FVector NewDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // Add movement in that direction AddMovementInput(NewDirection, Value * MovementScale); } } void APlayerCharacter::UpdateControllerPitch(float Value) { AddControllerPitchInput(Value); if (Value != 0.0f) { const float NewPitch = UKismetMathLibrary::NormalizedDeltaRotator(GetControlRotation(), GetActorRotation()).Pitch; ServerUpdateLookUp(NewPitch); } } void APlayerCharacter::TurnAtRate(float Rate) { // Calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void APlayerCharacter::LookUpAtRate(float Rate) { // Calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); if (Rate != 0.0f) { const float NewPitch = UKismetMathLibrary::NormalizedDeltaRotator(GetControlRotation(), GetActorRotation()).Pitch; ServerUpdateLookUp(NewPitch); } } void APlayerCharacter::ServerUpdateLookUp_Implementation(float Pitch) { LookUpPitch = Pitch; } void APlayerCharacter::AttemptJump() { if (GetStaminaComponent()->CurrentStamina > 0.0f && GetCharacterMovement()->IsFalling() == false) { GetStaminaComponent()->ServerJumpDrainStamina(); Jump(); } } void APlayerCharacter::StartSprint() { if (bDoOnceStopped) { GetStaminaComponent()->ServerStartStaminaDrain(EMovementState::Sprint); } ServerChangeMovementState(EMovementState::Sprint); } void APlayerCharacter::StopSprint() { ServerChangeMovementState(EMovementState::Walk); } void APlayerCharacter::ToggleCrouch() { if (bDoOnceCrouch) { if (MovementState != EMovementState::Crouch) { ServerChangeMovementState(EMovementState::Crouch); } else { ServerChangeMovementState(EMovementState::Walk); } bDoOnceCrouch = false; // Resetting crouch by a delay to stop the player from spamming the crouch. FTimerHandle TimerHandle; GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &APlayerCharacter::ResetCrouch, 0.3f); } } void APlayerCharacter::ResetCrouch() { bDoOnceCrouch = true; } void APlayerCharacter::Interact() { APickupActor* Pickup = FindPickup(); if (Pickup) { switch (Pickup->PickupType) { case 0: // Weapon ServerInteractWithWeapon(); break; case 1: // Ammo { AAmmoPickupActor* AmmoPickup = Cast<AAmmoPickupActor>(Pickup); if (AmmoPickup) { switch (AmmoPickup->AmmoType) { case 0: // 5.56 if (PlayerStateRef->FiveFiveSixAmmo < 120) { ServerInteractWithAmmo(); } break; case 1: // 7.62 if (PlayerStateRef->SevenSixTwoAmmo < 120) { ServerInteractWithAmmo(); } break; case 2: // .45 if (PlayerStateRef->FortyFiveAmmo < 90) { ServerInteractWithAmmo(); } break; case 3: // 40 mm HE Grenade if (PlayerStateRef->HighExplosive < 90) { ServerInteractWithAmmo(); } break; } } } break; case 2: // Health, If Current Health is lower than Max Health if (GetHealthComponent()->CurrentHealth < GetHealthComponent()->MaxHealth) { ServerInteractWithHealth(); } break; } } } void APlayerCharacter::StartAim() { if (CurrentWeapon && CurrentWeaponSlot != EWeaponToDo::NoWeapon) { ServerUpdateAimState(true); UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMin = -35.0f; UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMax = 55.0f; AimTimeline->Play(); TimeLineDirection = ETimelineDirection::Forward; } } void APlayerCharacter::StopAim() { ServerUpdateAimState(false); AimTimeline->Reverse(); TimeLineDirection = ETimelineDirection::Backward; if (PlayerHUD) { PlayerHUD->SetCrosshairVisibility(ESlateVisibility::Hidden); } } void APlayerCharacter::AimTimeLineUpdate(float Value) { if (TimeLineDirection == ETimelineDirection::Forward) { Camera->SetFieldOfView(FMath::Lerp(Camera->FieldOfView, 50.0f, Value)); SpringArm->SocketOffset.Y = FMath::Lerp(SpringArm->SocketOffset.Y, 50.0f, Value); SpringArm->TargetArmLength = FMath::Lerp(SpringArm->TargetArmLength, 150.0f, Value); } else { Camera->SetFieldOfView(FMath::Lerp(90.0f, Camera->FieldOfView, Value)); SpringArm->SocketOffset.Y = FMath::Lerp(50.0f, SpringArm->SocketOffset.Y, Value); SpringArm->TargetArmLength = FMath::Lerp(300.0f, SpringArm->TargetArmLength, Value); } } void APlayerCharacter::AimTimeLineFinished() { if (TimeLineDirection == ETimelineDirection::Forward) { if (PlayerHUD) { PlayerHUD->SetCrosshairVisibility(ESlateVisibility::HitTestInvisible); } } else { UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMin = -80.0f; UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->ViewPitchMax = 50.0f; } } void APlayerCharacter::StartFireWeapon() { if (bCanFireWeapon && CanFireWeapon()) { AddRecoil(); if (CurrentWeapon->bIsAutomatic) { GetWorld()->GetTimerManager().SetTimer(RecoilTimer, this, &APlayerCharacter::AddRecoil, CurrentWeapon->TimeBetweenShots, true); } ServerStartFireWeapon(); } } void APlayerCharacter::StopFireWeapon() { if (CurrentWeapon && CurrentWeaponSlot != EWeaponToDo::NoWeapon) { GetWorld()->GetTimerManager().ClearTimer(RecoilTimer); ServerStopFireWeapon(); } } void APlayerCharacter::AddRecoil() { if (CanFireWeapon()) { if (bIsAiming) { AddControllerPitchInput(CurrentWeapon->RecoilData.ControllerPitch); const float NewPitch = UKismetMathLibrary::NormalizedDeltaRotator(GetControlRotation(), GetActorRotation()).Pitch; ServerUpdateLookUp(NewPitch); } PlayerControllerRef->ClientStartCameraShake(CurrentWeapon->Effects.CameraShake); if (bCharacterAnimationInterface) { ICharacterAnimationInterface::Execute_AddRecoil(AnimInstance, CurrentWeapon->RecoilData.RotationIntensity, CurrentWeapon->RecoilData.ControlTime); } if (PlayerHUD) { PlayerHUD->AddCrosshairRecoil(CurrentWeapon->RecoilData.CrosshairRecoil, CurrentWeapon->RecoilData.ControlTime); } } else { GetWorld()->GetTimerManager().ClearTimer(RecoilTimer); } } void APlayerCharacter::ReloadWeapon() { if (bDoOnceReload && CanReloadWeapon()) { ServerReloadWeapon(); } } void APlayerCharacter::DropCurrentWeapon() { if (CurrentWeapon && CurrentWeaponSlot != EWeaponToDo::NoWeapon) { switch (CurrentWeaponSlot) { case 0: // No Weapon = Nothing to drop break; case 1: // Primary Weapon ServerDropWeapon(EWeaponToDo::Primary); break; case 2: // Secondary Weapon ServerDropWeapon(EWeaponToDo::Secondary); break; case 3: // Sidearm Weapon ServerDropWeapon(EWeaponToDo::Sidearm); break; } } } void APlayerCharacter::OnRep_CurrentWeapon() { if (GetLocalRole() == ROLE_AutonomousProxy && PlayerHUD) { if (CurrentWeapon) { PlayerHUD->SetWeaponInfoVisibility(ESlateVisibility::HitTestInvisible); PlayerHUD->UpdateWeaponInfo(CurrentWeapon->WeaponName, FindCurrentAmmo()); PlayerHUD->UpdateCurrentMagAmmo(CurrentWeapon->CurrentMagazineAmmo); } else { PlayerHUD->SetWeaponInfoVisibility(ESlateVisibility::Hidden); } } } int32 APlayerCharacter::FindCurrentAmmo() const { if (PlayerStateRef) { switch (CurrentWeapon->AmmoType) { case 0: // 5.56 mm return PlayerStateRef->FiveFiveSixAmmo; case 1: // 7.62 mm return PlayerStateRef->SevenSixTwoAmmo; case 2: // .45 ACP return PlayerStateRef->FortyFiveAmmo; case 3: // 40 mm HE Grenade return PlayerStateRef->HighExplosive; } } return 0; } void APlayerCharacter::ClientUpdateHealth_Implementation(float NewHealth) { if (GetLocalRole() < ROLE_Authority && PlayerHUD) { PlayerHUD->UpdateHealth(NewHealth); } } void APlayerCharacter::ClientUpdateStamina_Implementation(float NewStamina) { if (GetLocalRole() < ROLE_Authority && PlayerHUD) { PlayerHUD->UpdateStamina(NewStamina); } } void APlayerCharacter::Destroyed() { if (GetLocalRole() == ROLE_Authority) { // In case of player leave the session without getting killed if (bDoOnceDeath && PlayerStateRef) { bDoOnceDeath = false; PlayerStateRef->ServerPlayerDied(); } // Get player controller reference before destroying the player AController* RespawnControllerRef = GetController(); Super::Destroyed(); // Get the World and GameMode in the world to invoke its restart player function. ADeathmatchGameMode* GameMode = Cast<ADeathmatchGameMode>(GetWorld()->GetAuthGameMode()); if (GameMode) { GameMode->ServerStartRespawn(RespawnControllerRef); } } }
28.381041
173
0.751523
[ "vector" ]
a5509000bfc3dee75022f42e05d880de64ee0a7f
1,879
cpp
C++
src/Path.cpp
PSSTools/psslangserver
e3b44118c5ed698f44375bff40d2c4118ca45bbe
[ "Apache-2.0" ]
null
null
null
src/Path.cpp
PSSTools/psslangserver
e3b44118c5ed698f44375bff40d2c4118ca45bbe
[ "Apache-2.0" ]
null
null
null
src/Path.cpp
PSSTools/psslangserver
e3b44118c5ed698f44375bff40d2c4118ca45bbe
[ "Apache-2.0" ]
null
null
null
/* * Path.cpp * * Created on: Oct 9, 2020 * Author: ballance */ #include "Path.h" #ifndef _WIN32 #include <dirent.h> #else #include <windows.h> #endif #include <stdio.h> #include <string.h> #include <sys/stat.h> namespace pls { Path::Path() { // TODO Auto-generated constructor stub } Path::~Path() { // TODO Auto-generated destructor stub } bool Path::is_dir(const std::string &path) { struct stat st; int ret = stat(path.c_str(), &st); return (ret == 0 && ((st.st_mode & S_IFMT) == S_IFDIR)); } bool Path::is_file(const std::string &path) { struct stat st; return (stat(path.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFREG)); } std::string Path::ext(const std::string &path) { int32_t idx; if ((idx=path.rfind('.')) != std::string::npos && idx != 0) { return path.substr(idx); } else { return ""; } } std::string Path::join(const std::string &root, const std::string &leaf) { return root + "/" + leaf; } std::vector<std::string> Path::list(const std::string &path) { std::vector<std::string> ret; #ifndef _WIN32 DIR *d; struct dirent *dir; d = opendir(path.c_str()); if (d) { while ((dir = readdir(d)) != NULL) { if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")) { ret.push_back(dir->d_name); } } closedir(d); } #else WIN32_FIND_DATA FindFileData; std::string search_p = path + "/*"; fprintf(stdout, "Path::list: %s\n", search_p.c_str()); HANDLE hFind = FindFirstFile(search_p.c_str(), &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { do { if (strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..")) { fprintf(stdout, "Add path: %s\n", FindFileData.cFileName); ret.push_back(FindFileData.cFileName); } } while (FindNextFile(hFind, &FindFileData)); } else { fprintf(stdout, "hFind=INVALID_HANDLE\n"); } #endif return ret; } } /* namespace pls */
21.352273
85
0.62959
[ "vector" ]
a223f0a68bd2e89a002ce5e041370d4d1b52f653
5,101
hpp
C++
include/utility.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
7
2016-02-16T13:24:00.000Z
2018-09-24T09:02:38.000Z
include/utility.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
null
null
null
include/utility.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
2
2016-02-16T13:06:23.000Z
2018-10-15T04:27:42.000Z
/* utility %{Cpp:License:ClassName} - Yann BOUCHER (yann) 26/01/2016 ** ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** Version 2, December 2004 ** ** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> ** ** Everyone is permitted to copy and distribute verbatim or modified ** copies of this license document, and changing it is allowed as long ** as the name is changed. ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ** ** 0. You just DO WHAT THE FUCK YOU WANT TO. */ #ifndef UTILITY_HPP #define UTILITY_HPP #include <cctype> #include <climits> #include <algorithm> #include <chrono> #include <stdexcept> #include <string> #include <thread> #include "common.hpp" #include "cpustate.hpp" namespace i8080 { struct State; template <typename Function> inline void executeForDuration(std::chrono::duration<double> time, Function&& func) { auto time1 = std::chrono::high_resolution_clock::now(); func(); auto time2 = std::chrono::high_resolution_clock::now(); auto delta = time2 - time1; if (delta < time) { std::this_thread::sleep_for(time - delta); } } template <typename T> inline T wrap(T kX, T kLowerBound, T kUpperBound) { T range_size = kUpperBound - kLowerBound + 1; if (kX < kLowerBound) kX += range_size * ((kLowerBound - kX) / range_size + 1); return kLowerBound + (kX - kLowerBound) % range_size; } inline bool parity(byte input) { input ^= input >> 4; input &= 0xF; return !((0x6996 >> input) & 1); } inline bool getBit(byte input, size_t pos) { return (input >> pos) & 1; } inline void unsetBit(byte& input, size_t pos) { input &= ~(1 << pos); } inline void setBit(byte& input, size_t pos, bool val = true) { if (val) { input |= 1 << pos; } else { unsetBit(input, pos); } } inline void toggleBit(byte& input, size_t pos) { input ^= 1 << pos; } inline bool getFlagS(byte flags) { return getBit(flags, 7); } inline void setFlagS(byte& flags, bool val) { setBit(flags, 7, val); } inline bool getFlagZ(byte flags) { return getBit(flags, 6); } inline void setFlagZ(byte& flags, bool val) { setBit(flags, 6, val); } inline bool getFlagAC(byte flags) { return getBit(flags, 4); } inline void setFlagAC(byte& flags, bool val) { setBit(flags, 4, val); } inline bool getFlagP(byte flags) { return getBit(flags, 2); } inline void setFlagP(byte& flags, bool val) { setBit(flags, 2, val); } inline bool getFlagC(byte flags) { return getBit(flags, 0); } inline void setFlagC(byte& flags, bool val) { setBit(flags, 0, val); } inline bool sign(byte val) { return getBit(val, 7); } void checkACarry(byte& flags, unsigned int val, const State& state); inline void checkSign(byte& flags, unsigned int val) { setFlagS(flags, sign(val & 0xFF)); } inline void checkZero(byte& flags, unsigned int val) { setFlagZ(flags, val == 0); } inline void checkCarry(byte& flags, unsigned int val) { setFlagC(flags, (val & 0x100) != 0); } inline void checkParity(byte& flags, unsigned int val) { setFlagP(flags, parity(val & 0xFF)); } inline byte rotl(byte x, unsigned int n) { const decltype(n) mask = (CHAR_BIT*sizeof(x)-1); assert (n<=mask && "rotate by more than type width"); n &= mask; // avoid undef behaviour with NDEBUG. 0 overhead for most types / compilers return (x<<n) | (x>>( (-n)&mask )); } inline byte rotr(byte x, unsigned int n) { const decltype(n) mask = (CHAR_BIT*sizeof(x)-1); assert (n<=mask && "rotate by more than type width"); n &= mask; // avoid undef behaviour with NDEBUG. 0 overhead for most types / compilers return (x>>n) | (x<<( (-n)&mask )); } inline word invertWord(word in) { byte h = (in & 0xFF00) >> 8; byte l = in & 0xFF; return l << 8 | h; } namespace Opcode { byte fetchByte(State& state); word fetchWord(State& state); byte readReg(unsigned int index, const State& state); void writeReg(unsigned int index, byte val, State& state); inline byte getDdd(byte opcode) { byte result { 0 }; setBit(result, 0, getBit(opcode, 3)); setBit(result, 1, getBit(opcode, 4)); setBit(result, 2, getBit(opcode, 5)); return result; } inline byte getAaa(byte opcode) { return getDdd(opcode); } inline byte getSss(byte opcode) { byte result { 0 }; setBit(result, 0, getBit(opcode, 0)); setBit(result, 1, getBit(opcode, 1)); setBit(result, 2, getBit(opcode, 2)); return result; } } // namespace Opcode struct emu_error : std::runtime_error { using std::runtime_error::runtime_error; }; [[noreturn]] inline void error(const std::string& why) { throw emu_error(why); } inline std::string toUpper(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); return str; } inline std::string toLower(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } } // namepsace i8080 #endif // UTILITY_HPP
20.082677
90
0.647716
[ "transform" ]
a2245d61139e11bca8d5f724d5a2021d7c144dfc
1,067
cpp
C++
oo_file/write_files.cpp
Johk3/Cpp_Examples
4945df0740507d82c48ad884911ab67b4697d60c
[ "Unlicense" ]
null
null
null
oo_file/write_files.cpp
Johk3/Cpp_Examples
4945df0740507d82c48ad884911ab67b4697d60c
[ "Unlicense" ]
null
null
null
oo_file/write_files.cpp
Johk3/Cpp_Examples
4945df0740507d82c48ad884911ab67b4697d60c
[ "Unlicense" ]
null
null
null
#include <stdio.h> #include <cstdlib> #include <iostream> #include <string> #include <numeric> #include <sstream> #include <vector> #include <cmath> #include <cfenv> #include <algorithm> #include <fstream> int main(int argc, char **argv){ std::ofstream writeToFile; std::ifstream readFromFile; std::string txtToWrite = ""; std::string txtFromFile = ""; int lineNumbers; writeToFile.open("test.txt", std::ios_base::out | std::ios_base::trunc); if(writeToFile.is_open()){ writeToFile << "Story of a pepega Bob\n"; txtToWrite = "Bob is a pepega"; writeToFile << txtToWrite; writeToFile.close(); } readFromFile.open("test.txt", std::ios_base::in); if(readFromFile.is_open()){ while(readFromFile.good()){ getline(readFromFile, txtFromFile); lineNumbers = txtFromFile.length(); std::cout << txtFromFile << "\n"; std::cout << "Line length = " << lineNumbers << "\n"; } readFromFile.close(); } return 0; }
25.404762
76
0.597938
[ "vector" ]
a228ddcae754b59a87ccdc32268d26270b93f5a3
1,729
cpp
C++
HackerRank/FavoriteSequence.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
HackerRank/FavoriteSequence.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
HackerRank/FavoriteSequence.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned long long uInt; typedef unsigned uint; const int MAXN = 1000005; int T, N; set<int> seen; vector<int> G[MAXN]; int deg[MAXN]; vector<int> func(void) { vector<int> ans; priority_queue<int, vector<int>, greater<int> > q; for (auto it : seen) { if (deg[it] == 0) { q.push(it); } sort(G[it].begin(), G[it].end()); } while (!q.empty()) { int now = q.top(); q.pop(); ans.push_back(now); for (int i = 0; i < (int) G[now].size(); i++) { int next = G[now][i]; deg[next] -= 1; if (deg[next] == 0) { q.push(next); } } } return ans; } int main(void) { cin >> T; vector<int> curr; for (int i = 0; i < T; i++) { cin >> N; int now, last = -1; for (int j = 0; j < N; j++) { cin >> now; seen.insert(now); if (j > 0) { G[last].push_back(now); deg[now] += 1; } last = now; } } vector<int> ans = func(); for (int i = 0; i < (int) ans.size(); i++) { cout << ans[i] << " "; } cout << "\n"; return 0; }
18.793478
67
0.421631
[ "vector" ]
a2327c863e1892472796f719f7921fdc4e8fc6aa
441
cpp
C++
leetcode/cpp/162.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
null
null
null
leetcode/cpp/162.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
null
null
null
leetcode/cpp/162.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
2
2020-09-29T21:59:43.000Z
2021-06-22T13:24:04.000Z
/* * Binary Search * O(lgn) * */ class Solution { public: int findPeakElement(vector<int>& nums) { int l = 0, r = nums.size()-1; while(l < r) { int mid = l + (r-l) / 2; if(nums[mid] > nums[mid+1]) { r = mid; } else { l = mid+1; } } return r; } }; // Conclusion: // How to choose between mid and mid+1(or mid-1) ? //
17.64
50
0.405896
[ "vector" ]
a23a4f7fec8083ffa53489e5a68e653b3d749bb4
4,137
cpp
C++
aws-cpp-sdk-databrew/source/model/SessionStatus.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-databrew/source/model/SessionStatus.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-databrew/source/model/SessionStatus.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/databrew/model/SessionStatus.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace GlueDataBrew { namespace Model { namespace SessionStatusMapper { static const int ASSIGNED_HASH = HashingUtils::HashString("ASSIGNED"); static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int INITIALIZING_HASH = HashingUtils::HashString("INITIALIZING"); static const int PROVISIONING_HASH = HashingUtils::HashString("PROVISIONING"); static const int READY_HASH = HashingUtils::HashString("READY"); static const int RECYCLING_HASH = HashingUtils::HashString("RECYCLING"); static const int ROTATING_HASH = HashingUtils::HashString("ROTATING"); static const int TERMINATED_HASH = HashingUtils::HashString("TERMINATED"); static const int TERMINATING_HASH = HashingUtils::HashString("TERMINATING"); static const int UPDATING_HASH = HashingUtils::HashString("UPDATING"); SessionStatus GetSessionStatusForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == ASSIGNED_HASH) { return SessionStatus::ASSIGNED; } else if (hashCode == FAILED_HASH) { return SessionStatus::FAILED; } else if (hashCode == INITIALIZING_HASH) { return SessionStatus::INITIALIZING; } else if (hashCode == PROVISIONING_HASH) { return SessionStatus::PROVISIONING; } else if (hashCode == READY_HASH) { return SessionStatus::READY; } else if (hashCode == RECYCLING_HASH) { return SessionStatus::RECYCLING; } else if (hashCode == ROTATING_HASH) { return SessionStatus::ROTATING; } else if (hashCode == TERMINATED_HASH) { return SessionStatus::TERMINATED; } else if (hashCode == TERMINATING_HASH) { return SessionStatus::TERMINATING; } else if (hashCode == UPDATING_HASH) { return SessionStatus::UPDATING; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<SessionStatus>(hashCode); } return SessionStatus::NOT_SET; } Aws::String GetNameForSessionStatus(SessionStatus enumValue) { switch(enumValue) { case SessionStatus::ASSIGNED: return "ASSIGNED"; case SessionStatus::FAILED: return "FAILED"; case SessionStatus::INITIALIZING: return "INITIALIZING"; case SessionStatus::PROVISIONING: return "PROVISIONING"; case SessionStatus::READY: return "READY"; case SessionStatus::RECYCLING: return "RECYCLING"; case SessionStatus::ROTATING: return "ROTATING"; case SessionStatus::TERMINATED: return "TERMINATED"; case SessionStatus::TERMINATING: return "TERMINATING"; case SessionStatus::UPDATING: return "UPDATING"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace SessionStatusMapper } // namespace Model } // namespace GlueDataBrew } // namespace Aws
32.574803
92
0.595842
[ "model" ]