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
8d515517290f7dbc2cf1c2905846821f47b690d6
1,061
cpp
C++
Source/Rendering/RNRenderer.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
13
2020-08-08T11:57:05.000Z
2022-03-10T17:29:19.000Z
Source/Rendering/RNRenderer.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
1
2022-03-10T17:35:28.000Z
2022-03-10T18:21:57.000Z
Source/Rendering/RNRenderer.cpp
uberpixel/Rayne
94f601561aedfc3200e67ff9522f64fbc5ca4d8c
[ "MIT" ]
3
2020-08-08T14:22:34.000Z
2021-05-15T21:12:17.000Z
// // RNRenderer.cpp // Rayne // // Copyright 2015 by Überpixel. All rights reserved. // Unauthorized use is punishable by torture, mutilation, and vivisection. // #include "RNRenderer.h" #include "../Base/RNSettings.h" namespace RN { RNDefineMeta(Renderer, Object) RNExceptionImp(ShaderCompilation) static Renderer *_activeRenderer = nullptr; Renderer::Renderer(RendererDescriptor *descriptor, RenderingDevice *device) : _device(device), _descriptor(descriptor) { RN_ASSERT(descriptor, "Descriptor mustn't be NULL"); RN_ASSERT(device, "Device mustn't be NULL"); } Renderer::~Renderer() {} bool Renderer::IsHeadless() { return !_activeRenderer; } Renderer *Renderer::GetActiveRenderer() { RN_ASSERT(_activeRenderer, "GetActiveRenderer() called, but no renderer is currently active"); return _activeRenderer; } void Renderer::Activate() { RN_ASSERT(!_activeRenderer, "Rayne only supports one active renderer at a time"); _activeRenderer = this; } void Renderer::Deactivate() { _activeRenderer = nullptr; } }
20.018868
96
0.7295
[ "object" ]
8d520cf8dbed63d6cddb4e1a68beee5ad1df0104
13,000
cpp
C++
src/engine/utils/src/navigation/navmesh_generator.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
null
null
null
src/engine/utils/src/navigation/navmesh_generator.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
null
null
null
src/engine/utils/src/navigation/navmesh_generator.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
null
null
null
#include "halley/navigation/navmesh_generator.h" #include "halley/navigation/navmesh_set.h" using namespace Halley; NavmeshSet NavmeshGenerator::generate(const NavmeshBounds& bounds, gsl::span<const Polygon> rawObstacles, gsl::span<const Polygon> regions, int subWorld, float agentSize) { auto obstacles = preProcessObstacles(rawObstacles, agentSize); const auto u = bounds.side0 / bounds.side0Divisions; const auto v = bounds.side1 / bounds.side1Divisions; const float maxSize = (u - v).length() * 0.6f; std::vector<NavmeshNode> polygons; for (size_t i = 0; i < bounds.side0Divisions; ++i) { for (size_t j = 0; j < bounds.side1Divisions; ++j) { const auto cell = Polygon(VertexList{{ bounds.origin + (i + 1) * u + j * v, bounds.origin + (i + 1) * u + (j + 1) * v, bounds.origin + i * u + (j + 1) * v, bounds.origin + i * u + j * v }}); auto cellPolygons = toNavmeshNode(generateByPolygonSubtraction(gsl::span<const Polygon>(&cell, 1), obstacles, cell.getBoundingCircle())); generateConnectivity(cellPolygons); postProcessPolygons(cellPolygons, maxSize); const int startIdx = static_cast<int>(polygons.size()); for (auto& p: cellPolygons) { polygons.emplace_back(std::move(p)); for (auto& c: polygons.back().connections) { if (c != -1) { c += startIdx; } } } } } generateConnectivity(polygons); postProcessPolygons(polygons, maxSize); applyRegions(polygons, regions); const int nRegions = assignRegions(polygons); NavmeshSet result; for (int region = 0; region < nRegions; ++region) { result.add(makeNavmesh(polygons, bounds, region, subWorld)); } return result; } std::vector<Polygon> NavmeshGenerator::generateByPolygonSubtraction(gsl::span<const Polygon> inputPolygons, gsl::span<const Polygon> obstacles, Circle bounds) { // Start with the given input polygons std::vector<Polygon> output; for (const auto& b: inputPolygons) { b.splitIntoConvex(output); } for (const auto& p: output) { assert(p.isClockwise()); } // Subtract all obstacles for (const auto& obstacle: obstacles) { if (!obstacle.getBoundingCircle().overlaps(bounds)) { continue; } int nPolys = static_cast<int>(output.size()); std::vector<Polygon> toAdd; for (int i = 0; i < nPolys; ++i) { // Subtract this obstacle from this polygon, then update the list auto subResult = output[i].subtract(obstacle); if (subResult) { limitPolygonSides(subResult.value(), 8); if (subResult.value().size() == 1) { // Just replace output[i] = std::move(subResult.value()[0]); } else { // Put this polygon at the end of the list and remove it if (i != nPolys - 1) { std::swap(output[i], output[nPolys - 1]); } output.pop_back(); --i; nPolys--; for (auto& p: subResult.value()) { toAdd.push_back(std::move(p)); } } } } // Add the new polygons for (auto& p: toAdd) { output.push_back(std::move(p)); } } return output; } std::vector<Polygon> NavmeshGenerator::preProcessObstacles(gsl::span<const Polygon> obstacles, float agentSize) { std::vector<Polygon> result; // Convert all to convex for (const auto& o: obstacles) { if (o.isValid()) { o.splitIntoConvex(result); } } // Ensure they're all clockwise for (auto& o: result) { if (!o.isClockwise()) { o.invertWinding(); } } // Expand based on agent size const auto agentMask = makeAgentMask(agentSize); for (auto& o: result) { o = o.convolution(agentMask); o.simplify(2.0f); } return result; } Polygon NavmeshGenerator::makeAgentMask(float agentSize) { auto d = Vector2f(agentSize, agentSize * static_cast<float>(sin(pi() / 8.0))); VertexList vertices; for (int i = 0; i < 8; ++i) { vertices.push_back(d.rotate(Angle1f::fromRadians(static_cast<float>(i * pi() / 4.0f))) * Vector2f(1.0f, 0.5f)); } Polygon agentMask(std::move(vertices)); Ensures(agentMask.isClockwise()); Ensures(agentMask.isValid()); return agentMask; } std::vector<NavmeshGenerator::NavmeshNode> NavmeshGenerator::toNavmeshNode(std::vector<Polygon> polygons) { std::vector<NavmeshNode> result; result.reserve(polygons.size()); for (auto& p: polygons) { const size_t n = p.getNumSides(); result.push_back(NavmeshNode(std::move(p), std::vector<int>(n, -1))); } return result; } void NavmeshGenerator::generateConnectivity(gsl::span<NavmeshNode> polygons) { for (size_t polyAIdx = 0; polyAIdx < polygons.size(); ++polyAIdx) { NavmeshNode& a = polygons[polyAIdx]; for (size_t edgeAIdx = 0; edgeAIdx < a.connections.size(); ++edgeAIdx) { if (a.connections[edgeAIdx] == -1) { auto edgeA = a.polygon.getEdge(edgeAIdx); for (size_t polyBIdx = polyAIdx + 1; polyBIdx < polygons.size(); ++polyBIdx) { NavmeshNode& b = polygons[polyBIdx]; auto edgeBIdx = b.polygon.findEdge(edgeA, 0.0001f); if (edgeBIdx) { //auto edgeB = b.polygon.getEdge(edgeBIdx.value()); //assert(b.connections[edgeBIdx.value()] == -1); if (b.connections[edgeBIdx.value()] == -1) { // Establish connection a.connections[edgeAIdx] = static_cast<int>(polyBIdx); b.connections[edgeBIdx.value()] = static_cast<int>(polyAIdx); } } } } } } } void NavmeshGenerator::postProcessPolygons(std::vector<NavmeshNode>& polygons, float maxSize) { // Go through each polygon and see if any of its neighbours can be merged with it. // If it can be merged, repeat the loop on the same polygon, otherwise move on for (int aIdx = 0; aIdx < static_cast<int>(polygons.size()); ++aIdx) { auto& polyA = polygons[aIdx]; if (!polyA.alive) { continue; } for (size_t j = 0; j < polyA.connections.size(); ++j) { const auto bIdx = polyA.connections[j]; assert(bIdx != aIdx); if (bIdx > aIdx) { auto& polyB = polygons[bIdx]; auto bEdgeIter = std::find_if(polyB.connections.begin(), polyB.connections.end(), [&] (int c) { return c == aIdx; }); assert(bIdx == polyA.connections[j]); auto mergedPolygon = merge(polyA, polyB, j, bEdgeIter - polyB.connections.begin(), aIdx, bIdx, maxSize); if (mergedPolygon) { for (auto& c: polyB.connections) { if (c != -1 && c != aIdx) { remapConnections(polygons[c], bIdx, aIdx); } } for (auto& c: mergedPolygon.value().connections) { assert(c != aIdx); assert(c != bIdx); } --aIdx; polyA = std::move(mergedPolygon.value()); polyB.alive = false; break; } } } } removeDeadPolygons(polygons); } void NavmeshGenerator::removeDeadPolygons(std::vector<NavmeshNode>& polygons) { int newIdx = 0; for (int i = 0; i < static_cast<int>(polygons.size()); ++i) { if (polygons[i].alive) { polygons[i].remap = newIdx++; } } for (auto& poly: polygons) { if (poly.alive) { for (auto& c: poly.connections) { if (c >= 0) { c = polygons[c].remap; } } } } polygons.erase(std::remove_if(polygons.begin(), polygons.end(), [&] (const NavmeshNode& p) { return !p.alive; }), polygons.end()); } std::optional<NavmeshGenerator::NavmeshNode> NavmeshGenerator::merge(const NavmeshNode& a, const NavmeshNode& b, size_t aEdgeIdx, size_t bEdgeIdx, size_t aIdx, size_t bIdx, float maxSize) { Expects(a.polygon.isClockwise() == b.polygon.isClockwise()); std::vector<Vector2f> vsA = a.polygon.getVertices(); std::vector<Vector2f> vsB = b.polygon.getVertices(); std::vector<int> connA = a.connections; std::vector<int> connB = b.connections; const size_t aSize = vsA.size(); const size_t bSize = vsB.size(); if (aSize + bSize + 2 > maxPolygonSides) { return {}; } // Merge vertices std::rotate(vsA.begin(), vsA.begin() + (aEdgeIdx + 1) % aSize, vsA.end()); std::rotate(vsB.begin(), vsB.begin() + (bEdgeIdx + 1) % bSize, vsB.end()); vsA.pop_back(); vsB.pop_back(); vsA.insert(vsA.end(), vsB.begin(), vsB.end()); // Make polygon auto prePoly = Polygon(vsA); // Don't move vsA if (!prePoly.isConvex()) { return {}; } if (prePoly.getBoundingCircle().getRadius() > maxSize) { return {}; } // Merge connections std::rotate(connA.begin(), connA.begin() + (aEdgeIdx + 1) % aSize, connA.end()); std::rotate(connB.begin(), connB.begin() + (bEdgeIdx + 1) % bSize, connB.end()); assert(connA.back() == bIdx); assert(connB.back() == aIdx); connA.pop_back(); connB.pop_back(); connA.insert(connA.end(), connB.begin(), connB.end()); // Base result auto result = NavmeshNode(std::move(prePoly), connA); // Don't move connA // Simplify size_t n = vsA.size(); bool simplified = false; for (size_t i = 0; n > 3 && i < n; ++i) { if (connA[(i + n - 1) % n] == -1 && connA[i] == -1) { Vector2f cur = vsA[i]; Vector2f prev = vsA[(i + n - 1) % n]; Vector2f next = vsA[(i + 1) % n]; const float maxDist = (prev - next).length() * 0.01f; if (LineSegment(prev, next).contains(cur, maxDist)) { vsA.erase(vsA.begin() + i); connA.erase(connA.begin() + i); --n; --i; simplified = true; } } } if (simplified) { auto simplifiedPoly = Polygon(vsA); if (simplifiedPoly.isConvex() && simplifiedPoly.isClockwise() == a.polygon.isClockwise()) { return NavmeshNode(std::move(simplifiedPoly), std::move(connA)); } } return result; } void NavmeshGenerator::remapConnections(NavmeshNode& poly, int from, int to) { for (auto& c: poly.connections) { if (c == from) { c = to; } } } void NavmeshGenerator::limitPolygonSides(std::vector<Polygon>& polygons, size_t maxSides) { const size_t n = polygons.size(); for (size_t i = 0; i < n; ++i) { if (polygons[i].getNumSides() > maxSides) { auto result = polygons[i].splitConvexIntoMaxSides(maxSides); polygons[i] = std::move(result[0]); for (size_t j = 1; j < result.size(); ++j) { polygons.push_back(std::move(result[j])); } } } } void NavmeshGenerator::applyRegions(gsl::span<NavmeshNode> nodes, gsl::span<const Polygon> regions) { int curRegionGroup = 1; for (const auto& region: regions) { std::vector<Polygon> convexRegions; region.splitIntoConvex(convexRegions); for (auto& node: nodes) { for (const auto& convexRegion: convexRegions) { if (node.polygon.classify(convexRegion) != Polygon::SATClassification::Separate) { node.regionGroup = curRegionGroup; break; } } } ++curRegionGroup; } } int NavmeshGenerator::assignRegions(gsl::span<NavmeshNode> nodes) { int curRegion = 0; for (auto& n: nodes) { if (n.region == -1) { // Found an unassigned node, start floodfill from here floodFillRegion(nodes, n, n.regionGroup, curRegion++); } } return curRegion; } void NavmeshGenerator::floodFillRegion(gsl::span<NavmeshNode> nodes, NavmeshNode& firstNode, int regionGroup, int region) { std::list<NavmeshNode*> pending; pending.push_back(&firstNode); firstNode.tagged = true; while (!pending.empty()) { auto* cur = pending.front(); pending.pop_front(); cur->region = region; for (auto& c: cur->connections) { if (c != -1) { auto* neighbour = &nodes[c]; if (!neighbour->tagged && neighbour->regionGroup == regionGroup) { neighbour->tagged = true; pending.push_back(neighbour); } } } } } std::optional<size_t> NavmeshGenerator::getNavmeshEdge(NavmeshNode& node, size_t side, gsl::span<const Line> mapEdges) { const auto edge = node.polygon.getEdge(side); for (size_t i = 0; i < mapEdges.size(); ++i) { const auto& mapEdge = mapEdges[i]; if (mapEdge.getDistance(edge.a) < 0.1f && mapEdge.getDistance(edge.b) < 0.1f) { return i; } } return {}; } Navmesh NavmeshGenerator::makeNavmesh(gsl::span<NavmeshNode> nodes, const NavmeshBounds& bounds, int region, int subWorld) { std::vector<Navmesh::PolygonData> output; // Special connection values: // -1: no connection // -2, -3, -4, -5: connections to the four edges of this chunk // -6 onwards: connections to other regions in this chunk // Establish remapping int i = 0; for (auto& node: nodes) { assert (node.alive); if (node.region == region) { node.remap = i++; } else { node.remap = -(6 + node.region); } } output.reserve(i); // Make edges const auto u = bounds.side0.normalized(); const auto v = bounds.side1.normalized(); const auto p0 = bounds.origin; const auto p1 = bounds.origin + bounds.side0 + bounds.side1; const std::array<Line, 4> edges = { Line(p0, u), Line(p0, v), Line(p1, u), Line(p1, v) }; // Generate for (auto& node: nodes) { if (node.alive && node.region == region) { std::vector<int> connections = node.connections; for (size_t i = 0; i < connections.size(); ++i) { auto& c = connections[i]; if (c >= 0) { c = nodes[c].remap; } else { auto edge = getNavmeshEdge(node, i, edges); if (edge) { c = -(2 + static_cast<int>(edge.value())); } } } output.push_back(Navmesh::PolygonData{ std::move(node.polygon), std::move(connections) }); } } return Navmesh(std::move(output), bounds, subWorld); }
27.484144
187
0.646538
[ "vector" ]
8d59525e938179e95cb2863a80094b19d231dad6
5,809
inl
C++
Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2021-07-17T23:46:31.000Z
2021-07-17T23:46:31.000Z
Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> #include <CryCommon/ISystem.h> //////////////////////////////////////////////////////////////////////////////////////////////////// inline void Gestures::RecognizerSwipe::Config::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context)) { serialize->Class<Config>() ->Version(0) ->Field("maxSecondsHeld", &Config::maxSecondsHeld) ->Field("maxPixelsMoved", &Config::minPixelsMoved) ->Field("pointerIndex", &Config::pointerIndex) ->Field("priority", &Config::priority) ; if (AZ::EditContext* ec = serialize->GetEditContext()) { ec->Class<Config>("Swipe Config", "Configuration values used to setup a gesture recognizer for swipes.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::SpinBox, &Config::pointerIndex, "Pointer Index", "The pointer (button or finger) index to track.") ->Attribute(AZ::Edit::Attributes::Min, 0) ->Attribute(AZ::Edit::Attributes::Max, 10) ->DataElement(AZ::Edit::UIHandlers::Default, &Config::maxSecondsHeld, "Max Seconds Held", "The max time in seconds after the initial press for a swipe to be recognized.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &Config::minPixelsMoved, "Min Pixels Moved", "The min distance in pixels that must be moved before a swipe will be recognized.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// inline Gestures::RecognizerSwipe::RecognizerSwipe(const Config& config) : m_config(config) , m_startPosition() , m_endPosition() , m_startTime(0) , m_endTime(0) , m_currentState(State::Idle) { } //////////////////////////////////////////////////////////////////////////////////////////////////// inline Gestures::RecognizerSwipe::~RecognizerSwipe() { } //////////////////////////////////////////////////////////////////////////////////////////////////// inline bool Gestures::RecognizerSwipe::OnPressedEvent(const AZ::Vector2& screenPosition, uint32_t pointerIndex) { if (pointerIndex != m_config.pointerIndex) { return false; } switch (m_currentState) { case State::Idle: { m_startTime = gEnv->pTimer->GetFrameStartTime().GetValue(); m_startPosition = screenPosition; m_endPosition = screenPosition; m_currentState = State::Pressed; } break; case State::Pressed: default: { // Should not be possible, but not fatal if we happen to get here somehow. AZ_Warning("RecognizerDrag", false, "RecognizerDrag::OnPressedEvent state logic failure"); } break; } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline bool Gestures::RecognizerSwipe::OnDownEvent([[maybe_unused]] const AZ::Vector2& screenPosition, uint32_t pointerIndex) { if (pointerIndex != m_config.pointerIndex) { return false; } switch (m_currentState) { case State::Pressed: { const CTimeValue currentTime = gEnv->pTimer->GetFrameStartTime(); if (currentTime.GetDifferenceInSeconds(m_startTime) > m_config.maxSecondsHeld) { // Swipe recognition failed because we took too long. m_currentState = State::Idle; } } break; case State::Idle: { // Swipe recognition already failed above. } break; default: { // Should not be possible, but not fatal if we happen to get here somehow. AZ_Warning("RecognizerSwipe", false, "RecognizerSwipe::OnDownEvent state logic failure"); } break; } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline bool Gestures::RecognizerSwipe::OnReleasedEvent(const AZ::Vector2& screenPosition, uint32_t pointerIndex) { if (pointerIndex != m_config.pointerIndex) { return false; } switch (m_currentState) { case State::Pressed: { const CTimeValue currentTime = gEnv->pTimer->GetFrameStartTime(); if ((currentTime.GetDifferenceInSeconds(m_startTime) <= m_config.maxSecondsHeld) && (screenPosition.GetDistance(m_startPosition) >= m_config.minPixelsMoved)) { // Swipe recognition succeeded. m_endTime = currentTime.GetValue(); m_endPosition = screenPosition; OnDiscreteGestureRecognized(); m_currentState = State::Idle; } else { // Swipe recognition failed because we took too long or didn't move enough. m_currentState = State::Idle; } } break; case State::Idle: { // Swipe recognition already failed above. } break; default: { // Should not be possible, but not fatal if we happen to get here somehow. AZ_Warning("RecognizerSwipe", false, "RecognizerSwipe::OnReleasedEvent state logic failure"); } break; } return false; }
34.372781
189
0.56619
[ "3d" ]
8d66b23ed92d94c27f5ea11905925d048abf6587
1,659
cpp
C++
EDU/segment_tree/step 3/Nested_Segments.cpp
cfuser/codeforces
7f6d56ad8879bc8707b84b6f7e4d40511eab3914
[ "MIT" ]
10
2020-12-08T10:43:35.000Z
2021-12-24T02:50:36.000Z
EDU/segment_tree/step 3/Nested_Segments.cpp
cfuser/codeforces
7f6d56ad8879bc8707b84b6f7e4d40511eab3914
[ "MIT" ]
null
null
null
EDU/segment_tree/step 3/Nested_Segments.cpp
cfuser/codeforces
7f6d56ad8879bc8707b84b6f7e4d40511eab3914
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; struct segtree { int size; vector<long long> sums; void init(int n) { size = 1; while (size < n) size *= 2; sums.assign(2 * size, 0LL); } void build(vector<int> &a, int x, int lx, int rx) { if (rx - lx == 1) { if (lx < (int)a.size()) sums[x] = a[lx]; return ; } int mid = (lx + rx) / 2; build(a, 2 * x + 1, lx, mid); build(a, 2 * x + 2, mid, rx); sums[x] = sums[2 * x + 1] + sums[2 * x + 2]; } void build(vector<int> &a) { build(a, 0, 0, size); } void set(int i, int v, int x, int lx, int rx) { if (rx - lx == 1) { sums[ x ] = v; return ; } int mid = (lx + rx) / 2; if (i < mid) set(i, v, 2 * x + 1, lx, mid); else if (i >= mid) set(i, v, 2 * x + 2, mid, rx); sums[x] = sums[2 * x + 1] + sums[2 * x + 2]; } void set(int i, int v) { set(i, v, 0, 0, size); } long long sum(int l, int r, int x, int lx, int rx) { if (lx >= r || rx <= l) return 0; if (lx >= l && rx <= r) return sums[x]; int mid = (lx + rx) / 2; long long s1 = sum(l, r, 2 * x + 1, lx, mid); long long s2 = sum(l, r, 2 * x + 2, mid, rx); return s1 + s2; } long long sum(int l, int r) { return sum(l, r, 0, 0, size); } }; int main() { ios::sync_with_stdio(false); int n,m; cin >> n; n*=2; segtree st; st.init(n); vector<int> a(n),pos(n/2),ans(n/2); a.assign(n,0); pos.assign(n/2,-1); st.build(a); for (int i = 0; i < n; i++) {cin>>a[i];a[i]--;} for (int i = 0; i < n; i++) { if (pos[a[i]]==-1) pos[a[i]]=i; else { ans[a[i]] = st.sum(pos[a[i]],i); st.set(pos[a[i]],1); } } for (int i = 0; i < n/2; i++) cout<<ans[i]<<" ";cout<<endl; }
19.75
60
0.482821
[ "vector" ]
8d6814cfb884451fcb5d02e44f361c76d584287f
2,248
cpp
C++
Source/Runtime/Private/Components/ComFixedJoint.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
410
2017-03-03T08:56:54.000Z
2022-03-29T07:18:46.000Z
Source/Runtime/Private/Components/ComFixedJoint.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
31
2017-03-05T11:37:44.000Z
2021-09-15T21:28:34.000Z
Source/Runtime/Private/Components/ComFixedJoint.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
48
2017-03-18T05:28:21.000Z
2022-03-05T12:27:17.000Z
// Copyright(c) 2017 POLYGONTEK // // 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 "Precompiled.h" #include "Render/Render.h" #include "Components/ComTransform.h" #include "Components/ComRigidBody.h" #include "Components/ComFixedJoint.h" #include "Game/GameWorld.h" BE_NAMESPACE_BEGIN OBJECT_DECLARATION("Fixed Joint", ComFixedJoint, ComJoint) BEGIN_EVENTS(ComFixedJoint) END_EVENTS void ComFixedJoint::RegisterProperties() { } ComFixedJoint::ComFixedJoint() { } ComFixedJoint::~ComFixedJoint() { } void ComFixedJoint::Init() { ComJoint::Init(); // Mark as initialized SetInitialized(true); } void ComFixedJoint::CreateConstraint() { const ComRigidBody *rigidBody = GetEntity()->GetComponent<ComRigidBody>(); assert(rigidBody); // Fill up a constraint description. PhysConstraintDesc desc; desc.type = PhysConstraint::Type::Hinge; desc.collision = collisionEnabled; desc.breakImpulse = breakImpulse; desc.bodyA = rigidBody->GetBody(); desc.axisInA = Mat3::identity; desc.anchorInA = Vec3::zero; const ComRigidBody *connectedBody = GetConnectedBody(); if (connectedBody) { desc.bodyB = connectedBody->GetBody(); desc.axisInB = Mat3::identity; desc.anchorInB = connectedBody->GetBody()->GetAxis().TransposedMulVec(desc.bodyA->GetOrigin() - connectedBody->GetBody()->GetOrigin()); } else { desc.bodyB = nullptr; } // Create a constraint with the given description. PhysHingeConstraint *hingeConstraint = (PhysHingeConstraint *)physicsSystem.CreateConstraint(desc); hingeConstraint->SetAngularLimits(0, 0); hingeConstraint->EnableAngularLimits(true); constraint = hingeConstraint; } BE_NAMESPACE_END
29.194805
143
0.727758
[ "render" ]
8d6a2d35e3c6767973989cc4c16b430d18af2d73
5,778
hpp
C++
src/terark/thread/instance_tls.hpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
44
2020-12-21T05:14:38.000Z
2022-03-15T11:27:32.000Z
src/terark/thread/instance_tls.hpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
2
2020-12-28T10:42:03.000Z
2021-05-21T07:22:47.000Z
src/terark/thread/instance_tls.hpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
21
2020-12-22T09:40:16.000Z
2021-12-07T18:16:00.000Z
#pragma once #include <new> #include <memory> #include <mutex> #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <boost/noncopyable.hpp> #include <terark/valvec.hpp> #include <terark/util/throw.hpp> namespace terark { template<class T> T* tls_born(size_t n) { T* p = (T*)malloc(sizeof(T) * n); for (size_t i = 0; i < n; ++i) new (p+i) T (); return p; } template<class T> void tls_die(T* p, size_t n) { if (!boost::has_trivial_destructor<T>::value) for (size_t i = 0; i < n; ++i) p[i].~T(); free(p); } template<class T> void tls_reborn(T* p) { if (!boost::has_trivial_destructor<T>::value) p->~T(); new(p) T(); // call default cons } /// @param T default T::T() should initilize T into <null> state /// default T::T() should not throw template<class T, uint32_t Rows = 256, uint32_t Cols = Rows> class instance_tls : boost::noncopyable { static_assert(Cols && (Cols & (Cols-1)) == 0, "Cols must be power of 2"); // All allocated slots are initially constructed by default cons // 1. busy slot is ready to be accessed // 2. busy slot must be constructed(default cons to <null> state) // 3. busy slot may also be really initialized(not <null>) // 4. non-busy slot must be <null>(default cons'ed), and will not be // used by user code // 5. destructor will always be called on all slots static const uint32_t busy = uint32_t(-2); // for debug track static const uint32_t tail = uint32_t(-1); public: instance_tls() { std::lock_guard<std::mutex> lock(s_mutex); if (tail != s_id_head) { m_id = s_id_head; s_id_head = s_id_list[s_id_head]; s_id_list[m_id] = uint32_t(busy); } else if (s_id_list.size() < Rows * Cols) { m_id = (uint32_t)s_id_list.size(); s_id_list.push_back(uint32_t(busy)); } else { // fail THROW_STD(logic_error, "too many object instance"); } } ~instance_tls() { size_t id = m_id; size_t i = id / Cols; size_t j = id % Cols; s_mutex.lock(); for(MatrixLink* p = s_matrix_head.next; p != &s_matrix_head; ) { Matrix* q = static_cast<Matrix*>(p); if (q->A[i]) { tls_reborn(&q->A[i][j]); } p = p->next; } assert(busy == s_id_list[m_id]); s_id_list[id] = s_id_head; s_id_head = uint32_t(id); s_mutex.unlock(); } T& get() const { size_t i = m_id / Cols; size_t j = m_id % Cols; Matrix* pMatrix = tls_matrix.get(); if (terark_likely(nullptr != pMatrix)) { T* pOneRow = pMatrix->A[i]; if (terark_likely(nullptr != pOneRow)) return pOneRow[j]; } return get_slow(i, j); } private: terark_no_inline static T& get_slow(size_t i, size_t j) { T* pOneRow = tls_born<T>(Cols); std::unique_ptr<Matrix>& pMatrix = tls_matrix; // s_mutex protect for instance_tls::~instance_tls() if (terark_likely(NULL != pMatrix)) { s_mutex.lock(); pMatrix->A[i] = pOneRow; s_mutex.unlock(); } else { pMatrix.reset(new Matrix()); s_mutex.lock(); pMatrix->insert_to_list_no_lock(); pMatrix->A[i] = pOneRow; s_mutex.unlock(); } return pOneRow[j]; } uint32_t m_id; // static members: // static std::mutex s_mutex; static uint32_t s_thread_num; static uint32_t s_id_head; static valvec<uint32_t> s_id_list; // use matrix to speed lookup & reduce memory usage struct MatrixLink : boost::noncopyable { MatrixLink* next; MatrixLink* prev; MatrixLink() {} // do nothing MatrixLink(int) { // init as head next = prev = this; } }; struct Matrix : MatrixLink { using MatrixLink::next; using MatrixLink::prev; T* A[Rows]; // use 2-level direct access void insert_to_list_no_lock() { next = &s_matrix_head; prev = s_matrix_head.prev; s_matrix_head.prev->next = this; s_matrix_head.prev = this; s_thread_num++; } Matrix() { std::fill_n(A, Rows, nullptr); } ~Matrix() { size_t list_size; s_mutex.lock(); next->prev = prev; prev->next = next; s_thread_num--; list_size = s_id_list.size(); s_mutex.unlock(); for (size_t i = (list_size + Cols-1) / Cols; i-- > 0; ) { if (T* pOneRow = A[i]) { tls_die(pOneRow, Cols); } } } }; static MatrixLink s_matrix_head; static thread_local std::unique_ptr<Matrix> tls_matrix; }; template<class T, uint32_t Rows, uint32_t Cols> std::mutex instance_tls<T, Rows, Cols>::s_mutex; template<class T, uint32_t Rows, uint32_t Cols> uint32_t instance_tls<T, Rows, Cols>::s_thread_num = 0; template<class T, uint32_t Rows, uint32_t Cols> uint32_t instance_tls<T, Rows, Cols>::s_id_head = tail; template<class T, uint32_t Rows, uint32_t Cols> valvec<uint32_t> instance_tls<T, Rows, Cols>::s_id_list(Cols, valvec_reserve()); template<class T, uint32_t Rows, uint32_t Cols> typename instance_tls<T, Rows, Cols>::MatrixLink instance_tls<T, Rows, Cols>::s_matrix_head(0); // init as head template<class T, uint32_t Rows, uint32_t Cols> thread_local std::unique_ptr<typename instance_tls<T, Rows, Cols>::Matrix> instance_tls<T, Rows, Cols>::tls_matrix; } // namespace terark
29.783505
77
0.571651
[ "object" ]
8d6d42159a547dfea3203e376599a97cd722f851
3,198
cpp
C++
App/DatumCS.cpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
21
2019-12-06T09:57:10.000Z
2021-09-22T12:58:09.000Z
App/DatumCS.cpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
null
null
null
App/DatumCS.cpp
haisenzhao/CarpentryCompiler
c9714310b7ce7523a25becd397265bfaa3ab7ea3
[ "FSFAP" ]
5
2020-11-18T00:09:30.000Z
2021-01-13T04:40:47.000Z
/*************************************************************************** * Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRepBuilderAPI_MakeFace.hxx> # include <gp_Pln.hxx> #endif #include "DatumCS.h" using namespace PartDesign; using namespace Attacher; // ============================================================================ PROPERTY_SOURCE(PartDesign::CoordinateSystem, Part::Datum) CoordinateSystem::CoordinateSystem() { this->setAttacher(new AttachEngine3D); // Create a shape, which will be used by the Sketcher. Them main function is to avoid a dependency of // Sketcher on the PartDesign module BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0,0,0), gp_Dir(0,0,1))); if (!builder.IsDone()) return; Shape.setValue(builder.Shape()); } CoordinateSystem::~CoordinateSystem() { } Base::Vector3d CoordinateSystem::getXAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; rot.multVec(Base::Vector3d(1,0,0), normal); return normal; } Base::Vector3d CoordinateSystem::getYAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; rot.multVec(Base::Vector3d(0,1,0), normal); return normal; } Base::Vector3d CoordinateSystem::getZAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; rot.multVec(Base::Vector3d(0,0,1), normal); return normal; } PROPERTY_SOURCE(PartDesign::Variable, Part::Datum) Variable::Variable() { ADD_PROPERTY_TYPE(Value, (100.0), "Variable", App::Prop_None, "The value of variable"); } Variable::~Variable() { }
35.142857
105
0.540963
[ "shape" ]
8d6de686af4902c0b11d55ba4d6bcdf37c495773
12,544
cc
C++
src/util/misc.cc
ognis/jargon
3cd9917f5ffb3a7185467b6294656e666f04d05b
[ "Apache-2.0" ]
null
null
null
src/util/misc.cc
ognis/jargon
3cd9917f5ffb3a7185467b6294656e666f04d05b
[ "Apache-2.0" ]
null
null
null
src/util/misc.cc
ognis/jargon
3cd9917f5ffb3a7185467b6294656e666f04d05b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2014- Shingo OKAWA */ #include <assert.h> #include <cctype> #include <limits.h> #include <map> #include <iostream> #include "dirent.h" #include "misc.h" #if defined(JARGON_HAVE_SYS_TIME_H) # include <sys/time.h> #elif defined(JARGON_HAVE_TIME_H) # include <time.h> #endif #ifdef JARGON_HAVE_SYS_TIMEB_H # include <sys/timeb.h> #endif #if defined(JARGON_HAVE_SYS_STAT_H) # include <sys/stat.h> #endif #ifdef JARGON_HAVE_STRINGS_H # include <strings.h> #endif #ifdef JARGON_HAVE_UNISTD_H # include <unistd.h> #endif #ifdef JARGON_HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef JARGON_HAVE_IO_H # ifdef __APPLE__ # include <sys/uio.h> # else # include <sys/io.h> # endif #endif JARGON_NAMESPACE_BEGIN(util) /* Returns current time in milli second. */ uint64_t misc::current_time_millis() { #ifndef JARGON_HAVE_GETTIMEOFDAY_F struct _timeb tstruct; _ftime(&tstruct); return (((uint64_t) tstruct.time) * 1000) + tstruct.millitm; #else struct timeval tstruct; if (gettimeofday(&tstruct, NULL) < 0) { return 0; } return (((uint64_t) tstruct.tv_sec) * 1000) + tstruct.tv_usec / 1000; #endif } /* Replaces 'search' with 'replace' at every occurence of 'search' in 'value'. */ const tchar_t* misc::replace( const tchar_t* value, const tchar_t* search, const tchar_t* replace) { int32_t count = 0; size_t replace_length = tcslen(replace); size_t search_length = tcslen(search); size_t value_length = tcslen(value); const tchar_t* position = value; while ((position = tcsstr(position + 1, search)) != NULL) { ++count; } size_t new_length = (value_length - (search_length * count)) + (replace_length * count); tchar_t* result = JARGON_NEW_ARRAY(tchar_t, new_length + 1); result[new_length] = 0; if (count == 0) { tcscpy(result, value); return result; } tchar_t* current = result; const tchar_t* processing = value; position = value; while ((position = tcsstr(position + 1, search)) != NULL) { tcsncpy(current, processing, position - processing); current += (position - processing); processing = position; tcscpy(current, replace); current += replace_length; processing += search_length; } tcscpy(current, processing); return result; } /* Returns true if the given directory exist. */ bool misc::directory_exists(const char* path){ if (!path || !*path) { return false; } tstat_t info; int32_t result = tstat(path, &info); return result == 0; } /* Returns the size of file. */ int64_t misc::file_size(const char* path) { tstat_t info; if (tstat(path, &info) == 0) { return info.st_size; } else { return -1; } } /* Returns the length of file. */ int64_t misc::file_length(int handle) { tstat_t info; if (tfstat(handle, &info) == -1) { return -1; } return info.st_size; } /* Unlinks the given file, waits until directory_exists is false. */ int misc::file_unlink(const char* path, int32_t attempts) { int32_t i; if (!path || !*path ) { return -1; } if (attempts == 0) { attempts = 1; } while (attempts != 0) { if(tunlink(path) != 0 ) { return -1; } i = 0; while (i < 100) { if (!misc::directory_exists(path)) { return 1; } if (++i > 50) { misc::sleep(1); } } if (attempts > 0) { attempts--; } } return 0; } /* Sleep until assigned milli seconds elepsed. */ void misc::sleep(const int ms) { #if defined(JARGON_HAVE_USLEEP_F) usleep(ms * 1000); #else # error no sleep function? #endif } /* Lists all files in dir. */ bool misc::list_files( const char* directory_path, std::vector<std::string>& files, bool full_path) { tdir_t* directory = opendir(directory_path); if (directory == NULL) { return false; } struct dirent* current = readdir(directory); tstat_t info; std::string path; while (current != NULL) { path = std::string(directory->dd_name) + "/" + current->d_name; int32_t file_stat = tstat(path.c_str(), &info); if (file_stat == 0 && !(info.st_mode & S_IFDIR)) { if ((strcmp(current->d_name, ".")) && (strcmp(current->d_name, ".."))) { if (full_path) { files.push_back(path); } else { files.push_back(current->d_name); } } } current = readdir(directory); } closedir(directory); return true; } /* Returns true if the file is dot file. */ bool misc::is_dot_directory(const tchar_t* path) { if (path[0] == '\0') { return false; } if (path[0] == '.' && path[1] == '\0') { return true; } if (path[1] == '\0') { return false; } if (path[0] == '.' && path[1] == '.' && path[2] == '\0') { return true; } return false; } /* Generates hash code for the assigned single-string. */ size_t misc::c_hash_code(const char* value) { size_t hash_code = 0; while (*value != 0) { hash_code = hash_code * 31 + *value++; } return hash_code; } /* Generates hash code for the assigned single-string. */ size_t misc::c_hash_code(const char* value, size_t length){ size_t hash_code = 0; for (size_t i = 0; i < length; i++) { hash_code = hash_code * 31 + *value++; } return hash_code; } /* Concatenates given strings. */ tchar_t* misc::t_concat( const tchar_t* a, const tchar_t* b, const tchar_t* c, const tchar_t* d, const tchar_t* e, const tchar_t* f) { #define T_LENGTH(x) (x == NULL ? 0 : tcslen(x)) const size_t total_length = T_LENGTH(a) + T_LENGTH(b) + T_LENGTH(c) + T_LENGTH(d) + T_LENGTH(e) + T_LENGTH(f) + sizeof(tchar_t); tchar_t* buffer = JARGON_NEW_ARRAY(tchar_t, total_length); buffer[0]=0; if (a != NULL) { tcscat(buffer, a); } if (b != NULL) { tcscat(buffer, b); } if (c != NULL) { tcscat(buffer, c); } if (d != NULL) { tcscat(buffer, d); } if (e != NULL) { tcscat(buffer, e); } if (f != NULL) { tcscat(buffer, f); } return buffer; } /* Concatenates given single-strings. */ char* misc::c_concat( const char* a, const char* b, const char* c, const char* d, const char* e, const char* f ) { #define C_LENGTH(x) (x == NULL ? 0 : strlen(x)) const size_t total_length = C_LENGTH(a) + C_LENGTH(b) + C_LENGTH(c) + C_LENGTH(d) + C_LENGTH(e) + C_LENGTH(f) + sizeof(char); char* buffer = JARGON_NEW_ARRAY(char, total_length); buffer[0] = 0; if (a != NULL) { strcat(buffer, a); } if (b != NULL) { strcat(buffer, b); } if (c != NULL) { strcat(buffer, c); } if (d != NULL) { strcat(buffer, d); } if (e != NULL) { strcat(buffer, e); } if (f != NULL) { strcat(buffer, f); } return buffer; } /* Creates a filename by concatenating segment with exteernal and x */ std::string misc::segment_name( const char* segment, const char* extension, const int32_t x) { JARGON_PRECOND(extension != NULL, "extension is NULL"); if (x != -1) { char buffer[30]; snprintf(buffer, 10, "%d", x); return std::string(segment) + extension + buffer; } else { return std::string(segment) + extension; } } /* Creates a filename in buffer by concatenating segment with external and x */ void misc::segment_name( char* buffer, int32_t length, const char* segment, const char* extension, const int32_t x) { JARGON_PRECOND(buffer != NULL, "buffer is NULL"); JARGON_PRECOND(segment != NULL, "segment is NULL"); JARGON_PRECOND(extension != NULL, "extension is NULL"); if (x == -1) { snprintf(buffer, length, "%s%s", segment, extension); } else { snprintf(buffer, length, "%s%s%d", segment, extension, x); } } /* Compares two strings, character by character, and returns the first position where the two strings differ from one another. */ int32_t misc::t_compare( const tchar_t* s1, const int32_t s1_length, const tchar_t* s2, const int32_t s2_length) { int32_t length = s1_length < s2_length ? s1_length : s2_length; for (int32_t i = 0; i < length; i++) { if (s1[i] != s2[i]) { return i; } } return length; } /* In-place trimming for strings and words. */ tchar_t* misc::trim_string(tchar_t* value) { size_t i; size_t j; size_t length = tcslen(value); for (i = 0; i < length; i++) { if (!istspace(value[i])) { break; } } for (j = length - 1; j > i; --j) { if (!istspace(value[j])) { break; } } if (i == 0 && j == length - 1) { return value; } if (i == 0) { value[j + 1] = 0; } else { j++; tcsncpy(value, value + i, j - i); value[j - i] = 0; } return value; } tchar_t* misc::trim_word(tchar_t* value) { size_t i; size_t j; size_t length = tcslen(value); for (i = 0; i < length; i++) { if (!istspace(value[i])) break; } for (j = i; j < length; j++) { if (istspace(value[j])) { break; } } if (i == 0 && j == length) { return value; } if (i == j) { return NULL; } if (i == 0) { value[j] = 0; return value; } else { tcsncpy(value, value + i, j - i); value[j - i] = 0; } return value; } /* Casts long value to base36, and vice versa. */ size_t misc::long_to_base36(int64_t value, int32_t base, char* to) { static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buffer[(sizeof(unsigned long) << 3) + 1]; char *start; char *end; start = end = buffer + sizeof(buffer) - 1; *start = '\0'; do { *--start = digits[value % base]; value /= base; } while (start > buffer && value); memcpy( to, start, end - start ); to[end - start] = 0; return end - start; } int64_t misc::base36_to_long(const char* value) { char *start = (char*)value; int64_t result = 0; while ( *start != '\0' ) { result = isdigit(*start) ? (36 * result) + (*start - '0') : (36 * result) + (*start - 'a' + 10); start++; } return result; } /* Converts string. */ std::string misc::to_string(const int32_t value) { char buffer[20]; tchar_t t_buffer[20]; i64tot(value, t_buffer, 10); STRCPY_TtoA(buffer, t_buffer, 20); return buffer; } std::string misc::to_string(const int64_t value) { char buffer[20]; tchar_t t_buffer[20]; i64tot(value, t_buffer, 10); STRCPY_TtoA(buffer, t_buffer, 20); return buffer; } std::string misc::to_string(JARGON_THREAD_ID_T value) { static int32_t next_index = 0; static std::map<JARGON_THREAD_ID_T, int32_t> ids; if (ids.find(value) == ids.end()) { ids[value] = next_index++; } return misc::to_string(ids[value]); } std::string misc::to_string(const float_t value){ char buffer[20]; snprintf(buffer, 20, "%0.2f", (double)value); return buffer; } std::string misc::to_string(const bool value){ return value ? "true" : "false"; } std::string misc::to_string(const tchar_t* value, int32_t length){ if (value == NULL || length == 0) { return ""; } if (length < 0) { length = tcslen(value); } char* buffer = JARGON_NEW_ARRAY(char, length + 1); STRCPY_WtoA(buffer, value, length + 1); std::string result = buffer; JARGON_DEL_ARRAY(buffer); return result; } #ifndef JARGON_ASCII_MODE size_t misc::w_hash_code(const wchar_t* value) { size_t hash_code = 0; while (*value != 0 ) { hash_code = hash_code * 31 + *value++; } return hash_code; } size_t misc::w_hash_code(const wchar_t* value, size_t length) { size_t hash_code = 0; for (size_t i = 0; i < length; i++) { hash_code = hash_code * 31 + *value++; } return hash_code; } char* misc::wide_to_char(const wchar_t* value) { size_t length = tcslen(value); char* result = JARGON_NEW_ARRAY(char, length + 1); misc::copy_wide_to_char(value, result, length + 1); return result; } wchar_t* misc::char_to_wide(const char* value) { size_t length = strlen(value); wchar_t* result = JARGON_NEW_ARRAY(wchar_t, length + 1); misc::copy_char_to_wide(value, result, length + 1); return result; } void misc::copy_wide_to_char(const wchar_t* source, char* destination, size_t length) { size_t source_length = wcslen(source); for (uint32_t i = 0; i < length && i < source_length + 1; i++) { destination[i] = OUT_OF_RANGE_CHAR(source[i]); } } void misc::copy_char_to_wide(const char* source, wchar_t* destination, size_t length) { size_t source_length = strlen(source); for (uint32_t i = 0; i < length && i < source_length + 1; i++) { destination[i] = source[i]; } } #endif /* JARGON_ASCII_MODE */ JARGON_NAMESPACE_END
22.480287
90
0.616869
[ "vector" ]
8d713e31640ad00d810a78b0e003672dd3a31af7
23,789
cc
C++
proto/encpb/auc_impr_encs.pb.cc
qf6101/algorithm-components
f7307e4bd9697ee473d5763e0a61df7891b699f6
[ "Apache-2.0" ]
2
2019-11-27T11:43:45.000Z
2020-11-09T09:21:23.000Z
proto/encpb/auc_impr_encs.pb.cc
qf6101/algorithm-components
f7307e4bd9697ee473d5763e0a61df7891b699f6
[ "Apache-2.0" ]
null
null
null
proto/encpb/auc_impr_encs.pb.cc
qf6101/algorithm-components
f7307e4bd9697ee473d5763e0a61df7891b699f6
[ "Apache-2.0" ]
2
2019-12-16T18:54:17.000Z
2020-02-24T07:52:24.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: encpb/auc_impr_encs.proto #include "encpb/auc_impr_encs.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace algocomp { class AUCImprEncsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AUCImprEncs> _instance; } _AUCImprEncs_default_instance_; } // namespace algocomp namespace protobuf_encpb_2fauc_5fimpr_5fencs_2eproto { void InitDefaultsAUCImprEncsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_encpb_2fencode_5fbunch_2eproto::InitDefaultsEncodeBunch(); { void* ptr = &::algocomp::_AUCImprEncs_default_instance_; new (ptr) ::algocomp::AUCImprEncs(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::algocomp::AUCImprEncs::InitAsDefaultInstance(); } void InitDefaultsAUCImprEncs() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAUCImprEncsImpl); } ::google::protobuf::Metadata file_level_metadata[1]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, labels_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, weights_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, scores_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, encs_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::algocomp::AUCImprEncs, feat_size_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::algocomp::AUCImprEncs)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::algocomp::_AUCImprEncs_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "encpb/auc_impr_encs.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\031encpb/auc_impr_encs.proto\022\010algocomp\032\030e" "ncpb/encode_bunch.proto\"v\n\013AUCImprEncs\022\016" "\n\006labels\030\001 \003(\002\022\017\n\007weights\030\002 \003(\002\022\016\n\006score" "s\030\003 \003(\002\022#\n\004encs\030\004 \003(\0132\025.algocomp.EncodeB" "unch\022\021\n\tfeat_size\030\005 \001(\003B\036\n\010algocompB\rAUC" "ImprEncsPbP\001\370\001\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 223); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "encpb/auc_impr_encs.proto", &protobuf_RegisterTypes); ::protobuf_encpb_2fencode_5fbunch_2eproto::AddDescriptors(); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_encpb_2fauc_5fimpr_5fencs_2eproto namespace algocomp { // =================================================================== void AUCImprEncs::InitAsDefaultInstance() { } void AUCImprEncs::clear_encs() { encs_.Clear(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AUCImprEncs::kLabelsFieldNumber; const int AUCImprEncs::kWeightsFieldNumber; const int AUCImprEncs::kScoresFieldNumber; const int AUCImprEncs::kEncsFieldNumber; const int AUCImprEncs::kFeatSizeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AUCImprEncs::AUCImprEncs() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::InitDefaultsAUCImprEncs(); } SharedCtor(); // @@protoc_insertion_point(constructor:algocomp.AUCImprEncs) } AUCImprEncs::AUCImprEncs(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), labels_(arena), weights_(arena), scores_(arena), encs_(arena) { ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::InitDefaultsAUCImprEncs(); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:algocomp.AUCImprEncs) } AUCImprEncs::AUCImprEncs(const AUCImprEncs& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), labels_(from.labels_), weights_(from.weights_), scores_(from.scores_), encs_(from.encs_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); feat_size_ = from.feat_size_; // @@protoc_insertion_point(copy_constructor:algocomp.AUCImprEncs) } void AUCImprEncs::SharedCtor() { feat_size_ = GOOGLE_LONGLONG(0); _cached_size_ = 0; } AUCImprEncs::~AUCImprEncs() { // @@protoc_insertion_point(destructor:algocomp.AUCImprEncs) SharedDtor(); } void AUCImprEncs::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void AUCImprEncs::ArenaDtor(void* object) { AUCImprEncs* _this = reinterpret_cast< AUCImprEncs* >(object); (void)_this; } void AUCImprEncs::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void AUCImprEncs::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* AUCImprEncs::descriptor() { ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AUCImprEncs& AUCImprEncs::default_instance() { ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::InitDefaultsAUCImprEncs(); return *internal_default_instance(); } AUCImprEncs* AUCImprEncs::New(::google::protobuf::Arena* arena) const { return ::google::protobuf::Arena::CreateMessage<AUCImprEncs>(arena); } void AUCImprEncs::Clear() { // @@protoc_insertion_point(message_clear_start:algocomp.AUCImprEncs) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; labels_.Clear(); weights_.Clear(); scores_.Clear(); encs_.Clear(); feat_size_ = GOOGLE_LONGLONG(0); _internal_metadata_.Clear(); } bool AUCImprEncs::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:algocomp.AUCImprEncs) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated float labels = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_labels()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(13u /* 13 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 10u, input, this->mutable_labels()))); } else { goto handle_unusual; } break; } // repeated float weights = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_weights()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(21u /* 21 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 18u, input, this->mutable_weights()))); } else { goto handle_unusual; } break; } // repeated float scores = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_scores()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(29u /* 29 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 26u, input, this->mutable_scores()))); } else { goto handle_unusual; } break; } // repeated .algocomp.EncodeBunch encs = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_encs())); } else { goto handle_unusual; } break; } // int64 feat_size = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &feat_size_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:algocomp.AUCImprEncs) return true; failure: // @@protoc_insertion_point(parse_failure:algocomp.AUCImprEncs) return false; #undef DO_ } void AUCImprEncs::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:algocomp.AUCImprEncs) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float labels = 1; if (this->labels_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _labels_cached_byte_size_)); ::google::protobuf::internal::WireFormatLite::WriteFloatArray( this->labels().data(), this->labels_size(), output); } // repeated float weights = 2; if (this->weights_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _weights_cached_byte_size_)); ::google::protobuf::internal::WireFormatLite::WriteFloatArray( this->weights().data(), this->weights_size(), output); } // repeated float scores = 3; if (this->scores_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _scores_cached_byte_size_)); ::google::protobuf::internal::WireFormatLite::WriteFloatArray( this->scores().data(), this->scores_size(), output); } // repeated .algocomp.EncodeBunch encs = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->encs_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->encs(static_cast<int>(i)), output); } // int64 feat_size = 5; if (this->feat_size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->feat_size(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:algocomp.AUCImprEncs) } ::google::protobuf::uint8* AUCImprEncs::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:algocomp.AUCImprEncs) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float labels = 1; if (this->labels_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _labels_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->labels_, target); } // repeated float weights = 2; if (this->weights_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _weights_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->weights_, target); } // repeated float scores = 3; if (this->scores_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _scores_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->scores_, target); } // repeated .algocomp.EncodeBunch encs = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->encs_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->encs(static_cast<int>(i)), deterministic, target); } // int64 feat_size = 5; if (this->feat_size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->feat_size(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:algocomp.AUCImprEncs) return target; } size_t AUCImprEncs::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:algocomp.AUCImprEncs) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated float labels = 1; { unsigned int count = static_cast<unsigned int>(this->labels_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _labels_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated float weights = 2; { unsigned int count = static_cast<unsigned int>(this->weights_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _weights_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated float scores = 3; { unsigned int count = static_cast<unsigned int>(this->scores_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _scores_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated .algocomp.EncodeBunch encs = 4; { unsigned int count = static_cast<unsigned int>(this->encs_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->encs(static_cast<int>(i))); } } // int64 feat_size = 5; if (this->feat_size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->feat_size()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void AUCImprEncs::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:algocomp.AUCImprEncs) GOOGLE_DCHECK_NE(&from, this); const AUCImprEncs* source = ::google::protobuf::internal::DynamicCastToGenerated<const AUCImprEncs>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:algocomp.AUCImprEncs) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:algocomp.AUCImprEncs) MergeFrom(*source); } } void AUCImprEncs::MergeFrom(const AUCImprEncs& from) { // @@protoc_insertion_point(class_specific_merge_from_start:algocomp.AUCImprEncs) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; labels_.MergeFrom(from.labels_); weights_.MergeFrom(from.weights_); scores_.MergeFrom(from.scores_); encs_.MergeFrom(from.encs_); if (from.feat_size() != 0) { set_feat_size(from.feat_size()); } } void AUCImprEncs::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:algocomp.AUCImprEncs) if (&from == this) return; Clear(); MergeFrom(from); } void AUCImprEncs::CopyFrom(const AUCImprEncs& from) { // @@protoc_insertion_point(class_specific_copy_from_start:algocomp.AUCImprEncs) if (&from == this) return; Clear(); MergeFrom(from); } bool AUCImprEncs::IsInitialized() const { return true; } void AUCImprEncs::Swap(AUCImprEncs* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { AUCImprEncs* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void AUCImprEncs::UnsafeArenaSwap(AUCImprEncs* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void AUCImprEncs::InternalSwap(AUCImprEncs* other) { using std::swap; labels_.InternalSwap(&other->labels_); weights_.InternalSwap(&other->weights_); scores_.InternalSwap(&other->scores_); encs_.InternalSwap(&other->encs_); swap(feat_size_, other->feat_size_); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata AUCImprEncs::GetMetadata() const { protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_encpb_2fauc_5fimpr_5fencs_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace algocomp // @@protoc_insertion_point(global_scope)
38.001597
168
0.702215
[ "object" ]
8d71b26ddb211cfc2bbebc46473fc5ef71ffb6be
1,373
cxx
C++
smtk/model/Chain.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/model/Chain.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/model/Chain.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/model/Chain.h" #include "smtk/model/Edge.h" #include "smtk/model/EntityRefArrangementOps.h" #include "smtk/model/VertexUse.h" namespace smtk { namespace model { /**\brief Return the high-dimensional cell whose interior is bounded by this shell. * */ Edge Chain::edge() const { return this->ShellEntity::boundingCell().as<Edge>(); } /**\brief Return the face-uses composing this shell. * */ VertexUses Chain::vertexUses() const { return this->ShellEntity::uses<VertexUses>(); } /**\brief Return the parent shell of this shell (or an invalid shell if unbounded). * */ Chain Chain::containingChain() const { return this->ShellEntity::containingShellEntity().as<Chain>(); } /**\brief Return the child shells of this shell, if any. * */ Chains Chain::containedChains() const { return this->ShellEntity::containedShellEntities<Chains>(); } } // namespace model } // namespace smtk
24.963636
83
0.638747
[ "model" ]
8d740c21e1c137812fceee2c50fcfca23fc9d8b9
14,829
cpp
C++
src/clientmanager.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/clientmanager.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/clientmanager.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "clientmanager.h" #include <X11/Xlib.h> #include <algorithm> #include <string> #include "attribute.h" #include "client.h" #include "completion.h" #include "decoration.h" #include "ewmh.h" #include "globals.h" #include "ipc-protocol.h" #include "monitor.h" #include "monitormanager.h" #include "mousemanager.h" #include "root.h" #include "rulemanager.h" #include "stack.h" #include "tag.h" #include "tagmanager.h" #include "utils.h" #include "xconnection.h" using std::endl; using std::function; using std::string; using std::vector; ClientManager::ClientManager() : focus(*this, "focus") , dragged(*this, "dragged") , theme(nullptr) , settings(nullptr) , ewmh(nullptr) { } ClientManager::~ClientManager() { // make all clients visible at their original floating position for (auto c : clients_) { auto r = c.second->float_size_; auto window = c.second->x11Window(); XMoveResizeWindow(g_display, window, r.x, r.y, r.width, r.height); XReparentWindow(g_display, window, g_root, r.x, r.y); ewmh->updateFrameExtents(window, 0,0,0,0); XMapWindow(g_display, window); delete c.second; } } void ClientManager::injectDependencies(Settings* s, Theme* t, Ewmh* e) { settings = s; theme = t; ewmh = e; } Client* ClientManager::client(Window window) { auto entry = clients_.find(window); if (entry != clients_.end()) { return entry->second; } return {}; } /** * \brief Resolve a window description to a client * * \param str Describes the window: "" means the focused one, "urgent" * resolves to a arbitrary urgent window, "0x..." just * resolves to the given window given its hexadecimal window id, * a decimal number its decimal window id. * \return Pointer to the resolved client, or null, if client not found */ Client* ClientManager::client(const string &identifier) { if (identifier.empty()) { return focus(); } if (identifier == "urgent") { for (auto c : clients_) { if (c.second->urgent_) { return c.second; } } return {}; // no urgent client found } try { Window win = Converter<WindowID>::parse(identifier); return client(win); } catch (...) { return nullptr; } } //! the completion-counterpart of ClientManager::client() void ClientManager::completeClients(Completion& complete) { complete.full("urgent"); for (const auto& it : clients_) { complete.full(Converter<WindowID>::str(it.first)); } } void ClientManager::add(Client* client) { clients_[client->window_] = client; client->needsRelayout.connect(needsRelayout); client->floating_.changed().connect([this,client]() { this->floatingStateChanged.emit(client); }); addChild(client, client->window_id_str); } void ClientManager::setDragged(Client* client) { if (dragged()) { dragged()->dragged_ = false; } dragged = client; if (dragged()) { dragged()->dragged_ = true; } } void ClientManager::remove(Window window) { removeChild(*clients_[window]->window_id_str); clients_.erase(window); } Client* ClientManager::manage_client(Window win, bool visible_already, bool force_unmanage, function<void(ClientChanges&)> additionalRules) { if (is_herbstluft_window(g_display, win)) { // ignore our own window return nullptr; } if (client(win)) { // if the client is managed already return nullptr; } // init client auto client = new Client(win, visible_already, *this); client->listen_for_events(); Monitor* m = get_current_monitor(); // apply rules ClientChanges changes = applyDefaultRules(client->window_); if (additionalRules) { additionalRules(changes); } changes = Root::get()->rules()->evaluateRules(client, changes); if (!changes.manage || force_unmanage) { // map it... just to be sure XMapWindow(g_display, win); delete client; return {}; } if (!changes.tag_name.empty()) { HSTag* tag = find_tag(changes.tag_name.c_str()); if (tag) { client->setTag(tag); } } if (!changes.monitor_name.empty()) { Monitor *monitor = string_to_monitor(changes.monitor_name.c_str()); if (monitor) { // a valid tag was not already found, use the target monitor's tag if (!client->tag()) { client->setTag(monitor->tag); } // a tag was already found, display it on the target monitor, but // only if switchtag is set else if (changes.switchtag) { monitor_set_tag(monitor, client->tag()); } } } // important that this happens befor the insertion to a tag setSimpleClientAttributes(client, changes); // actually manage it client->dec->createWindow(); client->fuzzy_fix_initial_position(); add(client); // insert to layout if (!client->tag()) { client->setTag(m->tag); } // insert window to the stack client->slice = Slice::makeClientSlice(client); client->tag()->insertClientSlice(client); // insert window to the tag client->tag()->insertClient(client, changes.tree_index, changes.focus); tag_set_flags_dirty(); if (changes.fullscreen.has_value()) { client->fullscreen_ = changes.fullscreen.value(); } else { client->fullscreen_ = ewmh->isFullscreenSet(client->window_); } ewmh->updateWindowState(client); // add client after setting the correct tag for the new client // this ensures a panel can read the tag property correctly at this point ewmh->addClient(client->window_); client->make_full_client(); Monitor* monitor = find_monitor_with_tag(client->tag()); if (monitor) { if (monitor != get_current_monitor() && changes.focus && changes.switchtag) { monitor_set_tag(get_current_monitor(), client->tag()); } monitor->evaluateClientPlacement(client, changes.floatplacement); // TODO: monitor_apply_layout() maybe is called twice here if it // already is called by monitor_set_tag() monitor->applyLayout(); client->set_visible(true); } else { if (changes.focus && changes.switchtag) { monitor_set_tag(get_current_monitor(), client->tag()); get_current_monitor()->evaluateClientPlacement(client, changes.floatplacement); client->set_visible(true); } else { // if the client is not directly displayed on any monitor, // take the current monitor get_current_monitor()->evaluateClientPlacement(client, changes.floatplacement); } } client->send_configure(); // TODO: make this better Root::get()->mouse->grab_client_buttons(client, false); return client; } //! apply some built in rules that reflect the EWMH specification //! and regarding sensible single-window floating settings ClientChanges ClientManager::applyDefaultRules(Window win) { ClientChanges changes; const int windowType = ewmh->getWindowType(win); vector<int> unmanaged= { NetWmWindowTypeDesktop, NetWmWindowTypeDock, }; if (std::find(unmanaged.begin(), unmanaged.end(), windowType) != unmanaged.end()) { changes.manage = False; } vector<int> floated = { NetWmWindowTypeToolbar, NetWmWindowTypeMenu, NetWmWindowTypeUtility, NetWmWindowTypeSplash, NetWmWindowTypeDialog, NetWmWindowTypeDropdownMenu, NetWmWindowTypePopupMenu, NetWmWindowTypeTooltip, NetWmWindowTypeNotification, NetWmWindowTypeCombo, NetWmWindowTypeDnd, }; if (std::find(floated.begin(), floated.end(), windowType) != floated.end()) { changes.floating = True; } if (ewmh->X().getTransientForHint(win).has_value()) { changes.floating = true; } return changes; } /** apply simple attribute based client changes. We do not apply 'fullscreen' here because * its value defaults to the client's ewmh property and is handled in applyRulesCmd() and manage_client() differently. */ void ClientManager::setSimpleClientAttributes(Client* client, const ClientChanges& changes) { if (changes.floating.has_value()) { client->floating_ = changes.floating.value(); } if (changes.pseudotile.has_value()) { client->pseudotile_ = changes.pseudotile.value(); } if (changes.ewmhNotify.has_value()) { client->ewmhnotify_ = changes.ewmhNotify.value(); } if (changes.ewmhRequests.has_value()) { client->ewmhrequests_ = changes.ewmhRequests.value(); } if (changes.keyMask.has_value()) { client->keyMask_ = changes.keyMask.value(); } if (changes.keysInactive.has_value()) { client->keysInactive_ = changes.keysInactive.value(); } } int ClientManager::applyRulesCmd(Input input, Output output) { string winid; if (!(input >> winid)) { return HERBST_NEED_MORE_ARGS; } if (winid == "--all") { MonitorManager* monitors = Root::get()->monitors(); monitors->lock(); // avoid unnecessary redraws int status = 0; for (const auto& it : clients_) { status = std::max(status, applyRules(it.second, output, false)); } monitors->unlock(); return status; } else { Client* client = this->client(winid); if (!client) { output << "No such (managed) client: " << winid << "\n"; return HERBST_INVALID_ARGUMENT; } return applyRules(client, output); } } //! apply all rules for the given client. if focus=on and changeFocus=true, //! then the client is focused int ClientManager::applyRules(Client* client, Output output, bool changeFocus) { ClientChanges changes; changes.focus = client == focus(); changes = Root::get()->rules()->evaluateRules(client, changes); if (changes.manage == false) { // only make unmanaging clients possible as soon as it is // possible to make them managed again output << "Unmanaging clients not yet possible.\n"; return HERBST_INVALID_ARGUMENT; } // do the simple attributes first setSimpleClientAttributes(client, changes); if (changes.fullscreen.has_value()) { client->fullscreen_ = changes.fullscreen.value(); } HSTag* tag = nullptr; Monitor* monitor = nullptr; bool switch_tag = false; // in the following, we do the same decisions in the same order as in manage_client(); // the only difference is, that we only set the above variables and execute the decisions // later if (!changes.tag_name.empty()) { tag = find_tag(changes.tag_name.c_str()); } if (!changes.monitor_name.empty()) { monitor = string_to_monitor(changes.monitor_name.c_str()); if (monitor) { // a valid tag was not already found, use the target monitor's tag if (!tag) { tag = monitor->tag; } // a tag was already found, display it on the target monitor, but // only if switchtag is set else if (changes.switchtag) { switch_tag = true; } } } if (tag || !changes.tree_index.empty()) { if (!tag) { tag = client->tag(); } TagManager* tagman = Root::get()->tags(); tagman->moveClient(client, tag, changes.tree_index, changes.focus); } else if (changes.focus && (client != focus()) && changeFocus) { // focus the client client->tag()->focusClient(client); Root::get()->monitors->relayoutTag(client->tag()); } if (monitor && switch_tag && tag) { monitor_set_tag(monitor, tag); } return 0; } void ClientManager::applyRulesCompletion(Completion& complete) { if (complete == 0) { complete.full("--all"); completeClients(complete); } else { complete.none(); } } void ClientManager::unmap_notify(Window win) { auto client = this->client(win); if (!client) { return; } if (!client->ignore_unmapnotify()) { force_unmanage(client); } } void ClientManager::force_unmanage(Client* client) { if (dragged() == client) { dragged = nullptr; Root::get()->mouse->mouse_stop_drag(); } if (client->tag() && client->slice) { client->tag()->stack->removeSlice(client->slice); } // remove from tag client->tag()->removeClient(client); // ignore events from it XSelectInput(g_display, client->window_, 0); //XUngrabButton(g_display, AnyButton, AnyModifier, win); // permanently remove it XUnmapWindow(g_display, client->decorationWindow()); XReparentWindow(g_display, client->window_, g_root, 0, 0); client->clear_properties(); HSTag* tag = client->tag(); // and arrange monitor after the client has been removed from the stack needsRelayout.emit(tag); ewmh->removeClient(client->window_); tag_set_flags_dirty(); // delete client this->remove(client->window_); delete client; } int ClientManager::clientSetAttribute(string attribute, Input input, Output output) { string value = input.empty() ? "toggle" : input.front(); Client* c = get_current_client(); if (c) { Attribute* a = c->attribute(attribute); if (!a) { return HERBST_UNKNOWN_ERROR; } string error_message = a->change(value); if (!error_message.empty()) { output << input.command() << ": illegal argument \"" << value << "\": " << error_message << endl; return HERBST_INVALID_ARGUMENT; } } return 0; } int ClientManager::pseudotile_cmd(Input input, Output output) { return clientSetAttribute("pseudotile", input, output); } int ClientManager::fullscreen_cmd(Input input, Output output) { return clientSetAttribute("fullscreen", input, output); } void ClientManager::pseudotile_complete(Completion& complete) { fullscreen_complete(complete); } void ClientManager::fullscreen_complete(Completion& complete) { if (complete == 0) { // we want this command to have a completion, even if no client // is focused at the moment. bool value = true; Converter<bool>::complete(complete, &value); } else { complete.none(); } }
30.575258
118
0.620406
[ "vector" ]
8d74d9a674b7cc21d0a2ae687eef89eb02a0db2d
35,515
cpp
C++
B2G/gecko/extensions/gio/nsGIOProtocolHandler.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/extensions/gio/nsGIOProtocolHandler.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/extensions/gio/nsGIOProtocolHandler.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* vim:set ts=2 sw=2 et cindent: */ /* 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/. */ /* * This code is based on original Mozilla gnome-vfs extension. It implements * input stream provided by GVFS/GIO. */ #include "mozilla/ModuleUtils.h" #include "nsIPrefService.h" #include "nsIPrefBranch.h" #include "nsIObserver.h" #include "nsThreadUtils.h" #include "nsProxyRelease.h" #include "nsIStringBundle.h" #include "nsIStandardURL.h" #include "nsMimeTypes.h" #include "nsNetUtil.h" #include "mozilla/Monitor.h" #include <gio/gio.h> #define MOZ_GIO_SCHEME "moz-gio" #define MOZ_GIO_SUPPORTED_PROTOCOLS "network.gio.supported-protocols" //----------------------------------------------------------------------------- // NSPR_LOG_MODULES=gio:5 #ifdef PR_LOGGING static PRLogModuleInfo *sGIOLog; #define LOG(args) PR_LOG(sGIOLog, PR_LOG_DEBUG, args) #else #define LOG(args) #endif //----------------------------------------------------------------------------- static nsresult MapGIOResult(gint code) { switch (code) { case G_IO_ERROR_NOT_FOUND: return NS_ERROR_FILE_NOT_FOUND; // shows error case G_IO_ERROR_INVALID_ARGUMENT: return NS_ERROR_INVALID_ARG; case G_IO_ERROR_NOT_SUPPORTED: return NS_ERROR_NOT_AVAILABLE; case G_IO_ERROR_NO_SPACE: return NS_ERROR_FILE_NO_DEVICE_SPACE; case G_IO_ERROR_READ_ONLY: return NS_ERROR_FILE_READ_ONLY; case G_IO_ERROR_PERMISSION_DENIED: return NS_ERROR_FILE_ACCESS_DENIED; // wrong password/login case G_IO_ERROR_CLOSED: return NS_BASE_STREAM_CLOSED; // was EOF case G_IO_ERROR_NOT_DIRECTORY: return NS_ERROR_FILE_NOT_DIRECTORY; case G_IO_ERROR_PENDING: return NS_ERROR_IN_PROGRESS; case G_IO_ERROR_EXISTS: return NS_ERROR_FILE_ALREADY_EXISTS; case G_IO_ERROR_IS_DIRECTORY: return NS_ERROR_FILE_IS_DIRECTORY; case G_IO_ERROR_NOT_MOUNTED: return NS_ERROR_NOT_CONNECTED; // shows error case G_IO_ERROR_HOST_NOT_FOUND: return NS_ERROR_UNKNOWN_HOST; // shows error case G_IO_ERROR_CANCELLED: return NS_ERROR_ABORT; case G_IO_ERROR_NOT_EMPTY: return NS_ERROR_FILE_DIR_NOT_EMPTY; case G_IO_ERROR_FILENAME_TOO_LONG: return NS_ERROR_FILE_NAME_TOO_LONG; case G_IO_ERROR_INVALID_FILENAME: return NS_ERROR_FILE_INVALID_PATH; case G_IO_ERROR_TIMED_OUT: return NS_ERROR_NET_TIMEOUT; // shows error case G_IO_ERROR_WOULD_BLOCK: return NS_BASE_STREAM_WOULD_BLOCK; case G_IO_ERROR_FAILED_HANDLED: return NS_ERROR_ABORT; // Cancel on login dialog /* unhandled: G_IO_ERROR_NOT_REGULAR_FILE, G_IO_ERROR_NOT_SYMBOLIC_LINK, G_IO_ERROR_NOT_MOUNTABLE_FILE, G_IO_ERROR_TOO_MANY_LINKS, G_IO_ERROR_ALREADY_MOUNTED, G_IO_ERROR_CANT_CREATE_BACKUP, G_IO_ERROR_WRONG_ETAG, G_IO_ERROR_WOULD_RECURSE, G_IO_ERROR_BUSY, G_IO_ERROR_WOULD_MERGE, G_IO_ERROR_TOO_MANY_OPEN_FILES */ // Make GCC happy default: return NS_ERROR_FAILURE; } return NS_ERROR_FAILURE; } static nsresult MapGIOResult(GError *result) { if (!result) return NS_OK; else return MapGIOResult(result->code); } /** Return values for mount operation. * These enums are used as mount operation return values. */ typedef enum { MOUNT_OPERATION_IN_PROGRESS, /** \enum operation in progress */ MOUNT_OPERATION_SUCCESS, /** \enum operation successful */ MOUNT_OPERATION_FAILED /** \enum operation not successful */ } MountOperationResult; //----------------------------------------------------------------------------- /** * Sort function compares according to file type (directory/file) * and alphabethical order * @param a pointer to GFileInfo object to compare * @param b pointer to GFileInfo object to compare * @return -1 when first object should be before the second, 0 when equal, * +1 when second object should be before the first */ static gint FileInfoComparator(gconstpointer a, gconstpointer b) { GFileInfo *ia = ( GFileInfo *) a; GFileInfo *ib = ( GFileInfo *) b; if (g_file_info_get_file_type(ia) == G_FILE_TYPE_DIRECTORY && g_file_info_get_file_type(ib) != G_FILE_TYPE_DIRECTORY) return -1; if (g_file_info_get_file_type(ib) == G_FILE_TYPE_DIRECTORY && g_file_info_get_file_type(ia) != G_FILE_TYPE_DIRECTORY) return 1; return strcasecmp(g_file_info_get_name(ia), g_file_info_get_name(ib)); } /* Declaration of mount callback functions */ static void mount_enclosing_volume_finished (GObject *source_object, GAsyncResult *res, gpointer user_data); static void mount_operation_ask_password (GMountOperation *mount_op, const char *message, const char *default_user, const char *default_domain, GAskPasswordFlags flags, gpointer user_data); //----------------------------------------------------------------------------- class nsGIOInputStream : public nsIInputStream { public: NS_DECL_ISUPPORTS NS_DECL_NSIINPUTSTREAM nsGIOInputStream(const nsCString &uriSpec) : mSpec(uriSpec) , mChannel(nullptr) , mHandle(nullptr) , mStream(nullptr) , mBytesRemaining(UINT64_MAX) , mStatus(NS_OK) , mDirList(nullptr) , mDirListPtr(nullptr) , mDirBufCursor(0) , mDirOpen(false) , mMonitorMountInProgress("GIOInputStream::MountFinished") { } ~nsGIOInputStream() { Close(); } void SetChannel(nsIChannel *channel) { // We need to hold an owning reference to our channel. This is done // so we can access the channel's notification callbacks to acquire // a reference to a nsIAuthPrompt if we need to handle an interactive // mount operation. // // However, the channel can only be accessed on the main thread, so // we have to be very careful with ownership. Moreover, it doesn't // support threadsafe addref/release, so proxying is the answer. // // Also, it's important to note that this likely creates a reference // cycle since the channel likely owns this stream. This reference // cycle is broken in our Close method. NS_ADDREF(mChannel = channel); } void SetMountResult(MountOperationResult result, gint error_code); private: nsresult DoOpen(); nsresult DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead); nsresult SetContentTypeOfChannel(const char *contentType); nsresult MountVolume(); nsresult DoOpenDirectory(); nsresult DoOpenFile(GFileInfo *info); nsCString mSpec; nsIChannel *mChannel; // manually refcounted GFile *mHandle; GFileInputStream *mStream; uint64_t mBytesRemaining; nsresult mStatus; GList *mDirList; GList *mDirListPtr; nsCString mDirBuf; uint32_t mDirBufCursor; bool mDirOpen; MountOperationResult mMountRes; mozilla::Monitor mMonitorMountInProgress; gint mMountErrorCode; }; /** * Set result of mount operation and notify monitor waiting for results. * This method is called in main thread as long as it is used only * in mount_enclosing_volume_finished function. * @param result Result of mount operation */ void nsGIOInputStream::SetMountResult(MountOperationResult result, gint error_code) { mozilla::MonitorAutoLock mon(mMonitorMountInProgress); mMountRes = result; mMountErrorCode = error_code; mon.Notify(); } /** * Start mount operation and wait in loop until it is finished. This method is * called from thread which is trying to read from location. */ nsresult nsGIOInputStream::MountVolume() { GMountOperation* mount_op = g_mount_operation_new(); g_signal_connect (mount_op, "ask-password", G_CALLBACK (mount_operation_ask_password), mChannel); mMountRes = MOUNT_OPERATION_IN_PROGRESS; /* g_file_mount_enclosing_volume uses a dbus request to mount the volume. Callback mount_enclosing_volume_finished is called in main thread (not this thread on which this method is called). */ g_file_mount_enclosing_volume(mHandle, G_MOUNT_MOUNT_NONE, mount_op, NULL, mount_enclosing_volume_finished, this); mozilla::MonitorAutoLock mon(mMonitorMountInProgress); /* Waiting for finish of mount operation thread */ while (mMountRes == MOUNT_OPERATION_IN_PROGRESS) mon.Wait(); g_object_unref(mount_op); if (mMountRes == MOUNT_OPERATION_FAILED) { return MapGIOResult(mMountErrorCode); } else { return NS_OK; } } /** * Create list of infos about objects in opened directory * Return: NS_OK when list obtained, otherwise error code according * to failed operation. */ nsresult nsGIOInputStream::DoOpenDirectory() { GError *error = NULL; GFileEnumerator *f_enum = g_file_enumerate_children(mHandle, "standard::*,time::*", G_FILE_QUERY_INFO_NONE, NULL, &error); if (!f_enum) { nsresult rv = MapGIOResult(error); g_warning("Cannot read from directory: %s", error->message); g_error_free(error); return rv; } // fill list of file infos GFileInfo *info = g_file_enumerator_next_file(f_enum, NULL, &error); while (info) { mDirList = g_list_append(mDirList, info); info = g_file_enumerator_next_file(f_enum, NULL, &error); } g_object_unref(f_enum); if (error) { g_warning("Error reading directory content: %s", error->message); nsresult rv = MapGIOResult(error); g_error_free(error); return rv; } mDirOpen = true; // Sort list of file infos by using FileInfoComparator function mDirList = g_list_sort(mDirList, FileInfoComparator); mDirListPtr = mDirList; // Write base URL (make sure it ends with a '/') mDirBuf.Append("300: "); mDirBuf.Append(mSpec); if (mSpec.get()[mSpec.Length() - 1] != '/') mDirBuf.Append('/'); mDirBuf.Append('\n'); // Write column names mDirBuf.Append("200: filename content-length last-modified file-type\n"); // Write charset (assume UTF-8) // XXX is this correct? mDirBuf.Append("301: UTF-8\n"); SetContentTypeOfChannel(APPLICATION_HTTP_INDEX_FORMAT); return NS_OK; } /** * Create file stream and set mime type for channel * @param info file info used to determine mime type * @return NS_OK when file stream created successfuly, error code otherwise */ nsresult nsGIOInputStream::DoOpenFile(GFileInfo *info) { GError *error = NULL; mStream = g_file_read(mHandle, NULL, &error); if (!mStream) { nsresult rv = MapGIOResult(error); g_warning("Cannot read from file: %s", error->message); g_error_free(error); return rv; } const char * content_type = g_file_info_get_content_type(info); if (content_type) { char *mime_type = g_content_type_get_mime_type(content_type); if (mime_type) { if (strcmp(mime_type, APPLICATION_OCTET_STREAM) != 0) { SetContentTypeOfChannel(mime_type); } g_free(mime_type); } } else { g_warning("Missing content type."); } mBytesRemaining = g_file_info_get_size(info); // Update the content length attribute on the channel. We do this // synchronously without proxying. This hack is not as bad as it looks! mChannel->SetContentLength(mBytesRemaining); return NS_OK; } /** * Start file open operation, mount volume when needed and according to file type * create file output stream or read directory content. * @return NS_OK when file or directory opened successfully, error code otherwise */ nsresult nsGIOInputStream::DoOpen() { nsresult rv; GError *error = NULL; NS_ASSERTION(mHandle == nullptr, "already open"); mHandle = g_file_new_for_uri( mSpec.get() ); GFileInfo *info = g_file_query_info(mHandle, "standard::*", G_FILE_QUERY_INFO_NONE, NULL, &error); if (error) { if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_MOUNTED) { // location is not yet mounted, try to mount g_error_free(error); if (NS_IsMainThread()) return NS_ERROR_NOT_CONNECTED; error = NULL; rv = MountVolume(); if (rv != NS_OK) { return rv; } // get info again info = g_file_query_info(mHandle, "standard::*", G_FILE_QUERY_INFO_NONE, NULL, &error); // second try to get file info from remote files after media mount if (!info) { g_warning("Unable to get file info: %s", error->message); rv = MapGIOResult(error); g_error_free(error); return rv; } } else { g_warning("Unable to get file info: %s", error->message); rv = MapGIOResult(error); g_error_free(error); return rv; } } // Get file type to handle directories and file differently GFileType f_type = g_file_info_get_file_type(info); if (f_type == G_FILE_TYPE_DIRECTORY) { // directory rv = DoOpenDirectory(); } else if (f_type != G_FILE_TYPE_UNKNOWN) { // file rv = DoOpenFile(info); } else { g_warning("Unable to get file type."); rv = NS_ERROR_FILE_NOT_FOUND; } if (info) g_object_unref(info); return rv; } /** * Read content of file or create file list from directory * @param aBuf read destination buffer * @param aCount length of destination buffer * @param aCountRead number of read characters * @return NS_OK when read successfully, NS_BASE_STREAM_CLOSED when end of file, * error code otherwise */ nsresult nsGIOInputStream::DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead) { nsresult rv = NS_ERROR_NOT_AVAILABLE; if (mStream) { // file read GError *error = NULL; uint32_t bytes_read = g_input_stream_read(G_INPUT_STREAM(mStream), aBuf, aCount, NULL, &error); if (error) { rv = MapGIOResult(error); *aCountRead = 0; g_warning("Cannot read from file: %s", error->message); g_error_free(error); return rv; } *aCountRead = bytes_read; mBytesRemaining -= *aCountRead; return NS_OK; } else if (mDirOpen) { // directory read while (aCount && rv != NS_BASE_STREAM_CLOSED) { // Copy data out of our buffer uint32_t bufLen = mDirBuf.Length() - mDirBufCursor; if (bufLen) { uint32_t n = NS_MIN(bufLen, aCount); memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n); *aCountRead += n; aBuf += n; aCount -= n; mDirBufCursor += n; } if (!mDirListPtr) // Are we at the end of the directory list? { rv = NS_BASE_STREAM_CLOSED; } else if (aCount) // Do we need more data? { GFileInfo *info = (GFileInfo *) mDirListPtr->data; // Prune '.' and '..' from directory listing. const char * fname = g_file_info_get_name(info); if (fname && fname[0] == '.' && (fname[1] == '\0' || (fname[1] == '.' && fname[2] == '\0'))) { mDirListPtr = mDirListPtr->next; continue; } mDirBuf.Assign("201: "); // The "filename" field nsCString escName; nsCOMPtr<nsINetUtil> nu = do_GetService(NS_NETUTIL_CONTRACTID); if (nu && fname) { nu->EscapeString(nsDependentCString(fname), nsINetUtil::ESCAPE_URL_PATH, escName); mDirBuf.Append(escName); mDirBuf.Append(' '); } // The "content-length" field // XXX truncates size from 64-bit to 32-bit mDirBuf.AppendInt(int32_t(g_file_info_get_size(info))); mDirBuf.Append(' '); // The "last-modified" field // // NSPR promises: PRTime is compatible with time_t // we just need to convert from seconds to microseconds GTimeVal gtime; g_file_info_get_modification_time(info, &gtime); PRExplodedTime tm; PRTime pt = ((PRTime) gtime.tv_sec) * 1000000; PR_ExplodeTime(pt, PR_GMTParameters, &tm); { char buf[64]; PR_FormatTimeUSEnglish(buf, sizeof(buf), "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm); mDirBuf.Append(buf); } // The "file-type" field switch (g_file_info_get_file_type(info)) { case G_FILE_TYPE_REGULAR: mDirBuf.Append("FILE "); break; case G_FILE_TYPE_DIRECTORY: mDirBuf.Append("DIRECTORY "); break; case G_FILE_TYPE_SYMBOLIC_LINK: mDirBuf.Append("SYMBOLIC-LINK "); break; default: break; } mDirBuf.Append('\n'); mDirBufCursor = 0; mDirListPtr = mDirListPtr->next; } } } return rv; } /** * This class is used to implement SetContentTypeOfChannel. */ class nsGIOSetContentTypeEvent : public nsRunnable { public: nsGIOSetContentTypeEvent(nsIChannel *channel, const char *contentType) : mChannel(channel), mContentType(contentType) { // stash channel reference in mChannel. no AddRef here! see note // in SetContentTypeOfchannel. } NS_IMETHOD Run() { mChannel->SetContentType(mContentType); return NS_OK; } private: nsIChannel *mChannel; nsCString mContentType; }; nsresult nsGIOInputStream::SetContentTypeOfChannel(const char *contentType) { // We need to proxy this call over to the main thread. We post an // asynchronous event in this case so that we don't delay reading data, and // we know that this is safe to do since the channel's reference will be // released asynchronously as well. We trust the ordering of the main // thread's event queue to protect us against memory corruption. nsresult rv; nsCOMPtr<nsIRunnable> ev = new nsGIOSetContentTypeEvent(mChannel, contentType); if (!ev) { rv = NS_ERROR_OUT_OF_MEMORY; } else { rv = NS_DispatchToMainThread(ev); } return rv; } NS_IMPL_THREADSAFE_ISUPPORTS1(nsGIOInputStream, nsIInputStream) /** * Free all used memory and close stream. */ NS_IMETHODIMP nsGIOInputStream::Close() { if (mStream) { g_object_unref(mStream); mStream = nullptr; } if (mHandle) { g_object_unref(mHandle); mHandle = nullptr; } if (mDirList) { // Destroy the list of GIOFileInfo objects... g_list_foreach(mDirList, (GFunc) g_object_unref, nullptr); g_list_free(mDirList); mDirList = nullptr; mDirListPtr = nullptr; } if (mChannel) { nsresult rv = NS_OK; nsCOMPtr<nsIThread> thread = do_GetMainThread(); if (thread) rv = NS_ProxyRelease(thread, mChannel); NS_ASSERTION(thread && NS_SUCCEEDED(rv), "leaking channel reference"); mChannel = nullptr; } mSpec.Truncate(); // free memory // Prevent future reads from re-opening the handle. if (NS_SUCCEEDED(mStatus)) mStatus = NS_BASE_STREAM_CLOSED; return NS_OK; } /** * Return number of remaining bytes available on input * @param aResult remaining bytes */ NS_IMETHODIMP nsGIOInputStream::Available(uint64_t *aResult) { if (NS_FAILED(mStatus)) return mStatus; *aResult = mBytesRemaining; return NS_OK; } /** * Trying to read from stream. When location is not available it tries to mount it. * @param aBuf buffer to put read data * @param aCount length of aBuf * @param aCountRead number of bytes actually read */ NS_IMETHODIMP nsGIOInputStream::Read(char *aBuf, uint32_t aCount, uint32_t *aCountRead) { *aCountRead = 0; // Check if file is already opened, otherwise open it if (!mStream && !mDirOpen && mStatus == NS_OK) { mStatus = DoOpen(); if (NS_FAILED(mStatus)) { return mStatus; } } mStatus = DoRead(aBuf, aCount, aCountRead); // Check if all data has been read if (mStatus == NS_BASE_STREAM_CLOSED) return NS_OK; // Check whenever any error appears while reading return mStatus; } NS_IMETHODIMP nsGIOInputStream::ReadSegments(nsWriteSegmentFun aWriter, void *aClosure, uint32_t aCount, uint32_t *aResult) { // There is no way to implement this using GnomeVFS, but fortunately // that doesn't matter. Because we are a blocking input stream, Necko // isn't going to call our ReadSegments method. NS_NOTREACHED("nsGIOInputStream::ReadSegments"); return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsGIOInputStream::IsNonBlocking(bool *aResult) { *aResult = false; return NS_OK; } //----------------------------------------------------------------------------- /** * Called when finishing mount operation. Result of operation is set in * nsGIOInputStream. This function is called in main thread as an async request * typically from dbus. * @param source_object GFile object which requested the mount * @param res result object * @param user_data pointer to nsGIOInputStream */ static void mount_enclosing_volume_finished (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; nsGIOInputStream* istream = static_cast<nsGIOInputStream*>(user_data); g_file_mount_enclosing_volume_finish(G_FILE (source_object), res, &error); if (error) { g_warning("Mount failed: %s %d", error->message, error->code); istream->SetMountResult(MOUNT_OPERATION_FAILED, error->code); g_error_free(error); } else { istream->SetMountResult(MOUNT_OPERATION_SUCCESS, 0); } } /** * This function is called when username or password are requested from user. * This function is called in main thread as async request from dbus. * @param mount_op mount operation * @param message message to show to user * @param default_user preffered user * @param default_domain domain name * @param flags what type of information is required * @param user_data nsIChannel */ static void mount_operation_ask_password (GMountOperation *mount_op, const char *message, const char *default_user, const char *default_domain, GAskPasswordFlags flags, gpointer user_data) { nsIChannel *channel = (nsIChannel *) user_data; if (!channel) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } // We can't handle request for domain if (flags & G_ASK_PASSWORD_NEED_DOMAIN) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } nsCOMPtr<nsIAuthPrompt> prompt; NS_QueryNotificationCallbacks(channel, prompt); // If no auth prompt, then give up. We could failover to using the // WindowWatcher service, but that might defeat a consumer's purposeful // attempt to disable authentication (for whatever reason). if (!prompt) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } // Parse out the host and port... nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); if (!uri) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } nsAutoCString scheme, hostPort; uri->GetScheme(scheme); uri->GetHostPort(hostPort); // It doesn't make sense for either of these strings to be empty. What kind // of funky URI is this? if (scheme.IsEmpty() || hostPort.IsEmpty()) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } // Construct the single signon key. Altering the value of this key will // cause people's remembered passwords to be forgotten. Think carefully // before changing the way this key is constructed. nsAutoString key, realm; NS_ConvertUTF8toUTF16 dispHost(scheme); dispHost.Append(NS_LITERAL_STRING("://")); dispHost.Append(NS_ConvertUTF8toUTF16(hostPort)); key = dispHost; if (*default_domain != '\0') { // We assume the realm string is ASCII. That might be a bogus assumption, // but we have no idea what encoding GnomeVFS is using, so for now we'll // limit ourselves to ISO-Latin-1. XXX What is a better solution? realm.Append('"'); realm.Append(NS_ConvertASCIItoUTF16(default_domain)); realm.Append('"'); key.Append(' '); key.Append(realm); } // Construct the message string... // // We use Necko's string bundle here. This code really should be encapsulated // behind some Necko API, after all this code is based closely on the code in // nsHttpChannel.cpp. nsCOMPtr<nsIStringBundleService> bundleSvc = do_GetService(NS_STRINGBUNDLE_CONTRACTID); if (!bundleSvc) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } nsCOMPtr<nsIStringBundle> bundle; bundleSvc->CreateBundle("chrome://global/locale/commonDialogs.properties", getter_AddRefs(bundle)); if (!bundle) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } nsAutoString nsmessage; if (flags & G_ASK_PASSWORD_NEED_PASSWORD) { if (flags & G_ASK_PASSWORD_NEED_USERNAME) { if (!realm.IsEmpty()) { const PRUnichar *strings[] = { realm.get(), dispHost.get() }; bundle->FormatStringFromName(NS_LITERAL_STRING("EnterLoginForRealm").get(), strings, 2, getter_Copies(nsmessage)); } else { const PRUnichar *strings[] = { dispHost.get() }; bundle->FormatStringFromName(NS_LITERAL_STRING("EnterUserPasswordFor").get(), strings, 1, getter_Copies(nsmessage)); } } else { NS_ConvertUTF8toUTF16 userName(default_user); const PRUnichar *strings[] = { userName.get(), dispHost.get() }; bundle->FormatStringFromName(NS_LITERAL_STRING("EnterPasswordFor").get(), strings, 2, getter_Copies(nsmessage)); } } else { g_warning("Unknown mount operation request (flags: %x)", flags); } if (nsmessage.IsEmpty()) { g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } // Prompt the user... nsresult rv; bool retval = false; PRUnichar *user = nullptr, *pass = nullptr; if (default_user) { // user will be freed by PromptUsernameAndPassword user = ToNewUnicode(NS_ConvertUTF8toUTF16(default_user)); } if (flags & G_ASK_PASSWORD_NEED_USERNAME) { rv = prompt->PromptUsernameAndPassword(nullptr, nsmessage.get(), key.get(), nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, &user, &pass, &retval); } else { rv = prompt->PromptPassword(nullptr, nsmessage.get(), key.get(), nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, &pass, &retval); } if (NS_FAILED(rv) || !retval) { // was || user == '\0' || pass == '\0' g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); return; } /* GIO should accept UTF8 */ g_mount_operation_set_username(mount_op, NS_ConvertUTF16toUTF8(user).get()); g_mount_operation_set_password(mount_op, NS_ConvertUTF16toUTF8(pass).get()); nsMemory::Free(user); nsMemory::Free(pass); g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_HANDLED); } //----------------------------------------------------------------------------- class nsGIOProtocolHandler : public nsIProtocolHandler , public nsIObserver { public: NS_DECL_ISUPPORTS NS_DECL_NSIPROTOCOLHANDLER NS_DECL_NSIOBSERVER nsresult Init(); private: void InitSupportedProtocolsPref(nsIPrefBranch *prefs); bool IsSupportedProtocol(const nsCString &spec); nsCString mSupportedProtocols; }; NS_IMPL_ISUPPORTS2(nsGIOProtocolHandler, nsIProtocolHandler, nsIObserver) nsresult nsGIOProtocolHandler::Init() { #ifdef PR_LOGGING sGIOLog = PR_NewLogModule("gio"); #endif nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); if (prefs) { InitSupportedProtocolsPref(prefs); prefs->AddObserver(MOZ_GIO_SUPPORTED_PROTOCOLS, this, false); } return NS_OK; } void nsGIOProtocolHandler::InitSupportedProtocolsPref(nsIPrefBranch *prefs) { // Get user preferences to determine which protocol is supported. // Gvfs/GIO has a set of supported protocols like obex, network, archive, // computer, dav, cdda, gphoto2, trash, etc. Some of these seems to be // irrelevant to process by browser. By default accept only smb and sftp // protocols so far. nsresult rv = prefs->GetCharPref(MOZ_GIO_SUPPORTED_PROTOCOLS, getter_Copies(mSupportedProtocols)); if (NS_SUCCEEDED(rv)) { mSupportedProtocols.StripWhitespace(); ToLowerCase(mSupportedProtocols); } else mSupportedProtocols.Assign("smb:,sftp:"); // use defaults LOG(("gio: supported protocols \"%s\"\n", mSupportedProtocols.get())); } bool nsGIOProtocolHandler::IsSupportedProtocol(const nsCString &aSpec) { const char *specString = aSpec.get(); const char *colon = strchr(specString, ':'); if (!colon) return false; uint32_t length = colon - specString + 1; // <scheme> + ':' nsCString scheme(specString, length); char *found = PL_strcasestr(mSupportedProtocols.get(), scheme.get()); if (!found) return false; if (found[length] != ',' && found[length] != '\0') return false; return true; } NS_IMETHODIMP nsGIOProtocolHandler::GetScheme(nsACString &aScheme) { aScheme.Assign(MOZ_GIO_SCHEME); return NS_OK; } NS_IMETHODIMP nsGIOProtocolHandler::GetDefaultPort(int32_t *aDefaultPort) { *aDefaultPort = -1; return NS_OK; } NS_IMETHODIMP nsGIOProtocolHandler::GetProtocolFlags(uint32_t *aProtocolFlags) { // Is URI_STD true of all GnomeVFS URI types? *aProtocolFlags = URI_STD | URI_DANGEROUS_TO_LOAD; return NS_OK; } NS_IMETHODIMP nsGIOProtocolHandler::NewURI(const nsACString &aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **aResult) { const nsCString flatSpec(aSpec); LOG(("gio: NewURI [spec=%s]\n", flatSpec.get())); if (!aBaseURI) { // XXX Is it good to support all GIO protocols? if (!IsSupportedProtocol(flatSpec)) return NS_ERROR_UNKNOWN_PROTOCOL; int32_t colon_location = flatSpec.FindChar(':'); if (colon_location <= 0) return NS_ERROR_UNKNOWN_PROTOCOL; // Verify that GIO supports this URI scheme. bool uri_scheme_supported = false; GVfs *gvfs = g_vfs_get_default(); if (!gvfs) { g_warning("Cannot get GVfs object."); return NS_ERROR_UNKNOWN_PROTOCOL; } const gchar* const * uri_schemes = g_vfs_get_supported_uri_schemes(gvfs); while (*uri_schemes != NULL) { // While flatSpec ends with ':' the uri_scheme does not. Therefore do not // compare last character. if (StringHead(flatSpec, colon_location).Equals(*uri_schemes)) { uri_scheme_supported = true; break; } uri_schemes++; } if (!uri_scheme_supported) { return NS_ERROR_UNKNOWN_PROTOCOL; } } nsresult rv; nsCOMPtr<nsIStandardURL> url = do_CreateInstance(NS_STANDARDURL_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; rv = url->Init(nsIStandardURL::URLTYPE_STANDARD, -1, flatSpec, aOriginCharset, aBaseURI); if (NS_SUCCEEDED(rv)) rv = CallQueryInterface(url, aResult); return rv; } NS_IMETHODIMP nsGIOProtocolHandler::NewChannel(nsIURI *aURI, nsIChannel **aResult) { NS_ENSURE_ARG_POINTER(aURI); nsresult rv; nsAutoCString spec; rv = aURI->GetSpec(spec); if (NS_FAILED(rv)) return rv; nsRefPtr<nsGIOInputStream> stream = new nsGIOInputStream(spec); if (!stream) { rv = NS_ERROR_OUT_OF_MEMORY; } else { // start out assuming an unknown content-type. we'll set the content-type // to something better once we open the URI. rv = NS_NewInputStreamChannel(aResult, aURI, stream, NS_LITERAL_CSTRING(UNKNOWN_CONTENT_TYPE)); if (NS_SUCCEEDED(rv)) stream->SetChannel(*aResult); } return rv; } NS_IMETHODIMP nsGIOProtocolHandler::AllowPort(int32_t aPort, const char *aScheme, bool *aResult) { // Don't override anything. *aResult = false; return NS_OK; } NS_IMETHODIMP nsGIOProtocolHandler::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { if (strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0) { nsCOMPtr<nsIPrefBranch> prefs = do_QueryInterface(aSubject); InitSupportedProtocolsPref(prefs); } return NS_OK; } //----------------------------------------------------------------------------- #define NS_GIOPROTOCOLHANDLER_CID \ { /* ee706783-3af8-4d19-9e84-e2ebfe213480 */ \ 0xee706783, \ 0x3af8, \ 0x4d19, \ {0x9e, 0x84, 0xe2, 0xeb, 0xfe, 0x21, 0x34, 0x80} \ } NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGIOProtocolHandler, Init) NS_DEFINE_NAMED_CID(NS_GIOPROTOCOLHANDLER_CID); static const mozilla::Module::CIDEntry kVFSCIDs[] = { { &kNS_GIOPROTOCOLHANDLER_CID, false, NULL, nsGIOProtocolHandlerConstructor }, { NULL } }; static const mozilla::Module::ContractIDEntry kVFSContracts[] = { { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX MOZ_GIO_SCHEME, &kNS_GIOPROTOCOLHANDLER_CID }, { NULL } }; static const mozilla::Module kVFSModule = { mozilla::Module::kVersion, kVFSCIDs, kVFSContracts }; NSMODULE_DEFN(nsGIOModule) = &kVFSModule;
31.568889
108
0.633225
[ "object" ]
8d77318d9d3b7c64b978c1f6ab08ba1c8c2f4e17
8,798
hpp
C++
include/MasterServer/ClientKeyExchangeRequest.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/MasterServer/ClientKeyExchangeRequest.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/MasterServer/ClientKeyExchangeRequest.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: BaseMasterServerReliableResponse #include "GlobalNamespace/BaseMasterServerReliableResponse.hpp" // Including type: MasterServer.IHandshakeClientToServerMessage #include "MasterServer/IHandshakeClientToServerMessage.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: ByteArrayNetSerializable class ByteArrayNetSerializable; // Forward declaring type: PacketPool`1<T> template<typename T> class PacketPool_1; } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: MasterServer namespace MasterServer { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: MasterServer.ClientKeyExchangeRequest // [TokenAttribute] Offset: FFFFFFFF class ClientKeyExchangeRequest : public GlobalNamespace::BaseMasterServerReliableResponse/*, public MasterServer::IHandshakeClientToServerMessage*/ { public: // public readonly ByteArrayNetSerializable clientPublicKey // Size: 0x8 // Offset: 0x18 GlobalNamespace::ByteArrayNetSerializable* clientPublicKey; // Field size check static_assert(sizeof(GlobalNamespace::ByteArrayNetSerializable*) == 0x8); // Creating value type constructor for type: ClientKeyExchangeRequest ClientKeyExchangeRequest(GlobalNamespace::ByteArrayNetSerializable* clientPublicKey_ = {}) noexcept : clientPublicKey{clientPublicKey_} {} // Creating interface conversion operator: operator MasterServer::IHandshakeClientToServerMessage operator MasterServer::IHandshakeClientToServerMessage() noexcept { return *reinterpret_cast<MasterServer::IHandshakeClientToServerMessage*>(this); } // Creating conversion operator: operator GlobalNamespace::ByteArrayNetSerializable* constexpr operator GlobalNamespace::ByteArrayNetSerializable*() const noexcept { return clientPublicKey; } // Get instance field: public readonly ByteArrayNetSerializable clientPublicKey GlobalNamespace::ByteArrayNetSerializable* _get_clientPublicKey(); // Set instance field: public readonly ByteArrayNetSerializable clientPublicKey void _set_clientPublicKey(GlobalNamespace::ByteArrayNetSerializable* value); // static public PacketPool`1<MasterServer.ClientKeyExchangeRequest> get_pool() // Offset: 0x208874C static GlobalNamespace::PacketPool_1<MasterServer::ClientKeyExchangeRequest*>* get_pool(); // public MasterServer.ClientKeyExchangeRequest Init(System.Byte[] clientPublicKey) // Offset: 0x2088794 MasterServer::ClientKeyExchangeRequest* Init(::Array<uint8_t>* clientPublicKey); // public System.Void .ctor() // Offset: 0x208A6C8 // Implemented from: BaseMasterServerReliableResponse // Base method: System.Void BaseMasterServerReliableResponse::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ClientKeyExchangeRequest* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::ClientKeyExchangeRequest::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ClientKeyExchangeRequest*, creationType>())); } // public override System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x208A5E4 // Implemented from: BaseMasterServerReliableResponse // Base method: System.Void BaseMasterServerReliableResponse::Serialize(LiteNetLib.Utils.NetDataWriter writer) void Serialize(LiteNetLib::Utils::NetDataWriter* writer); // public override System.Void Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x208A620 // Implemented from: BaseMasterServerReliableResponse // Base method: System.Void BaseMasterServerReliableResponse::Deserialize(LiteNetLib.Utils.NetDataReader reader) void Deserialize(LiteNetLib::Utils::NetDataReader* reader); // public override System.Void Release() // Offset: 0x208A65C // Implemented from: BaseMasterServerReliableResponse // Base method: System.Void BaseMasterServerReliableResponse::Release() void Release(); }; // MasterServer.ClientKeyExchangeRequest #pragma pack(pop) static check_size<sizeof(ClientKeyExchangeRequest), 24 + sizeof(GlobalNamespace::ByteArrayNetSerializable*)> __MasterServer_ClientKeyExchangeRequestSizeCheck; static_assert(sizeof(ClientKeyExchangeRequest) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(MasterServer::ClientKeyExchangeRequest*, "MasterServer", "ClientKeyExchangeRequest"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::get_pool // Il2CppName: get_pool template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::PacketPool_1<MasterServer::ClientKeyExchangeRequest*>* (*)()>(&MasterServer::ClientKeyExchangeRequest::get_pool)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::ClientKeyExchangeRequest*), "get_pool", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<MasterServer::ClientKeyExchangeRequest* (MasterServer::ClientKeyExchangeRequest::*)(::Array<uint8_t>*)>(&MasterServer::ClientKeyExchangeRequest::Init)> { static const MethodInfo* get() { static auto* clientPublicKey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::ClientKeyExchangeRequest*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clientPublicKey}); } }; // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::Serialize // Il2CppName: Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::ClientKeyExchangeRequest::*)(LiteNetLib::Utils::NetDataWriter*)>(&MasterServer::ClientKeyExchangeRequest::Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::ClientKeyExchangeRequest*), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::Deserialize // Il2CppName: Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::ClientKeyExchangeRequest::*)(LiteNetLib::Utils::NetDataReader*)>(&MasterServer::ClientKeyExchangeRequest::Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::ClientKeyExchangeRequest*), "Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: MasterServer::ClientKeyExchangeRequest::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::ClientKeyExchangeRequest::*)()>(&MasterServer::ClientKeyExchangeRequest::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::ClientKeyExchangeRequest*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
59.85034
223
0.765288
[ "object", "vector" ]
8d77c65f82e84fa759c47638097aa68275601a33
41,496
cpp
C++
src/eval.cpp
Mespyr/bop
f1ca7a0e242f437905a1258ea1c7243b232f8825
[ "MIT" ]
3
2021-03-23T13:30:44.000Z
2021-03-26T06:41:36.000Z
src/eval.cpp
Mespyr/bop
f1ca7a0e242f437905a1258ea1c7243b232f8825
[ "MIT" ]
null
null
null
src/eval.cpp
Mespyr/bop
f1ca7a0e242f437905a1258ea1c7243b232f8825
[ "MIT" ]
null
null
null
#include "../include/eval.h" Node AST_Handler::next() { ptr++; if (ptr >= (int) ast.nodes.size()) { eof = true; } return ast.nodes.at(ptr-1); } object Null() { return make_object(BOP_NUMBER, "0"); } // formatting strings std::string Function_format_string(std::vector<object> objs) { std::string res; for (int i = 0; i < (int)objs.size(); i++) { res += repr(objs.at(i)); } return "'"+res+"'"; } // Math stuff ################################################################# std::string Function_add_nums(std::vector<object> objs) { double res = to_number(objs.at(0).value); for (int i = 1; i < (int)objs.size(); i++) { res += to_number(objs.at(i).value); } return std::to_string(res); } std::string Function_subtract_nums(std::vector<object> objs) { double res = to_number(objs.at(0).value); for (int i = 1; i < (int)objs.size(); i++) { res -= to_number(objs.at(i).value); } return std::to_string(res); } std::string Function_times_nums(std::vector<object> objs) { double res = to_number(objs.at(0).value); for (int i = 1; i < (int)objs.size(); i++) { res *= to_number(objs.at(i).value); } return std::to_string(res); } std::string Function_div_nums(std::vector<object> objs) { double res = to_number(objs.at(0).value); for (int i = 1; i < (int)objs.size(); i++) { res /= to_number(objs.at(i).value); } return std::to_string(res); } // ############################################################################ // Evaluate ################################################################### void Evaluator::destructive_return(std::string name, object value) { Env top = env_stack.back(); top.set_key(name, value); env_stack.pop(); env_stack.push(top); } object Evaluator::evaluate(Node node) { if (node.type == ATOM) { Atom atom = node.atom; if (atom.type == NUMBER) { return make_object(BOP_NUMBER, atom.value); } else if (atom.type == STRING) { return make_object(BOP_STRING, atom.value); } else { if (env_stack.back().has_key(atom.value)) { return env_stack.back().at_key(atom.value); } else { error_found = true; error.type = KEYWORD_ERROR; error.keyword = KeywordError{"Undefined variable '" + atom.value + "'.", atom.line}; return Null(); } } } else { if (node.nodes.front().atom.value == "println") { if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'println'.", node.nodes.front().atom.line}; } else if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'println'.", node.nodes.front().atom.line}; } object obj = evaluate(node.nodes.back()); if (error_found) { return Null(); } std::cout << repr(obj) << std::endl; return Null(); } else if (node.nodes.front().atom.value == "print") { if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'print'.", node.nodes.front().atom.line}; } else if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'print'.", node.nodes.front().atom.line}; } object obj = evaluate(node.nodes.back()); if (error_found) { return Null(); } std::cout << repr(obj); return Null(); } else if (node.nodes.front().atom.value == "let") { if ((int) node.nodes.size() > 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'let'.", node.nodes.front().atom.line}; } else if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficient number of arguments passed for 'let'.", node.nodes.front().atom.line}; } object obj = evaluate(node.nodes.back()); if (error_found) { return Null(); } if (node.nodes.at(1).atom.type != SYMBOL) { error_found = true; error.type = KEYWORD_ERROR; error.keyword = KeywordError{"Can't set variable name to non-symbol type.", node.nodes.front().atom.line}; return Null(); } Env env = env_stack.back(); env.set_key(node.nodes.at(1).atom.value, obj); env_stack.pop(); env_stack.push(env); return Null(); } else if (node.nodes.front().atom.value == "format") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'format'.", node.nodes.front().atom.line}; } std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); formatters.push_back(evaluate(n)); if (error_found) { return Null(); } } return make_object(BOP_STRING, Function_format_string(formatters)); } else if (node.nodes.front().atom.value == "+") { if ( (int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '+'.", node.nodes.front().atom.line}; return Null(); } std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); object o = evaluate(n); if (error_found) { return Null(); } if (o.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't add with non-numeric type.", node.nodes.front().atom.line}; return Null(); } formatters.push_back(o); } return make_object(BOP_NUMBER, Function_add_nums(formatters)); } else if (node.nodes.front().atom.value == "-") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '-'.", node.nodes.front().atom.line}; return Null(); } std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); object o = evaluate(n); if (error_found) { return Null(); } if (o.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't subtract with non-numeric type.", node.nodes.front().atom.line}; return Null(); } formatters.push_back(o); } return make_object(BOP_NUMBER, Function_subtract_nums(formatters)); } else if (node.nodes.front().atom.value == "*") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '*'.", node.nodes.front().atom.line}; return Null(); } std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); object o = evaluate(n); if (error_found) { return Null(); } if (o.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't multiply with non-numeric type.", node.nodes.front().atom.line}; } formatters.push_back(o); } return make_object(BOP_NUMBER, Function_times_nums(formatters)); } else if (node.nodes.front().atom.value == "/") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '/'.", node.nodes.front().atom.line}; return Null(); } std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); object o = evaluate(n); if (error_found) { return Null(); } if (o.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't divide with non-numeric type.", node.nodes.front().atom.line}; return Null(); } else if (o.value == "0") { error_found = true; error.type = DIVISION_BY_ZERO_ERROR; error.division = DivisionByZeroError{node.nodes.front().atom.line}; return Null(); } formatters.push_back(o); } return make_object(BOP_NUMBER, Function_div_nums(formatters)); } else if (node.nodes.front().atom.value == "list") { if ((int)node.nodes.size() == 1) { return make_object(BOP_LIST, ""); } else { std::vector<object> formatters; for (int i = 1; i < (int) node.nodes.size(); i++) { Node n = node.nodes.at(i); object o = evaluate(n); formatters.push_back(o); if (error_found) { return Null(); } } return make_object(BOP_LIST, "", formatters); } } else if (node.nodes.front().atom.value == "first") { if ( (int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'first'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'first'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type != BOP_LIST and obj.type != BOP_STRING) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get first value on type that isn't string or list.", node.nodes.front().atom.line}; return Null(); } if (obj.type == BOP_LIST) { if ((int)obj.list.size() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get first value from empty list.", node.nodes.front().atom.line}; return Null(); } return obj.list.front(); } else { if ((int)obj.value.length() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get first value from empty string.", node.nodes.front().atom.line}; return Null(); } return make_object(BOP_STRING, "'"+repr(obj).substr(0, 1)+"'"); } } else if (node.nodes.front().atom.value == "last") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for last'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'last'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type != BOP_LIST and obj.type != BOP_STRING) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get last value on type that isn't string or list.", node.nodes.front().atom.line}; return Null(); } if (obj.type == BOP_LIST) { if ((int)obj.list.size() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get last value from empty list.", node.nodes.front().atom.line}; return Null(); } return obj.list.back(); } else { if ((int)obj.value.length() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get last value from empty string.", node.nodes.front().atom.line}; return Null(); } std::string c = "'"; c.push_back(repr(obj).back()); c.push_back('\''); return make_object(BOP_STRING, c); } } else if (node.nodes.front().atom.value == "rest") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'rest'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'rest'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type != BOP_LIST and obj.type != BOP_STRING) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get values on type that isn't string or list.", node.nodes.front().atom.line}; return Null(); } if (obj.type == BOP_LIST) { if ((int)obj.list.size() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get the rest of a list that is empty.", node.nodes.front().atom.line}; return Null(); } std::vector<object> sub_list; for (int i = 1; i < obj.list.size(); i++) { sub_list.push_back(obj.list.at(i)); } return make_object(BOP_LIST, "", sub_list); } else { if ((int)obj.value.length() == 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Can't get the rest of a string that is empty.", node.nodes.front().atom.line}; return Null(); } return make_object(BOP_STRING, "'"+repr(obj).substr(1)+"'"); } } else if (node.nodes.front().atom.value == "nth") { if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'nth'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'nth'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } object idx = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (obj.type != BOP_LIST and obj.type != BOP_STRING) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get value from type that isn't string or list.", node.nodes.front().atom.line}; return Null(); } if (idx.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get use value that isn't number as index.", node.nodes.front().atom.line}; return Null(); } if (obj.type == BOP_LIST) { if (atoi(idx.value.c_str()) > (int)obj.list.size()-1) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx.value + " out of range.", node.nodes.front().atom.line}; return Null(); } return obj.list.at(atoi(idx.value.c_str())); } else if (obj.type == BOP_STRING) { if (atoi(idx.value.c_str()) > (int)repr(obj).length()-1) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx.value + " out of range.", node.nodes.front().atom.line}; return Null(); } int idx_ = atoi(idx.value.c_str()); std::string str = "'"; str.push_back(repr(obj).at(idx_)); str.push_back('\''); return make_object(BOP_STRING, str); } } else if (node.nodes.front().atom.value == "append") { if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'append'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'append'.", node.nodes.front().atom.line}; return Null(); } object appender = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } object obj = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (obj.type != BOP_LIST) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't append value to type that isn't list.", node.nodes.front().atom.line}; return Null(); } obj.list.push_back(appender); // std::cout << appender.value << std::endl; if (node.nodes.at(2).type == ATOM) { destructive_return(node.nodes.at(2).atom.value, obj); } return obj; } else if (node.nodes.front().atom.value == "push") { if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'push'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'push'.", node.nodes.front().atom.line}; return Null(); } object appender = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } object obj = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (obj.type != BOP_LIST) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't push value to type that isn't list.", node.nodes.front().atom.line}; return Null(); } obj.list.insert(obj.list.begin(), appender); // std::cout << appender.value << std::endl; if (node.nodes.at(2).type == ATOM) { destructive_return(node.nodes.at(2).atom.value, obj); } return obj; } else if (node.nodes.front().atom.value == "sub") { if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'sub'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 4) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'sub'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type == BOP_LIST) { object idx_start = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (idx_start.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't use value that isn't a number as the start index.", node.nodes.front().atom.line}; return Null(); } if (to_number(idx_start.value) > (int)obj.list.size() or to_number(idx_start.value) < 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx_start.value + " out of range.", node.nodes.front().atom.line}; return Null(); } if ((int)node.nodes.size() == 3) { std::vector<object> sublist(obj.list.begin() + to_number(idx_start.value), obj.list.end()); return make_object(BOP_LIST, "", sublist); } else { object idx_end = evaluate(node.nodes.at(3)); if (error_found) { return Null(); } if (idx_start.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't use value that isn't a number as the end index.", node.nodes.front().atom.line}; return Null(); } if (to_number(idx_end.value) > (int)obj.list.size()-1 or to_number(idx_end.value) < 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx_end.value + " out of range.", node.nodes.front().atom.line}; return Null(); } std::vector<object> sublist(obj.list.begin() + to_number(idx_start.value), obj.list.begin()+to_number(idx_end.value)+1); return make_object(BOP_LIST, "", sublist); } } else if (obj.type == BOP_STRING) { object idx_start = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (idx_start.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't use value that isn't a number as the start index.", node.nodes.front().atom.line}; return Null(); } if (to_number(idx_start.value) > (int)obj.value.length()-1 or to_number(idx_start.value) < 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx_start.value + " out of range.", node.nodes.front().atom.line}; return Null(); } if ((int)node.nodes.size() == 3) { return make_object(BOP_STRING, repr(obj).substr(to_number(idx_start.value))); } else { object idx_end = evaluate(node.nodes.at(3)); if (error_found) { return Null(); } if (idx_end.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't use value that isn't a number as the end index.", node.nodes.front().atom.line}; return Null(); } if (to_number(idx_end.value) > (int)obj.value.length() or to_number(idx_end.value) < 0) { error_found = true; error.type = INDEX_ERROR; error.index = IndexError{"Index " + idx_end.value + " out of range.", node.nodes.front().atom.line}; return Null(); } return make_object(BOP_STRING, "'"+repr(obj).substr(to_number(idx_start.value), to_number(idx_end.value))+"'"); } } else { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get subvalue of value that isn't of type list or string.", node.nodes.front().atom.line}; return Null(); } } else if (node.nodes.front().atom.value == "len") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for 'len'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'len'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type == BOP_LIST) { return make_object(BOP_NUMBER, std::to_string(obj.list.size())); } else if (obj.type == BOP_STRING) { return make_object(BOP_NUMBER, std::to_string(repr(obj).length())); } else { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get length from type that isn't string or list.", node.nodes.front().atom.line}; return Null(); } } else if (node.nodes.front().atom.value == "setf") { if ((int) node.nodes.size() < 4) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'setf'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 4) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'setf'.", node.nodes.front().atom.line}; return Null(); } object obj = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (obj.type != BOP_LIST and obj.type != BOP_STRING) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't set value at an index to type isn't a list or string.", node.nodes.at(1).atom.line}; return Null(); } object idx = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (idx.type != BOP_NUMBER) { error_found = true; error.type = TYPE_ERROR; error.type_ = TypeError{"Can't get index " + obj.value + " since it isn't a number.", node.nodes.at(1).atom.line}; return Null(); } object value = evaluate(node.nodes.back()); if (error_found) { return Null(); } if (obj.type == BOP_LIST) { obj.list[to_number(idx.value)] = value; } else if (obj.type == BOP_STRING) { std::string repr_string = repr(obj); repr_string.insert(to_number(idx.value), repr(value)); obj.value = "'" + repr_string + "'"; } if (node.nodes.at(1).type == ATOM) { destructive_return(node.nodes.at(1).atom.value, obj); } return obj; } else if (node.nodes.front().atom.value == "read") { if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'read'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() == 1) { std::string input; getline(std::cin, input); return make_object(BOP_STRING, "'"+input+"'"); } object obj = evaluate(node.nodes.back()); if (error_found) { return Null(); } std::cout << repr(obj); std::string input; getline(std::cin, input); return make_object(BOP_STRING, "'"+input+"'"); } else if (node.nodes.front().atom.value == "=") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '='.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for '='.", node.nodes.front().atom.line}; return Null(); } object comp1 = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } object comp2 = evaluate(node.nodes.at(2)); if (error_found) { return Null(); } if (comp1.type == comp2.type) { if (comp1.type != BOP_LIST) { if (comp1.type == BOP_NUMBER) { int n1, n2; n1 = to_number(comp1.value); n2 = to_number(comp2.value); if (n1==n2) { return make_object(BOP_NUMBER, "1"); } return Null(); } if (comp1.value == comp2.value) { return make_object(BOP_NUMBER, "1"); } return Null(); } if (comp1.list.size() != comp2.list.size()) { return Null(); } std::string value = "1"; for (int i = 0; i < (int)comp1.list.size(); i++) { object comp1_list_value = comp1.list.at(i); object comp2_list_value = comp2.list.at(i); if (comp2_list_value.type != comp1_list_value.type) { value = "0"; break; } } return make_object(BOP_NUMBER, value); } } else if (node.nodes.front().atom.value == "!") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"No arguments passed for '!'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 2) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for '!'.", node.nodes.front().atom.line}; return Null(); } object comp1 = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (comp1.type == BOP_NUMBER) { if (comp1.value == "0") { return make_object(BOP_NUMBER, "1"); } } return Null(); } else if (node.nodes.front().atom.value == "if") { if ((int) node.nodes.size() < 4) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments passed for 'if'.", node.nodes.front().atom.line}; return Null(); } else if ((int) node.nodes.size() > 4) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Too many arguments passed for 'if'.", node.nodes.front().atom.line}; return Null(); } object cond = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } if (cond.type == BOP_NUMBER) { if (cond.value != "0") { return evaluate(node.nodes.at(2)); } } else if (cond.type == BOP_LIST) { if ((int)cond.list.size() != 0) { return evaluate(node.nodes.at(2)); } } if ((int)node.nodes.size()==4) { return evaluate(node.nodes.at(3)); } return Null(); } else if (node.nodes.front().atom.value == "do") { if ((int) node.nodes.size() == 1) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Nothing passed for 'do'.", node.nodes.front().atom.line}; return Null(); } else { for (int i = 1; i < (int)node.nodes.size(); i++) { evaluate(node.nodes.at(i)); if (error_found) { return Null(); } } } } else if (node.nodes.front().atom.value == "while") { if ((int) node.nodes.size() < 3) { error_found = true; error.type = ARGUMENT_ERROR; error.arg = ArgumentError{"Insufficent number of arguments for 'while'.", node.nodes.front().atom.line}; return Null(); } else { object cond = evaluate(node.nodes.at(1)); while (cond.value != "0") { evaluate(node.nodes.back()); if (error_found) { return Null(); } cond = evaluate(node.nodes.at(1)); if (error_found) { return Null(); } } return Null(); } } else { error_found = true; error.type = KEYWORD_ERROR; error.keyword = KeywordError{"Unrecogonized keyword '" + node.nodes.front().atom.value + "'.", node.nodes.front().atom.line}; } } return Null(); } // ############################################################################
36.62489
140
0.426234
[ "object", "vector" ]
8d7910d0ea195d3c543e631f102bec292a87e842
6,986
cpp
C++
arangod/VocBase/Validators.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
arangod/VocBase/Validators.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
arangod/VocBase/Validators.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// #include "Validators.h" #include <Basics/Exceptions.h> #include <Basics/StaticStrings.h> #include <Logger/LogMacros.h> #include <tao/json/contrib/schema.hpp> #include <tao/json/jaxn/to_string.hpp> #include <validation/validation.hpp> #include <iostream> #include <tao/json/to_string.hpp> namespace arangodb { std::string const& to_string(ValidationLevel level) { switch (level) { case ValidationLevel::None: return StaticStrings::ValidationLevelNone; case ValidationLevel::New: return StaticStrings::ValidationLevelNew; case ValidationLevel::Moderate: return StaticStrings::ValidationLevelModerate; case ValidationLevel::Strict: return StaticStrings::ValidationLevelStrict; } TRI_ASSERT(false); return StaticStrings::ValidationLevelStrict; // <- avoids: reaching end of // non-void function .... } ////////////////////////////////////////////////////////////////////////////// ValidatorBase::ValidatorBase() : _level(ValidationLevel::Strict), _special(validation::SpecialProperties::None) {} ValidatorBase::ValidatorBase(VPackSlice params) : ValidatorBase() { // parse message auto msgSlice = params.get(StaticStrings::ValidationParameterMessage); if (msgSlice.isString()) { this->_message = msgSlice.copyString(); } // parse level auto levelSlice = params.get(StaticStrings::ValidationParameterLevel); if (!levelSlice.isNone() && levelSlice.isString()) { if (levelSlice.compareString(StaticStrings::ValidationLevelNone) == 0) { this->_level = ValidationLevel::None; } else if (levelSlice.compareString(StaticStrings::ValidationLevelNew) == 0) { this->_level = ValidationLevel::New; } else if (levelSlice.compareString( StaticStrings::ValidationLevelModerate) == 0) { this->_level = ValidationLevel::Moderate; } else if (levelSlice.compareString(StaticStrings::ValidationLevelStrict) == 0) { this->_level = ValidationLevel::Strict; } else { THROW_ARANGO_EXCEPTION_MESSAGE( TRI_ERROR_VALIDATION_BAD_PARAMETER, "Valid validation levels are: " + StaticStrings::ValidationLevelNone + ", " + StaticStrings::ValidationLevelNew + ", " + StaticStrings::ValidationLevelModerate + ", " + StaticStrings::ValidationLevelStrict); } } } Result ValidatorBase::validate(VPackSlice newDoc, VPackSlice oldDoc, bool isInsert, VPackOptions const* options) const { // This function performs the validation depending on operation (Insert / // Update / Replace) and requested validation level (None / Insert / New / // Strict / Moderate). if (this->_level == ValidationLevel::None) { return {}; } if (isInsert) { return this->validateOne(newDoc, options); } /* update replace case */ if (this->_level == ValidationLevel::New) { // Level NEW is for insert only. return {}; } if (this->_level == ValidationLevel::Strict) { // Changed document must be good! return validateOne(newDoc, options); } TRI_ASSERT(this->_level == ValidationLevel::Moderate); // Changed document must be good IIF the unmodified // document passed validation. auto resNew = this->validateOne(newDoc, options); if (resNew.ok()) { return {}; } if (this->validateOne(oldDoc, options).fail()) { return {}; } return resNew; } void ValidatorBase::toVelocyPack(VPackBuilder& b) const { VPackObjectBuilder guard(&b); b.add(StaticStrings::ValidationParameterMessage, VPackValue(_message)); b.add(StaticStrings::ValidationParameterLevel, VPackValue(to_string(this->_level))); b.add(StaticStrings::ValidationParameterType, VPackValue(this->type())); this->toVelocyPackDerived(b); } ///////////////////////////////////////////////////////////////////////////// ValidatorBool::ValidatorBool(VPackSlice params) : ValidatorBase(params) { _result = params.get(StaticStrings::ValidationParameterRule).getBool(); } Result ValidatorBool::validateOne(VPackSlice slice, VPackOptions const* options) const { if (_result) { return {}; } return {TRI_ERROR_VALIDATION_FAILED, _message}; } void ValidatorBool::toVelocyPackDerived(VPackBuilder& b) const { b.add(StaticStrings::ValidationParameterRule, VPackValue(_result)); } char const* ValidatorBool::type() const { return "bool"; } ///////////////////////////////////////////////////////////////////////////// ValidatorJsonSchema::ValidatorJsonSchema(VPackSlice params) : ValidatorBase(params) { auto rule = params.get(StaticStrings::ValidationParameterRule); if (!rule.isObject()) { std::string msg = "No valid schema in rule attribute given (no object): "; msg += params.toJson(); THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_VALIDATION_BAD_PARAMETER, msg); } auto taoRuleValue = validation::slice_to_value(rule); try { _schema = std::make_shared<tao::json::schema>(taoRuleValue); _builder.add(rule); } catch (std::exception const& ex) { auto valueString = tao::json::to_string(taoRuleValue, 4); auto msg = std::string("invalid object") + valueString + "exception: " + ex.what(); LOG_TOPIC("baabe", ERR, Logger::VALIDATION) << msg; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_VALIDATION_BAD_PARAMETER, msg); } } Result ValidatorJsonSchema::validateOne(VPackSlice slice, VPackOptions const* options) const { auto res = validation::validate(*_schema, _special, slice, options); if (res) { return {}; } return {TRI_ERROR_VALIDATION_FAILED, _message}; } void ValidatorJsonSchema::toVelocyPackDerived(VPackBuilder& b) const { TRI_ASSERT(!_builder.slice().isNone()); b.add(StaticStrings::ValidationParameterRule, _builder.slice()); } char const* ValidatorJsonSchema::type() const { return "json"; } } // namespace arangodb
34.756219
80
0.651589
[ "object" ]
8d7d4c736889aa75ec7621d755fbbd5a5745c778
7,970
hpp
C++
include/wila/wrappers.hpp
csiro-hydroinformatics/wila
f203dad0e10185a171480a684bc58b57e34fed12
[ "MIT" ]
1
2017-06-19T01:54:36.000Z
2017-06-19T01:54:36.000Z
include/wila/wrappers.hpp
jmp75/wila
f203dad0e10185a171480a684bc58b57e34fed12
[ "MIT" ]
6
2017-06-02T04:38:02.000Z
2018-12-12T05:45:58.000Z
include/wila/wrappers.hpp
csiro-hydroinformatics/wila
f203dad0e10185a171480a684bc58b57e34fed12
[ "MIT" ]
4
2015-09-21T01:11:33.000Z
2018-05-25T03:39:57.000Z
#pragma once #include <string> #include <vector> #include <atomic> #include <map> #include <random> #include <functional> #include "core.hpp" namespace mhcpp { namespace types { using std::string; template<typename Type, typename BaseType> static Type* As(BaseType* ptr) { return dynamic_cast<Type*>(ptr); } template<typename Type, typename BaseType> static bool Is(BaseType* ptr) { return (As<Type>(ptr) != nullptr); } template<typename Type, typename BaseType> static Type* StrictlyAs(BaseType* ptr, const string& errormsg = string(""), const string& nullargmsg = string("")) { if (ptr == nullptr) { string msgnull; if (nullargmsg == "") msgnull = "StrictlyAs: input pointer must not be null"; else msgnull = nullargmsg; throw std::logic_error(msgnull); } Type* res = dynamic_cast<Type*>(ptr); if (res == nullptr) { string msg; if (errormsg == "") msg = string("StrictlyAs: input pointer ") + typeid(BaseType*).name() + " points to object of type " + typeid(*ptr).name() + " which cannot be addressed by pointer of type " + typeid(Type*).name(); else msg = errormsg; throw std::logic_error(msg); } return res; } } namespace wrappers { template<typename HyperCubeParameterizer> class HypercubeWrapper : public HyperCubeParameterizer, public mhcpp::IHyperCubeSetBounds<double> { private: HyperCubeParameterizer* def = nullptr; public: HypercubeWrapper() { this->def = nullptr; } HypercubeWrapper(const HyperCubeParameterizer& def) { this->def = def.Clone(); } HypercubeWrapper(const HypercubeWrapper& src) { if (src.def != nullptr) this->def = src.def->Clone(); } HypercubeWrapper(HypercubeWrapper&& src) { this->def = src.def; src.def = nullptr; } virtual ~HypercubeWrapper() { if (this->def != nullptr) { delete def; def = nullptr; } } HypercubeWrapper& operator= (const HypercubeWrapper& src) { if (&src == this) { return *this; } if (src.def != nullptr) this->def = src.def->Clone(); return *this; } HypercubeWrapper& operator= (HypercubeWrapper&& src) { if (&src == this) { return *this; } this->def = src.def; src.def = nullptr; return *this; } HyperCubeParameterizer * InnerParameterizer() const { return def; } vector<string> GetVariableNames() const { //return def->GetParameterNames(); return def->GetVariableNames(); } static HypercubeWrapper WrapIfRequired(HyperCubeParameterizer * hcPtr) { if (hcPtr == nullptr) throw std::logic_error("WrapIfRequired: pointer to hypercube must not be null"); if (mhcpp::types::Is<HypercubeWrapper, HyperCubeParameterizer>(hcPtr)) return *(mhcpp::types::As<HypercubeWrapper, HyperCubeParameterizer>(hcPtr)); else return HypercubeWrapper(*hcPtr); } static HypercubeWrapper* WrapIfRequiredNewPtr(HyperCubeParameterizer * hcPtr) { if (hcPtr == nullptr) throw std::logic_error("WrapIfRequired: pointer to hypercube must not be null"); if (mhcpp::types::Is<HypercubeWrapper, HyperCubeParameterizer>(hcPtr)) return (mhcpp::types::As<HypercubeWrapper, HyperCubeParameterizer>(hcPtr)); else return new HypercubeWrapper(*hcPtr); } static HyperCubeParameterizer* UnwrapIfRequiredNewPtr(HyperCubeParameterizer * hcPtr) { HypercubeWrapper* w = mhcpp::types::As<HypercubeWrapper, HyperCubeParameterizer>(hcPtr); if (w != nullptr) return(w->InnerParameterizer()->Clone()); else return hcPtr->Clone(); } static HyperCubeParameterizer* UnwrapIfRequired(HyperCubeParameterizer * hcPtr) { HypercubeWrapper* w = mhcpp::types::As<HypercubeWrapper, HyperCubeParameterizer>(hcPtr); if (w != nullptr) return(w->InnerParameterizer()); else return hcPtr; } size_t Dimensions() const { return def->GetNumParameters(); } double GetValue(const string& variableName) const { return def->GetValue(variableName); } double GetMaxValue(const string& variableName) const { return def->GetMaxValue(variableName); } double GetMinValue(const string& variableName) const { return def->GetMinValue(variableName); } void SetValue(const string& variableName, double value) { def->SetValue(variableName, value); } void SetMinValue(const string& variableName, double value) { def->SetMinValue(variableName, value); } void SetMaxValue(const string& variableName, double value) { def->SetMaxValue(variableName, value); } void SetMinMaxValue(const string& variableName, double min, double max, double value) { SetMinValue(variableName, min); SetMaxValue(variableName, max); SetValue(variableName, value); } string GetConfigurationDescription() const { return ""; } void ApplyConfiguration(void* system) {/*Nothing?*/ } bool SupportsThreadSafeCloning() const { return def->SupportsThreadSafeCloning(); } //std::vector<std::string> GetParameterNames() const { return def->GetParameterNames(); } bool HasKey(const string &paramName) const { return def->HasKey(paramName); } size_t GetNumParameters() const { return def->GetNumParameters(); } HyperCubeParameterizer* Clone() const { return new HypercubeWrapper(*def); } static HypercubeWrapper GetCentroid(const std::vector<HypercubeWrapper>& points) { return mhcpp::GetCentroid<HypercubeWrapper>(points); } HypercubeWrapper HomotheticTransform(const HypercubeWrapper& from, double factor) { return mhcpp::HomotheticTransform<HypercubeWrapper, double>(*this, from, factor); } virtual bool IsFeasible() const { return this->def->IsWithinBounds(); } virtual string ToString() const { string s; return this->def->ToString(); //auto vnames = GetVariableNames(); //for (auto& v : vnames) // s += v + ":" + mhcpp::utils::ToString(GetValue(v)) + ", "; //return s; } }; template<typename HyperCubeParameterizer, typename ObjectiveEvaluator> class ObjectiveCalculatorWrapper : public IObjectiveEvaluator<HypercubeWrapper<HyperCubeParameterizer>> { private: bool owner = true; public: typedef HypercubeWrapper<HyperCubeParameterizer> HcWrapper; ObjectiveCalculatorWrapper() { } ObjectiveCalculatorWrapper(const ObjectiveCalculatorWrapper& src) { if (src.def != nullptr) this->def = src.def->Clone(); } ObjectiveCalculatorWrapper(ObjectiveEvaluator * objc, bool owner = true) { this->owner = owner; this->def = objc; } ObjectiveCalculatorWrapper(ObjectiveCalculatorWrapper&& src) { *this = std::move(src); } virtual ~ObjectiveCalculatorWrapper() { if (!owner) return; if (this->def != nullptr) { delete def; def = nullptr; } } ObjectiveCalculatorWrapper& operator= (ObjectiveCalculatorWrapper&& src) { if (&src == this) { return *this; } this->def = src.def; src.def = nullptr; return *this; } ObjectiveCalculatorWrapper& operator= (const ObjectiveCalculatorWrapper& src) { if (&src == this) { return *this; } if (src.def != nullptr) this->def = src.def->Clone(); return *this; } bool IsCloneable() const { return true; } IObjectiveEvaluator<HcWrapper> * Clone() const { return new ObjectiveCalculatorWrapper(*this); } IObjectiveScores<HcWrapper> EvaluateScore(const HcWrapper& parameterizer) { auto p = parameterizer.InnerParameterizer(); if (p == nullptr) throw std::logic_error("Parameterizer is a null pointer - cannot evaluate score"); double value = def->EvaluateScore(p); IObjectiveScores<HcWrapper> res(parameterizer, def->GetName(), value, def->IsMaximizable()); return res; } private: ObjectiveEvaluator * def = nullptr; }; } }
25.876623
116
0.669762
[ "object", "vector" ]
8d7f7f8e1fe480eb8373ed5dcf170e9fc75c2aba
964
cpp
C++
Leetcode - Top Interview Questions/(leetcode)SpiralMatrix.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Leetcode - Top Interview Questions/(leetcode)SpiralMatrix.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Leetcode - Top Interview Questions/(leetcode)SpiralMatrix.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ans; int c=0,i,j,n=matrix.size(),m=matrix[0].size(),p=0; while(p<n*m) { for(i=c;i<m-c-1;i++) if(matrix[c][i]!=101) ans.push_back(matrix[c][i]),matrix[c][i]=101,p++; else return ans; for(j=c;j<n-1-c;j++) if(matrix[j][m-1-c]!=101) ans.push_back(matrix[j][m-1-c]),matrix[j][m-1-c]=101,p++; else return ans; for(i=m-1-c;i>=c;i--) if(matrix[n-1-c][i]!=101) ans.push_back(matrix[n-1-c][i]),matrix[n-1-c][i]=101,p++; else return ans; for(j=n-2-c;j>c;j--) if(matrix[j][c]!=101) ans.push_back(matrix[j][c]),matrix[j][c]=101,p++; else return ans; c++; } return ans; } };
30.125
73
0.421162
[ "vector" ]
8d80a3f8d2899595b7683727ce4b1a6d84dcaf27
25,992
cpp
C++
hphp/runtime/ext/hash/hash_ripemd.cpp
OrochiProject/hhvm-verifier
4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5
[ "PHP-3.01", "Zend-2.0" ]
3
2015-04-21T12:15:53.000Z
2016-12-25T09:15:44.000Z
hphp/runtime/ext/hash/hash_ripemd.cpp
OrochiProject/hhvm-verifier
4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5
[ "PHP-3.01", "Zend-2.0" ]
1
2017-04-10T11:50:15.000Z
2017-04-10T11:50:15.000Z
hphp/runtime/ext/hash/hash_ripemd.cpp
OrochiProject/hhvm-verifier
4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5
[ "PHP-3.01", "Zend-2.0" ]
1
2015-06-16T05:47:12.000Z
2015-06-16T05:47:12.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ /* Heavily borrowed from md5.c & sha1.c of PHP archival fame Note that ripemd laughs in the face of logic and uses little endian byte ordering */ #include "hphp/runtime/ext/hash/hash_ripemd.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// typedef struct { unsigned int state[4]; /* state (ABCD) */ unsigned int count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } PHP_RIPEMD128_CTX; typedef struct { unsigned int state[5]; /* state (ABCD) */ unsigned int count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } PHP_RIPEMD160_CTX; typedef struct { unsigned int state[8]; /* state (ABCD) */ unsigned int count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } PHP_RIPEMD256_CTX; typedef struct { unsigned int state[10]; /* state (ABCD) */ unsigned int count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } PHP_RIPEMD320_CTX; hash_ripemd128::hash_ripemd128() : HashEngine(16, 64, sizeof(PHP_RIPEMD128_CTX)) { } hash_ripemd160::hash_ripemd160() : HashEngine(20, 64, sizeof(PHP_RIPEMD160_CTX)) { } hash_ripemd256::hash_ripemd256() : HashEngine(32, 64, sizeof(PHP_RIPEMD256_CTX)) { } hash_ripemd320::hash_ripemd320() : HashEngine(40, 64, sizeof(PHP_RIPEMD320_CTX)) { } /* * ripemd128 initialization. Begins a ripemd128 operation, writing * a new context. */ void hash_ripemd128::hash_init(void *context_) { PHP_RIPEMD128_CTX * context = (PHP_RIPEMD128_CTX*)context_; context->count[0] = context->count[1] = 0; /* Load magic initialization constants. */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; } /* * ripemd256 initialization. Begins a ripemd256 operation, * writing a new context. */ void hash_ripemd256::hash_init(void *context_) { PHP_RIPEMD256_CTX * context = (PHP_RIPEMD256_CTX*)context_; context->count[0] = context->count[1] = 0; /* Load magic initialization constants. */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0x76543210; context->state[5] = 0xFEDCBA98; context->state[6] = 0x89ABCDEF; context->state[7] = 0x01234567; } /* * ripemd160 initialization. Begins a ripemd160 operation, * writing a new context. */ void hash_ripemd160::hash_init(void *context_) { PHP_RIPEMD160_CTX * context = (PHP_RIPEMD160_CTX*)context_; context->count[0] = context->count[1] = 0; /* Load magic initialization constants. */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; } /* * ripemd320 initialization. Begins a ripemd320 operation, * writing a new context. */ void hash_ripemd320::hash_init(void *context_) { PHP_RIPEMD320_CTX * context = (PHP_RIPEMD320_CTX*)context_; context->count[0] = context->count[1] = 0; /* Load magic initialization constants. */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->state[5] = 0x76543210; context->state[6] = 0xFEDCBA98; context->state[7] = 0x89ABCDEF; context->state[8] = 0x01234567; context->state[9] = 0x3C2D1E0F; } /* Basic ripemd function */ #define F0(x,y,z) ((x) ^ (y) ^ (z)) #define F1(x,y,z) (((x) & (y)) | ((~(x)) & (z))) #define F2(x,y,z) (((x) | (~(y))) ^ (z)) #define F3(x,y,z) (((x) & (z)) | ((y) & (~(z)))) #define F4(x,y,z) ((x) ^ ((y) | (~(z)))) static const unsigned int K_values[5] = { 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E }; /* 128, 256, 160, 320 */ static const unsigned int KK_values[4] = { 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x00000000 }; /* 128 & 256 */ static const unsigned int KK160_values[5] = { 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000 }; /* 160 & 320 */ #define K(n) K_values[ (n) >> 4] #define KK(n) KK_values[(n) >> 4] #define KK160(n) KK160_values[(n) >> 4] static const unsigned char R[80] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }; static const unsigned char RR[80] = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }; static const unsigned char S[80] = { 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }; static const unsigned char SS[80] = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 }; #define ROLS(j, x) (((x) << S[j]) | ((x) >> (32 - S[j]))) #define ROLSS(j, x) (((x) << SS[j]) | ((x) >> (32 - SS[j]))) #define ROL(n, x) (((x) << n) | ((x) >> (32 - n))) /* Decodes input (unsigned char) into output (unsigned int). Assumes len is a multiple of 4. */ static void RIPEMDDecode(unsigned int *output, const unsigned char *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((unsigned int) input[j + 0]) | (((unsigned int) input[j + 1]) << 8) | (((unsigned int) input[j + 2]) << 16) | (((unsigned int) input[j + 3]) << 24); } /* * ripemd128 basic transformation. Transforms state based on block. */ static void RIPEMD128Transform(unsigned int state[4], const unsigned char block[64]) { unsigned int a = state[0], b = state[1], c = state[2], d = state[3]; unsigned int aa = state[0], bb = state[1], cc = state[2], dd = state[3]; unsigned int tmp, x[16]; int j; RIPEMDDecode(x, block, 64); for(j = 0; j < 16; j++) { tmp = ROLS( j, a + F0(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F3(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } for(j = 16; j < 32; j++) { tmp = ROLS( j, a + F1(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F2(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } for(j = 32; j < 48; j++) { tmp = ROLS( j, a + F2(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F1(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } for(j = 48; j < 64; j++) { tmp = ROLS( j, a + F3(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F0(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } tmp = state[1] + c + dd; state[1] = state[2] + d + aa; state[2] = state[3] + a + bb; state[3] = state[0] + b + cc; state[0] = tmp; tmp = 0; memset(x, 0, sizeof(x)); } /* ripemd128 block update operation. Continues a ripemd128 message-digest operation, processing another message block, and updating the context. */ void hash_ripemd128::hash_update(void *context_, const unsigned char *input, unsigned int inputLen) { PHP_RIPEMD128_CTX * context = (PHP_RIPEMD128_CTX*)context_; unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int) ((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((unsigned int) inputLen << 3)) < ((unsigned int) inputLen << 3)) { context->count[1]++; } context->count[1] += ((unsigned int) inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen); RIPEMD128Transform(context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) { RIPEMD128Transform(context->state, &input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy((unsigned char*) & context->buffer[index], (unsigned char*) & input[i], inputLen - i); } /* * ripemd256 basic transformation. Transforms state based on block. */ static void RIPEMD256Transform(unsigned int state[8], const unsigned char block[64]) { unsigned int a = state[0], b = state[1], c = state[2], d = state[3]; unsigned int aa = state[4], bb = state[5], cc = state[6], dd = state[7]; unsigned int tmp, x[16]; int j; RIPEMDDecode(x, block, 64); for(j = 0; j < 16; j++) { tmp = ROLS( j, a + F0(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F3(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } tmp = a; a = aa; aa = tmp; for(j = 16; j < 32; j++) { tmp = ROLS( j, a + F1(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F2(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } tmp = b; b = bb; bb = tmp; for(j = 32; j < 48; j++) { tmp = ROLS( j, a + F2(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F1(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } tmp = c; c = cc; cc = tmp; for(j = 48; j < 64; j++) { tmp = ROLS( j, a + F3(b, c, d) + x[R[j]] + K(j)); a = d; d = c; c = b; b = tmp; tmp = ROLSS(j, aa + F0(bb, cc, dd) + x[RR[j]] + KK(j)); aa = dd; dd = cc; cc = bb; bb = tmp; } tmp = d; d = dd; dd = tmp; state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += aa; state[5] += bb; state[6] += cc; state[7] += dd; tmp = 0; memset(x, 0, sizeof(x)); } /* ripemd256 block update operation. Continues a ripemd256 message-digest operation, processing another message block, and updating the context. */ void hash_ripemd256::hash_update(void *context_, const unsigned char *input, unsigned int inputLen) { PHP_RIPEMD256_CTX * context = (PHP_RIPEMD256_CTX*)context_; unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int) ((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((unsigned int) inputLen << 3)) < ((unsigned int) inputLen << 3)) { context->count[1]++; } context->count[1] += ((unsigned int) inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen); RIPEMD256Transform(context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) { RIPEMD256Transform(context->state, &input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy((unsigned char*) & context->buffer[index], (unsigned char*) & input[i], inputLen - i); } /* * ripemd160 basic transformation. Transforms state based on block. */ static void RIPEMD160Transform(unsigned int state[5], const unsigned char block[64]) { unsigned int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; unsigned int aa = state[0], bb = state[1], cc = state[2], dd = state[3], ee = state[4]; unsigned int tmp, x[16]; int j; RIPEMDDecode(x, block, 64); for(j = 0; j < 16; j++) { tmp = ROLS( j, a + F0(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F4(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } for(j = 16; j < 32; j++) { tmp = ROLS( j, a + F1(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F3(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } for(j = 32; j < 48; j++) { tmp = ROLS( j, a + F2(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F2(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } for(j = 48; j < 64; j++) { tmp = ROLS( j, a + F3(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F1(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } for(j = 64; j < 80; j++) { tmp = ROLS( j, a + F4(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F0(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = state[1] + c + dd; state[1] = state[2] + d + ee; state[2] = state[3] + e + aa; state[3] = state[4] + a + bb; state[4] = state[0] + b + cc; state[0] = tmp; tmp = 0; memset(x, 0, sizeof(x)); } /* ripemd160 block update operation. Continues a ripemd160 message-digest operation, processing another message block, and updating the context. */ void hash_ripemd160::hash_update(void *context_, const unsigned char *input, unsigned int inputLen) { PHP_RIPEMD160_CTX * context = (PHP_RIPEMD160_CTX*)context_; unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int) ((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((unsigned int) inputLen << 3)) < ((unsigned int) inputLen << 3)) { context->count[1]++; } context->count[1] += ((unsigned int) inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen); RIPEMD160Transform(context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) { RIPEMD160Transform(context->state, &input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy((unsigned char*) & context->buffer[index], (unsigned char*) & input[i], inputLen - i); } /* * ripemd320 basic transformation. Transforms state based on block. */ static void RIPEMD320Transform(unsigned int state[10], const unsigned char block[64]) { unsigned int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; unsigned int aa = state[5], bb = state[6], cc = state[7], dd = state[8], ee = state[9]; unsigned int tmp, x[16]; int j; RIPEMDDecode(x, block, 64); for(j = 0; j < 16; j++) { tmp = ROLS( j, a + F0(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F4(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = b; b = bb; bb = tmp; for(j = 16; j < 32; j++) { tmp = ROLS( j, a + F1(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F3(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = d; d = dd; dd = tmp; for(j = 32; j < 48; j++) { tmp = ROLS( j, a + F2(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F2(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = a; a = aa; aa = tmp; for(j = 48; j < 64; j++) { tmp = ROLS( j, a + F3(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F1(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = c; c = cc; cc = tmp; for(j = 64; j < 80; j++) { tmp = ROLS( j, a + F4(b, c, d) + x[R[j]] + K(j)) + e; a = e; e = d; d = ROL(10, c); c = b; b = tmp; tmp = ROLSS(j, aa + F0(bb, cc, dd) + x[RR[j]] + KK160(j)) + ee; aa = ee; ee = dd; dd = ROL(10, cc); cc = bb; bb = tmp; } tmp = e; e = ee; ee = tmp; state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; state[5] += aa; state[6] += bb; state[7] += cc; state[8] += dd; state[9] += ee; tmp = 0; memset(x, 0, sizeof(x)); } /* ripemd320 block update operation. Continues a ripemd320 message-digest operation, processing another message block, and updating the context. */ void hash_ripemd320::hash_update(void *context_, const unsigned char *input, unsigned int inputLen) { PHP_RIPEMD320_CTX * context = (PHP_RIPEMD320_CTX*)context_; unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int) ((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((unsigned int) inputLen << 3)) < ((unsigned int) inputLen << 3)) { context->count[1]++; } context->count[1] += ((unsigned int) inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen); RIPEMD320Transform(context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) { RIPEMD320Transform(context->state, &input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy((unsigned char*) & context->buffer[index], (unsigned char*) & input[i], inputLen - i); } static const unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* Encodes input (unsigned int) into output (unsigned char). Assumes len is a multiple of 4. */ static void RIPEMDEncode(unsigned char *output, unsigned int *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff); output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff); output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff); output[j + 0] = (unsigned char) (input[i] & 0xff); } } /* ripemd128 finalization. Ends a ripemd128 message-digest operation, writing the message digest and zeroizing the context. */ void hash_ripemd128::hash_final(unsigned char *digest, void *context_) { PHP_RIPEMD128_CTX * context = (PHP_RIPEMD128_CTX*)context_; unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ bits[0] = (unsigned char) (context->count[0] & 0xFF); bits[1] = (unsigned char) ((context->count[0] >> 8) & 0xFF); bits[2] = (unsigned char) ((context->count[0] >> 16) & 0xFF); bits[3] = (unsigned char) ((context->count[0] >> 24) & 0xFF); bits[4] = (unsigned char) (context->count[1] & 0xFF); bits[5] = (unsigned char) ((context->count[1] >> 8) & 0xFF); bits[6] = (unsigned char) ((context->count[1] >> 16) & 0xFF); bits[7] = (unsigned char) ((context->count[1] >> 24) & 0xFF); /* Pad out to 56 mod 64. */ index = (unsigned int) ((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); hash_update(context, PADDING, padLen); /* Append length (before padding) */ hash_update(context, bits, 8); /* Store state in digest */ RIPEMDEncode(digest, context->state, 16); /* Zeroize sensitive information. */ memset((unsigned char*) context, 0, sizeof(*context)); } /* ripemd256 finalization. Ends a ripemd256 message-digest operation, writing the message digest and zeroizing the context. */ void hash_ripemd256::hash_final(unsigned char *digest, void *context_) { PHP_RIPEMD256_CTX * context = (PHP_RIPEMD256_CTX*)context_; unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ bits[0] = (unsigned char) (context->count[0] & 0xFF); bits[1] = (unsigned char) ((context->count[0] >> 8) & 0xFF); bits[2] = (unsigned char) ((context->count[0] >> 16) & 0xFF); bits[3] = (unsigned char) ((context->count[0] >> 24) & 0xFF); bits[4] = (unsigned char) (context->count[1] & 0xFF); bits[5] = (unsigned char) ((context->count[1] >> 8) & 0xFF); bits[6] = (unsigned char) ((context->count[1] >> 16) & 0xFF); bits[7] = (unsigned char) ((context->count[1] >> 24) & 0xFF); /* Pad out to 56 mod 64. */ index = (unsigned int) ((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); hash_update(context, PADDING, padLen); /* Append length (before padding) */ hash_update(context, bits, 8); /* Store state in digest */ RIPEMDEncode(digest, context->state, 32); /* Zeroize sensitive information. */ memset((unsigned char*) context, 0, sizeof(*context)); } /* ripemd160 finalization. Ends a ripemd160 message-digest operation, writing the message digest and zeroizing the context. */ void hash_ripemd160::hash_final(unsigned char *digest, void *context_) { PHP_RIPEMD160_CTX * context = (PHP_RIPEMD160_CTX*)context_; unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ bits[0] = (unsigned char) (context->count[0] & 0xFF); bits[1] = (unsigned char) ((context->count[0] >> 8) & 0xFF); bits[2] = (unsigned char) ((context->count[0] >> 16) & 0xFF); bits[3] = (unsigned char) ((context->count[0] >> 24) & 0xFF); bits[4] = (unsigned char) (context->count[1] & 0xFF); bits[5] = (unsigned char) ((context->count[1] >> 8) & 0xFF); bits[6] = (unsigned char) ((context->count[1] >> 16) & 0xFF); bits[7] = (unsigned char) ((context->count[1] >> 24) & 0xFF); /* Pad out to 56 mod 64. */ index = (unsigned int) ((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); hash_update(context, PADDING, padLen); /* Append length (before padding) */ hash_update(context, bits, 8); /* Store state in digest */ RIPEMDEncode(digest, context->state, 20); /* Zeroize sensitive information. */ memset((unsigned char*) context, 0, sizeof(*context)); } /* ripemd320 finalization. Ends a ripemd320 message-digest operation, writing the message digest and zeroizing the context. */ void hash_ripemd320::hash_final(unsigned char *digest, void *context_) { PHP_RIPEMD320_CTX * context = (PHP_RIPEMD320_CTX*)context_; unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ bits[0] = (unsigned char) (context->count[0] & 0xFF); bits[1] = (unsigned char) ((context->count[0] >> 8) & 0xFF); bits[2] = (unsigned char) ((context->count[0] >> 16) & 0xFF); bits[3] = (unsigned char) ((context->count[0] >> 24) & 0xFF); bits[4] = (unsigned char) (context->count[1] & 0xFF); bits[5] = (unsigned char) ((context->count[1] >> 8) & 0xFF); bits[6] = (unsigned char) ((context->count[1] >> 16) & 0xFF); bits[7] = (unsigned char) ((context->count[1] >> 24) & 0xFF); /* Pad out to 56 mod 64. */ index = (unsigned int) ((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); hash_update(context, PADDING, padLen); /* Append length (before padding) */ hash_update(context, bits, 8); /* Store state in digest */ RIPEMDEncode(digest, context->state, 40); /* Zeroize sensitive information. */ memset((unsigned char*) context, 0, sizeof(*context)); } /////////////////////////////////////////////////////////////////////////////// }
33.494845
132
0.541128
[ "transform" ]
8d86020f6a3f6fcc370ec3fa0c1d5b060642123a
27,951
cpp
C++
src/video_core/shader/control_flow.cpp
maierfelix/bnsh-decoder
e02ccef69780831b38fe5b31710855d9ca6a5977
[ "MIT" ]
4
2020-11-11T05:36:24.000Z
2021-12-25T05:22:09.000Z
src/video_core/shader/control_flow.cpp
maierfelix/bnsh-decoder
e02ccef69780831b38fe5b31710855d9ca6a5977
[ "MIT" ]
1
2021-01-24T00:22:38.000Z
2021-01-24T00:22:38.000Z
src/video_core/shader/control_flow.cpp
maierfelix/bnsh-decoder
e02ccef69780831b38fe5b31710855d9ca6a5977
[ "MIT" ]
3
2021-02-24T12:01:13.000Z
2021-12-14T01:37:53.000Z
// Copyright 2019 yuzu Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #include <list> #include <map> #include <set> #include <stack> #include <unordered_map> #include <vector> #include "common/assert.h" #include "common/common_types.h" #include "video_core/shader/ast.h" #include "video_core/shader/control_flow.h" #include "video_core/shader/memory_util.h" #include "video_core/shader/registry.h" #include "video_core/shader/shader_ir.h" namespace VideoCommon::Shader { namespace { using Tegra::Shader::Instruction; using Tegra::Shader::OpCode; constexpr s32 unassigned_branch = -2; struct Query { u32 address{}; std::stack<u32> ssy_stack{}; std::stack<u32> pbk_stack{}; }; struct BlockStack { BlockStack() = default; explicit BlockStack(const Query& q) : ssy_stack{q.ssy_stack}, pbk_stack{q.pbk_stack} {} std::stack<u32> ssy_stack{}; std::stack<u32> pbk_stack{}; }; template <typename T, typename... Args> BlockBranchInfo MakeBranchInfo(Args&&... args) { static_assert(std::is_convertible_v<T, BranchData>); return std::make_shared<BranchData>(T(std::forward<Args>(args)...)); } bool BlockBranchIsIgnored(BlockBranchInfo first) { bool ignore = false; if (std::holds_alternative<SingleBranch>(*first)) { const auto branch = std::get_if<SingleBranch>(first.get()); ignore = branch->ignore; } return ignore; } struct BlockInfo { u32 start{}; u32 end{}; bool visited{}; BlockBranchInfo branch{}; bool IsInside(const u32 address) const { return start <= address && address <= end; } }; struct CFGRebuildState { explicit CFGRebuildState(const ProgramCode& program_code, u32 start, Registry& registry) : program_code{program_code}, registry{registry}, start{start} {} const ProgramCode& program_code; Registry& registry; u32 start{}; std::vector<BlockInfo> block_info; std::list<u32> inspect_queries; std::list<Query> queries; std::unordered_map<u32, u32> registered; std::set<u32> labels; std::map<u32, u32> ssy_labels; std::map<u32, u32> pbk_labels; std::unordered_map<u32, BlockStack> stacks; ASTManager* manager{}; }; enum class BlockCollision : u32 { None, Found, Inside }; std::pair<BlockCollision, u32> TryGetBlock(CFGRebuildState& state, u32 address) { const auto& blocks = state.block_info; for (u32 index = 0; index < blocks.size(); index++) { if (blocks[index].start == address) { return {BlockCollision::Found, index}; } if (blocks[index].IsInside(address)) { return {BlockCollision::Inside, index}; } } return {BlockCollision::None, 0xFFFFFFFF}; } struct ParseInfo { BlockBranchInfo branch_info{}; u32 end_address{}; }; BlockInfo& CreateBlockInfo(CFGRebuildState& state, u32 start, u32 end) { auto& it = state.block_info.emplace_back(); it.start = start; it.end = end; const u32 index = static_cast<u32>(state.block_info.size() - 1); state.registered.insert({start, index}); return it; } Pred GetPredicate(u32 index, bool negated) { return static_cast<Pred>(static_cast<u64>(index) + (negated ? 8ULL : 0ULL)); } enum class ParseResult : u32 { ControlCaught, BlockEnd, AbnormalFlow, }; struct BranchIndirectInfo { u32 buffer{}; u32 offset{}; u32 entries{}; s32 relative_position{}; }; struct BufferInfo { u32 index; u32 offset; }; std::optional<std::pair<s32, u64>> GetBRXInfo(const CFGRebuildState& state, u32& pos) { const Instruction instr = state.program_code[pos]; const auto opcode = OpCode::Decode(instr); if (opcode->get().GetId() != OpCode::Id::BRX) { return std::nullopt; } if (instr.brx.constant_buffer != 0) { return std::nullopt; } --pos; return std::make_pair(instr.brx.GetBranchExtend(), instr.gpr8.Value()); } template <typename Result, typename TestCallable, typename PackCallable> // requires std::predicate<TestCallable, Instruction, const OpCode::Matcher&> // requires std::invocable<PackCallable, Instruction, const OpCode::Matcher&> std::optional<Result> TrackInstruction(const CFGRebuildState& state, u32& pos, TestCallable test, PackCallable pack) { for (; pos >= state.start; --pos) { if (IsSchedInstruction(pos, state.start)) { continue; } const Instruction instr = state.program_code[pos]; const auto opcode = OpCode::Decode(instr); if (!opcode) { continue; } if (test(instr, opcode->get())) { --pos; return std::make_optional(pack(instr, opcode->get())); } } return std::nullopt; } std::optional<std::pair<BufferInfo, u64>> TrackLDC(const CFGRebuildState& state, u32& pos, u64 brx_tracked_register) { return TrackInstruction<std::pair<BufferInfo, u64>>( state, pos, [brx_tracked_register](auto instr, const auto& opcode) { return opcode.GetId() == OpCode::Id::LD_C && instr.gpr0.Value() == brx_tracked_register && instr.ld_c.type.Value() == Tegra::Shader::UniformType::Single; }, [](auto instr, const auto& opcode) { const BufferInfo info = {static_cast<u32>(instr.cbuf36.index.Value()), static_cast<u32>(instr.cbuf36.GetOffset())}; return std::make_pair(info, instr.gpr8.Value()); }); } std::optional<u64> TrackSHLRegister(const CFGRebuildState& state, u32& pos, u64 ldc_tracked_register) { return TrackInstruction<u64>(state, pos, [ldc_tracked_register](auto instr, const auto& opcode) { return opcode.GetId() == OpCode::Id::SHL_IMM && instr.gpr0.Value() == ldc_tracked_register; }, [](auto instr, const auto&) { return instr.gpr8.Value(); }); } std::optional<u32> TrackIMNMXValue(const CFGRebuildState& state, u32& pos, u64 shl_tracked_register) { return TrackInstruction<u32>(state, pos, [shl_tracked_register](auto instr, const auto& opcode) { return opcode.GetId() == OpCode::Id::IMNMX_IMM && instr.gpr0.Value() == shl_tracked_register; }, [](auto instr, const auto&) { return static_cast<u32>(instr.alu.GetSignedImm20_20() + 1); }); } std::optional<BranchIndirectInfo> TrackBranchIndirectInfo(const CFGRebuildState& state, u32 pos) { const auto brx_info = GetBRXInfo(state, pos); if (!brx_info) { return std::nullopt; } const auto [relative_position, brx_tracked_register] = *brx_info; const auto ldc_info = TrackLDC(state, pos, brx_tracked_register); if (!ldc_info) { return std::nullopt; } const auto [buffer_info, ldc_tracked_register] = *ldc_info; const auto shl_tracked_register = TrackSHLRegister(state, pos, ldc_tracked_register); if (!shl_tracked_register) { return std::nullopt; } const auto entries = TrackIMNMXValue(state, pos, *shl_tracked_register); if (!entries) { return std::nullopt; } return BranchIndirectInfo{buffer_info.index, buffer_info.offset, *entries, relative_position}; } std::pair<ParseResult, ParseInfo> ParseCode(CFGRebuildState& state, u32 address) { u32 offset = static_cast<u32>(address); const u32 end_address = static_cast<u32>(state.program_code.size()); ParseInfo parse_info{}; SingleBranch single_branch{}; const auto insert_label = [](CFGRebuildState& state, u32 address) { const auto pair = state.labels.emplace(address); if (pair.second) { state.inspect_queries.push_back(address); } }; while (true) { if (offset >= end_address) { // ASSERT_OR_EXECUTE can't be used, as it ignores the break ASSERT_MSG(false, "Shader passed the current limit!"); single_branch.address = exit_branch; single_branch.ignore = false; break; } if (state.registered.count(offset) != 0) { single_branch.address = offset; single_branch.ignore = true; break; } if (IsSchedInstruction(offset, state.start)) { offset++; continue; } const Instruction instr = {state.program_code[offset]}; const auto opcode = OpCode::Decode(instr); if (!opcode || opcode->get().GetType() != OpCode::Type::Flow) { offset++; continue; } switch (opcode->get().GetId()) { case OpCode::Id::EXIT: { const auto pred_index = static_cast<u32>(instr.pred.pred_index); single_branch.condition.predicate = GetPredicate(pred_index, instr.negate_pred != 0); if (single_branch.condition.predicate == Pred::NeverExecute) { offset++; continue; } const ConditionCode cc = instr.flow_condition_code; single_branch.condition.cc = cc; if (cc == ConditionCode::F) { offset++; continue; } single_branch.address = exit_branch; single_branch.kill = false; single_branch.is_sync = false; single_branch.is_brk = false; single_branch.ignore = false; parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::ControlCaught, parse_info}; } case OpCode::Id::BRA: { if (instr.bra.constant_buffer != 0) { return {ParseResult::AbnormalFlow, parse_info}; } const auto pred_index = static_cast<u32>(instr.pred.pred_index); single_branch.condition.predicate = GetPredicate(pred_index, instr.negate_pred != 0); if (single_branch.condition.predicate == Pred::NeverExecute) { offset++; continue; } const ConditionCode cc = instr.flow_condition_code; single_branch.condition.cc = cc; if (cc == ConditionCode::F) { offset++; continue; } const u32 branch_offset = offset + instr.bra.GetBranchTarget(); if (branch_offset == 0) { single_branch.address = exit_branch; } else { single_branch.address = branch_offset; } insert_label(state, branch_offset); single_branch.kill = false; single_branch.is_sync = false; single_branch.is_brk = false; single_branch.ignore = false; parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::ControlCaught, parse_info}; } case OpCode::Id::SYNC: { const auto pred_index = static_cast<u32>(instr.pred.pred_index); single_branch.condition.predicate = GetPredicate(pred_index, instr.negate_pred != 0); if (single_branch.condition.predicate == Pred::NeverExecute) { offset++; continue; } const ConditionCode cc = instr.flow_condition_code; single_branch.condition.cc = cc; if (cc == ConditionCode::F) { offset++; continue; } single_branch.address = unassigned_branch; single_branch.kill = false; single_branch.is_sync = true; single_branch.is_brk = false; single_branch.ignore = false; parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::ControlCaught, parse_info}; } case OpCode::Id::BRK: { const auto pred_index = static_cast<u32>(instr.pred.pred_index); single_branch.condition.predicate = GetPredicate(pred_index, instr.negate_pred != 0); if (single_branch.condition.predicate == Pred::NeverExecute) { offset++; continue; } const ConditionCode cc = instr.flow_condition_code; single_branch.condition.cc = cc; if (cc == ConditionCode::F) { offset++; continue; } single_branch.address = unassigned_branch; single_branch.kill = false; single_branch.is_sync = false; single_branch.is_brk = true; single_branch.ignore = false; parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::ControlCaught, parse_info}; } case OpCode::Id::KIL: { const auto pred_index = static_cast<u32>(instr.pred.pred_index); single_branch.condition.predicate = GetPredicate(pred_index, instr.negate_pred != 0); if (single_branch.condition.predicate == Pred::NeverExecute) { offset++; continue; } const ConditionCode cc = instr.flow_condition_code; single_branch.condition.cc = cc; if (cc == ConditionCode::F) { offset++; continue; } single_branch.address = exit_branch; single_branch.kill = true; single_branch.is_sync = false; single_branch.is_brk = false; single_branch.ignore = false; parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::ControlCaught, parse_info}; } case OpCode::Id::SSY: { const u32 target = offset + instr.bra.GetBranchTarget(); insert_label(state, target); state.ssy_labels.emplace(offset, target); break; } case OpCode::Id::PBK: { const u32 target = offset + instr.bra.GetBranchTarget(); insert_label(state, target); state.pbk_labels.emplace(offset, target); break; } case OpCode::Id::BRX: { const auto tmp = TrackBranchIndirectInfo(state, offset); if (!tmp) { LOG_WARNING(HW_GPU, "BRX Track Unsuccesful"); return {ParseResult::AbnormalFlow, parse_info}; } const auto result = *tmp; const s32 pc_target = offset + result.relative_position; std::vector<CaseBranch> branches; for (u32 i = 0; i < result.entries; i++) { auto key = state.registry.ObtainKey(result.buffer, result.offset + i * 4); if (!key) { return {ParseResult::AbnormalFlow, parse_info}; } u32 value = *key; u32 target = static_cast<u32>((value >> 3) + pc_target); insert_label(state, target); branches.emplace_back(value, target); } parse_info.end_address = offset; parse_info.branch_info = MakeBranchInfo<MultiBranch>( static_cast<u32>(instr.gpr8.Value()), std::move(branches)); return {ParseResult::ControlCaught, parse_info}; } default: break; } offset++; } single_branch.kill = false; single_branch.is_sync = false; single_branch.is_brk = false; parse_info.end_address = offset - 1; parse_info.branch_info = MakeBranchInfo<SingleBranch>( single_branch.condition, single_branch.address, single_branch.kill, single_branch.is_sync, single_branch.is_brk, single_branch.ignore); return {ParseResult::BlockEnd, parse_info}; } bool TryInspectAddress(CFGRebuildState& state) { if (state.inspect_queries.empty()) { return false; } const u32 address = state.inspect_queries.front(); state.inspect_queries.pop_front(); const auto [result, block_index] = TryGetBlock(state, address); switch (result) { case BlockCollision::Found: { return true; } case BlockCollision::Inside: { // This case is the tricky one: // We need to split the block into 2 separate blocks const u32 end = state.block_info[block_index].end; BlockInfo& new_block = CreateBlockInfo(state, address, end); BlockInfo& current_block = state.block_info[block_index]; current_block.end = address - 1; new_block.branch = std::move(current_block.branch); BlockBranchInfo forward_branch = MakeBranchInfo<SingleBranch>(); const auto branch = std::get_if<SingleBranch>(forward_branch.get()); branch->address = address; branch->ignore = true; current_block.branch = std::move(forward_branch); return true; } default: break; } const auto [parse_result, parse_info] = ParseCode(state, address); if (parse_result == ParseResult::AbnormalFlow) { // if it's AbnormalFlow, we end it as false, ending the CFG reconstruction return false; } BlockInfo& block_info = CreateBlockInfo(state, address, parse_info.end_address); block_info.branch = parse_info.branch_info; if (std::holds_alternative<SingleBranch>(*block_info.branch)) { const auto branch = std::get_if<SingleBranch>(block_info.branch.get()); if (branch->condition.IsUnconditional()) { return true; } const u32 fallthrough_address = parse_info.end_address + 1; state.inspect_queries.push_front(fallthrough_address); return true; } return true; } bool TryQuery(CFGRebuildState& state) { const auto gather_labels = [](std::stack<u32>& cc, std::map<u32, u32>& labels, BlockInfo& block) { auto gather_start = labels.lower_bound(block.start); const auto gather_end = labels.upper_bound(block.end); while (gather_start != gather_end) { cc.push(gather_start->second); ++gather_start; } }; if (state.queries.empty()) { return false; } Query& q = state.queries.front(); const u32 block_index = state.registered[q.address]; BlockInfo& block = state.block_info[block_index]; // If the block is visited, check if the stacks match, else gather the ssy/pbk // labels into the current stack and look if the branch at the end of the block // consumes a label. Schedule new queries accordingly if (block.visited) { BlockStack& stack = state.stacks[q.address]; const bool all_okay = (stack.ssy_stack.empty() || q.ssy_stack == stack.ssy_stack) && (stack.pbk_stack.empty() || q.pbk_stack == stack.pbk_stack); state.queries.pop_front(); return all_okay; } block.visited = true; state.stacks.insert_or_assign(q.address, BlockStack{q}); Query q2(q); state.queries.pop_front(); gather_labels(q2.ssy_stack, state.ssy_labels, block); gather_labels(q2.pbk_stack, state.pbk_labels, block); if (std::holds_alternative<SingleBranch>(*block.branch)) { const auto branch = std::get_if<SingleBranch>(block.branch.get()); if (!branch->condition.IsUnconditional()) { q2.address = block.end + 1; state.queries.push_back(q2); } Query conditional_query{q2}; if (branch->is_sync) { if (branch->address == unassigned_branch) { branch->address = conditional_query.ssy_stack.top(); } conditional_query.ssy_stack.pop(); } if (branch->is_brk) { if (branch->address == unassigned_branch) { branch->address = conditional_query.pbk_stack.top(); } conditional_query.pbk_stack.pop(); } conditional_query.address = branch->address; state.queries.push_back(std::move(conditional_query)); return true; } const auto multi_branch = std::get_if<MultiBranch>(block.branch.get()); for (const auto& branch_case : multi_branch->branches) { Query conditional_query{q2}; conditional_query.address = branch_case.address; state.queries.push_back(std::move(conditional_query)); } return true; } void InsertBranch(ASTManager& mm, const BlockBranchInfo& branch_info) { const auto get_expr = ([&](const Condition& cond) -> Expr { Expr result{}; if (cond.cc != ConditionCode::T) { result = MakeExpr<ExprCondCode>(cond.cc); } if (cond.predicate != Pred::UnusedIndex) { u32 pred = static_cast<u32>(cond.predicate); bool negate = false; if (pred > 7) { negate = true; pred -= 8; } Expr extra = MakeExpr<ExprPredicate>(pred); if (negate) { extra = MakeExpr<ExprNot>(extra); } if (result) { return MakeExpr<ExprAnd>(extra, result); } return extra; } if (result) { return result; } return MakeExpr<ExprBoolean>(true); }); if (std::holds_alternative<SingleBranch>(*branch_info)) { const auto branch = std::get_if<SingleBranch>(branch_info.get()); if (branch->address < 0) { if (branch->kill) { mm.InsertReturn(get_expr(branch->condition), true); return; } mm.InsertReturn(get_expr(branch->condition), false); return; } mm.InsertGoto(get_expr(branch->condition), branch->address); return; } const auto multi_branch = std::get_if<MultiBranch>(branch_info.get()); for (const auto& branch_case : multi_branch->branches) { mm.InsertGoto(MakeExpr<ExprGprEqual>(multi_branch->gpr, branch_case.cmp_value), branch_case.address); } } void DecompileShader(CFGRebuildState& state) { state.manager->Init(); for (auto label : state.labels) { state.manager->DeclareLabel(label); } for (auto& block : state.block_info) { if (state.labels.count(block.start) != 0) { state.manager->InsertLabel(block.start); } const bool ignore = BlockBranchIsIgnored(block.branch); u32 end = ignore ? block.end + 1 : block.end; state.manager->InsertBlock(block.start, end); if (!ignore) { InsertBranch(*state.manager, block.branch); } } state.manager->Decompile(); } } // Anonymous namespace std::unique_ptr<ShaderCharacteristics> ScanFlow(const ProgramCode& program_code, u32 start_address, const CompilerSettings& settings, Registry& registry) { auto result_out = std::make_unique<ShaderCharacteristics>(); if (settings.depth == CompileDepth::BruteForce) { result_out->settings.depth = CompileDepth::BruteForce; return result_out; } CFGRebuildState state{program_code, start_address, registry}; // Inspect Code and generate blocks state.labels.clear(); state.labels.emplace(start_address); state.inspect_queries.push_back(state.start); while (!state.inspect_queries.empty()) { if (!TryInspectAddress(state)) { result_out->settings.depth = CompileDepth::BruteForce; return result_out; } } bool use_flow_stack = true; bool decompiled = false; if (settings.depth != CompileDepth::FlowStack) { // Decompile Stacks state.queries.push_back(Query{state.start, {}, {}}); decompiled = true; while (!state.queries.empty()) { if (!TryQuery(state)) { decompiled = false; break; } } } use_flow_stack = !decompiled; // Sort and organize results std::sort(state.block_info.begin(), state.block_info.end(), [](const BlockInfo& a, const BlockInfo& b) -> bool { return a.start < b.start; }); if (decompiled && settings.depth != CompileDepth::NoFlowStack) { ASTManager manager{settings.depth != CompileDepth::DecompileBackwards, settings.disable_else_derivation}; state.manager = &manager; DecompileShader(state); decompiled = state.manager->IsFullyDecompiled(); if (!decompiled) { if (settings.depth == CompileDepth::FullDecompile) { LOG_CRITICAL(HW_GPU, "Failed to remove all the gotos!:"); } else { LOG_CRITICAL(HW_GPU, "Failed to remove all backward gotos!:"); } state.manager->ShowCurrentState("Of Shader"); state.manager->Clear(); } else { auto characteristics = std::make_unique<ShaderCharacteristics>(); characteristics->start = start_address; characteristics->settings.depth = settings.depth; characteristics->manager = std::move(manager); characteristics->end = state.block_info.back().end + 1; return characteristics; } } result_out->start = start_address; result_out->settings.depth = use_flow_stack ? CompileDepth::FlowStack : CompileDepth::NoFlowStack; result_out->blocks.clear(); for (auto& block : state.block_info) { ShaderBlock new_block{}; new_block.start = block.start; new_block.end = block.end; new_block.ignore_branch = BlockBranchIsIgnored(block.branch); if (!new_block.ignore_branch) { new_block.branch = block.branch; } result_out->end = std::max(result_out->end, block.end); result_out->blocks.push_back(new_block); } if (!use_flow_stack) { result_out->labels = std::move(state.labels); return result_out; } auto back = result_out->blocks.begin(); auto next = std::next(back); while (next != result_out->blocks.end()) { if (state.labels.count(next->start) == 0 && next->start == back->end + 1) { back->end = next->end; next = result_out->blocks.erase(next); continue; } back = next; ++next; } return result_out; } } // namespace VideoCommon::Shader
37.317757
99
0.595972
[ "vector" ]
8d8cde9b62d3e577c975d97255a41f7e417a575c
18,916
cpp
C++
lanelet2_python/python_api/routing.cpp
icolwell-as/Lanelet2
0e2e222352936cd70a9fab5256684a97c3091996
[ "BSD-3-Clause" ]
null
null
null
lanelet2_python/python_api/routing.cpp
icolwell-as/Lanelet2
0e2e222352936cd70a9fab5256684a97c3091996
[ "BSD-3-Clause" ]
null
null
null
lanelet2_python/python_api/routing.cpp
icolwell-as/Lanelet2
0e2e222352936cd70a9fab5256684a97c3091996
[ "BSD-3-Clause" ]
null
null
null
#include <lanelet2_routing/Route.h> #include <lanelet2_routing/RoutingGraph.h> #include <boost/python.hpp> #include "internal/converter.h" using namespace boost::python; using namespace lanelet; Optional<std::shared_ptr<lanelet::routing::Route>> getRouteWrapper(const lanelet::routing::RoutingGraph& self, const ConstLanelet& from, const ConstLanelet& to, lanelet::routing::RoutingCostId costId, bool withLaneChange) { auto route = self.getRoute(from, to, costId, withLaneChange); if (!route) { return {}; } return std::make_shared<lanelet::routing::Route>(std::move(*route)); } Optional<std::shared_ptr<lanelet::routing::Route>> getRouteViaWrapper(const lanelet::routing::RoutingGraph& self, const ConstLanelet& from, const ConstLanelets& via, const ConstLanelet& to, lanelet::routing::RoutingCostId costId, bool withLaneChange) { auto route = self.getRouteVia(from, via, to, costId, withLaneChange); if (!route) { return {}; } return std::make_shared<lanelet::routing::Route>(std::move(*route)); } routing::RoutingGraphPtr makeRoutingGraph(LaneletMap& laneletMap, const traffic_rules::TrafficRules& trafficRules, const routing::RoutingCostPtrs& routingCosts) { return routing::RoutingGraph::build(laneletMap, trafficRules, routingCosts); } routing::RoutingGraphPtr makeRoutingGraphSubmap(LaneletSubmap& laneletMap, const traffic_rules::TrafficRules& trafficRules, const routing::RoutingCostPtrs& routingCosts) { return routing::RoutingGraph::build(laneletMap, trafficRules, routingCosts); } BOOST_PYTHON_MODULE(PYTHON_API_MODULE_NAME) { // NOLINT auto trafficRules = import("lanelet2.traffic_rules"); using namespace lanelet::routing; using converters::IterableConverter; using converters::OptionalConverter; using converters::VectorToListConverter; OptionalConverter<Route>(); OptionalConverter<std::shared_ptr<Route>>(); OptionalConverter<RelationType>(); OptionalConverter<LaneletRelation>(); OptionalConverter<LaneletPath>(); VectorToListConverter<LaneletRelations>(); VectorToListConverter<RoutingCostPtrs>(); VectorToListConverter<LaneletPaths>(); // Register interable conversions. IterableConverter().fromPython<RoutingCostPtrs>(); implicitly_convertible<std::shared_ptr<RoutingCostDistance>, RoutingCostPtr>(); implicitly_convertible<std::shared_ptr<RoutingCostTravelTime>, RoutingCostPtr>(); implicitly_convertible<LaneletMapPtr, LaneletMapConstPtr>(); // Routing costs class_<RoutingCost, boost::noncopyable, std::shared_ptr<RoutingCost>>( // NOLINT "RoutingCost", "Object for calculating routing costs between lanelets", no_init); class_<RoutingCostDistance, bases<RoutingCost>, std::shared_ptr<RoutingCostDistance>>( // NOLINT "RoutingCostDistance", "Distance based routing cost calculation object", init<double, double>((arg("laneChangeCost"), arg("minLaneChangeDistance") = 0))); class_<RoutingCostTravelTime, bases<RoutingCost>, std::shared_ptr<RoutingCostTravelTime>>( // NOLINT "RoutingCostTravelTime", "Travel time based routing cost calculation object", init<double, double>((arg("laneChangeCost"), arg("minLaneChangeTime") = 0))); auto possPCost = static_cast<LaneletPaths (RoutingGraph::*)(const ConstLanelet&, double, RoutingCostId, bool) const>( &RoutingGraph::possiblePaths); auto possPLen = static_cast<LaneletPaths (RoutingGraph::*)(const ConstLanelet&, uint32_t, bool, RoutingCostId) const>( &RoutingGraph::possiblePaths); auto possPToCost = static_cast<LaneletPaths (RoutingGraph::*)(const ConstLanelet&, double, RoutingCostId, bool) const>( &RoutingGraph::possiblePathsTowards); auto possPToLen = static_cast<LaneletPaths (RoutingGraph::*)(const ConstLanelet&, uint32_t, bool, RoutingCostId) const>( &RoutingGraph::possiblePathsTowards); class_<LaneletPath>("LaneletPath", "A set of consecutive lanelets connected in straight " "directon or by lane changes", init<ConstLanelets>(arg("lanelets"))) .def("__iter__", iterator<LaneletPath>()) .def("__len__", &LaneletPath::size) .def("__getitem__", wrappers::getItem<LaneletPath>, return_internal_reference<>()) .def("getRemainingLane", +[](const LaneletPath& self, const ConstLanelet& llt) { return self.getRemainingLane(llt); }, "get the sequence of remaining lanelets without a lane change") .def(self == self) // NOLINT .def(self != self); // NOLINT class_<LaneletVisitInformation>("LaneletVisitInformation", "Object passed as input for the forEachSuccessor function of the routing graph") .add_property("lanelet", &LaneletVisitInformation::lanelet, "the currently visited lanelet") .add_property("predecessor", &LaneletVisitInformation::predecessor, "the predecessor within the shortest path") .add_property("length", &LaneletVisitInformation::length, "The length of the shortest path to this lanelet (including lanelet") .add_property("cost", &LaneletVisitInformation::cost, "The cost along the shortest path") .add_property("numLaneChanges", &LaneletVisitInformation::numLaneChanges, "The number of lane changes necessary along the shortest path"); class_<LaneletOrAreaVisitInformation>( "LaneletOrAreaVisitInformation", "Object passed as input for the forEachSuccessorIncludingAreas function of the routing graph") .add_property("laneletOrArea", &LaneletOrAreaVisitInformation::laneletOrArea, "the currently visited lanelet/area") .add_property("predecessor", &LaneletOrAreaVisitInformation::predecessor, "the predecessor within the shortest path") .add_property("length", &LaneletOrAreaVisitInformation::length, "The length of the shortest path to this lanelet (including lanelet") .add_property("cost", &LaneletOrAreaVisitInformation::cost, "The cost along the shortest path") .add_property("numLaneChanges", &LaneletOrAreaVisitInformation::numLaneChanges, "The number of lane changes necessary along the shortest path"); class_<RoutingGraph, boost::noncopyable, RoutingGraphPtr>( "RoutingGraph", "Main class of the routing module that holds routing information and can " "be queried", no_init) .def("__init__", make_constructor(makeRoutingGraph, default_call_policies(), (arg("laneletMap"), arg("trafficRules"), arg("routingCost") = defaultRoutingCosts())), "Initialization with default routing costs") .def("__init__", make_constructor(makeRoutingGraphSubmap, default_call_policies(), (arg("laneletSubmap"), arg("trafficRules"), arg("routingCost") = defaultRoutingCosts())), "Initialization from a submap") .def("getRoute", getRouteWrapper, "driving route from 'start' to 'end' lanelet", (arg("from"), arg("to"), arg("routingCostId") = 0, arg("withLaneChanges") = true)) .def("getRouteVia", getRouteViaWrapper, "driving route from 'start' to 'end' lanelet using the 'via' lanelets", (arg("from"), arg("via"), arg("to"), arg("routingCostId") = 0, arg("withLaneChanges") = true)) .def("shortestPath", &RoutingGraph::shortestPath, "shortest path between 'start' and 'end'", (arg("from"), arg("to"), arg("routingCostId") = 0)) .def("shortestPathWithVia", &RoutingGraph::shortestPathVia, "shortest path between 'start' and 'end' using intermediate points", (arg("start"), arg("via"), arg("end"), arg("routingCostId") = 0)) .def("routingRelation", &RoutingGraph::routingRelation, "relation between two lanelets excluding 'conflicting'", (arg("from"), arg("to"))) .def("following", &RoutingGraph::following, "lanelets that can be reached from this lanelet", (arg("lanelet"), arg("withLaneChanges") = false)) .def("followingRelations", &RoutingGraph::followingRelations, "relations to following lanelets", (arg("lanelet"), arg("withLaneChanges") = false)) .def("previous", &RoutingGraph::previous, "previous lanelets of this lanelet", (arg("lanelet"), arg("withLaneChanges") = false)) .def("previousRelations", &RoutingGraph::previousRelations, "relations to preceding lanelets", (arg("lanelet"), arg("withLaneChanges") = false)) .def("besides", &RoutingGraph::besides, "all reachable left and right lanelets, including lanelet, from " "left to right", (arg("lanelet"))) .def("left", &RoutingGraph::left, "left (routable)lanelet, if exists", (arg("lanelet"))) .def("right", &RoutingGraph::right, "right (routable)lanelet, if it exists", (arg("lanelet"))) .def("adjacentLeft", &RoutingGraph::adjacentLeft, "left non-routable lanelet", arg("lanelet")) .def("adjacentRight", &RoutingGraph::adjacentRight, "right non-routable lanelet", arg("lanelet")) .def("lefts", &RoutingGraph::lefts, "all left (routable) lanelets", arg("lanelet")) .def("rights", &RoutingGraph::rights, "all right (routable) lanelets", arg("lanelet")) .def("adjacentLefts", &RoutingGraph::adjacentLefts, "all left (non-routable) lanelets", arg("lanelet")) .def("adjacentRights", &RoutingGraph::adjacentRights, "all right (non-routable) lanelets", arg("lanelet")) .def("leftRelations", &RoutingGraph::leftRelations, "relations to left lanelets", arg("lanelet")) .def("rightRelations", &RoutingGraph::rightRelations, "relations to right lanelets", arg("lanelet")) .def("conflicting", &RoutingGraph::conflicting, "Conflicting lanelets", arg("lanelet")) .def("reachableSet", &RoutingGraph::reachableSet, "set of lanelets that can be reached from a given lanelet", (arg("lanelet"), arg("maxRoutingCost"), arg("RoutingCostId") = 0, arg("allowLaneChanges") = true)) .def("reachableSetTowards", &RoutingGraph::reachableSetTowards, "set of lanelets that can reach a given lanelet", (arg("lanelet"), arg("maxRoutingCost"), arg("RoutingCostId") = 0, arg("allowLaneChanges") = true)) .def("possiblePaths", possPCost, "possible paths from a given start lanelet that are 'minRoutingCost'-long", (arg("lanelet"), arg("minRoutingCost"), arg("RoutingCostId") = 0, arg("allowLaneChanges") = false, arg("routingCostId") = 0)) .def("possiblePathsTowards", possPToCost, "possible paths to a given start lanelet that are 'minRoutingCost'-long", (arg("lanelet"), arg("minRoutingCost"), arg("RoutingCostId") = 0, arg("allowLaneChanges") = false, arg("routingCostId") = 0)) .def("possiblePathsMinLen", possPLen, "possible routes from a given start lanelet that are 'minLanelets'-long", (arg("lanelet"), arg("minLanelets"), arg("allowLaneChanges") = false, arg("routingCostId") = 0)) .def("possiblePathsTowardsMinLen", possPToLen, "possible routes from a given start lanelet that are 'minLanelets'-long", (arg("lanelet"), arg("minLanelets"), arg("allowLaneChanges") = false, arg("routingCostId") = 0)) .def("forEachSuccessor", +[](RoutingGraph& self, const ConstLanelet& from, object func, bool lc, RoutingCostId costId) { self.forEachSuccessor(from, std::move(func), lc, costId); }, "calls a function on each successor of lanelet with increasing cost. The function must receives a " "LaneletVisitInformation object as input and must return a bool whether followers of the current lanelet " "should be visited as well. The function can raise an exception if an early exit is desired", (arg("lanelet"), arg("func"), arg("allowLaneChanges") = true, arg("routingCostId") = 0)) .def("forEachSuccessorIncludingAreas", +[](RoutingGraph& self, const ConstLaneletOrArea& from, object func, bool lc, RoutingCostId costId) { self.forEachSuccessorIncludingAreas(from, std::move(func), lc, costId); }, "similar to forEachSuccessor but also includes areas into the search", (arg("lanelet"), arg("func"), arg("allowLaneChanges") = true, arg("routingCostId") = 0)) .def("forEachPredecessor", +[](RoutingGraph& self, const ConstLanelet& from, object func, bool lc, RoutingCostId costId) { self.forEachPredecessor(from, std::move(func), lc, costId); }, "similar to forEachSuccessor but instead goes backwards along the routing graph", (arg("lanelet"), arg("func"), arg("allowLaneChanges") = true, arg("routingCostId") = 0)) .def("forEachPredecessorIncludingAreas", +[](RoutingGraph& self, const ConstLaneletOrArea& from, object func, bool lc, RoutingCostId costId) { self.forEachPredecessorIncludingAreas(from, std::move(func), lc, costId); }, "calls a function on each successor of lanelet. The function must receives a LaneletVisitInformation object " "as input and must return a bool whether followers of the current lanelet should be visited as well. The " "function can throw an exception if an early exit is desired", (arg("lanelet"), arg("func"), arg("allowLaneChanges") = true, arg("routingCostId") = 0)) .def("exportGraphML", +[](RoutingGraph& self, const std::string& path) { self.exportGraphML(path); }, "Export the internal graph to graphML (xml-based) file format") .def("exportGraphViz", +[](RoutingGraph& self, const std::string& path) { self.exportGraphViz(path); }, "Export the internal graph to graphViz (DOT) file format") .def("getDebugLaneletMap", &RoutingGraph::getDebugLaneletMap, "abstract lanelet map holding the information of the routing graph", (arg("routingCostId") = 0, arg("includeAdjacent") = false, arg("includeConflicting") = false)) .def("passableLaneletSubmap", &RoutingGraph::passableSubmap, "LaneletMap that includes all passable lanelets") .def("checkValidity", &RoutingGraph::checkValidity, "Performs some basic sanity checks", (arg("throwOnError") = true)); class_<LaneletRelation>("LaneletRelation") .add_property("lanelet", &LaneletRelation::lanelet) .add_property("relationType", &LaneletRelation::relationType); enum_<RelationType>("RelationType") .value("Successor", RelationType::Successor) .value("Left", RelationType::Left) .value("Right", RelationType::Right) .value("Conflicting", RelationType::Conflicting) .value("AdjacentLeft", RelationType::AdjacentLeft) .value("AdjacentRight", RelationType::AdjacentRight) .export_values(); class_<Route, boost::noncopyable, std::shared_ptr<Route>>("Route", "The famous route object that marks a route from A to B, " "including all lanelets that can be used", no_init) .def("shortestPath", &Route::shortestPath, "Returns the shortest path along this route", return_internal_reference<>()) .def("fullLane", &Route::fullLane, "Returns the complete lane a Lanelet belongs to") .def("remainingLane", &Route::remainingLane, "Returns that remaining lane a Lanelet belongs to") .def("remainingShortestPath", &Route::remainingShortestPath, "Returns all lanelets on the shortest path that follow the input lanelet") .def("length2d", &Route::length2d, "2d length of shortest path") .def("numLanes", &Route::numLanes, "Number of inidividual lanes") .def("laneletSubmap", +[](const Route& r) { return std::const_pointer_cast<LaneletSubmap>(r.laneletSubmap()); }, "laneletSubmap with all lanelets that are part of the route") .def("getDebugLaneletMap", &Route::getDebugLaneletMap, "laneletMap that represents the Lanelets of the Route and their relationship") .def("size", &Route::size, "Number of lanelets") .def("followingRelations", &Route::followingRelations, "Provides the following lanelets within the Route") .def("previousRelations", &Route::previousRelations, "Provides the previous lanelets within the Route") .def("leftRelation", &Route::leftRelation, "Provides the lanelet left of a given lanelet within the Route") .def("leftRelations", &Route::leftRelations, "*all* lanelets left of a given lanelet within the Route") .def("rightRelation", &Route::rightRelation, "Provides the lanelet right of a given lanelet within the Route") .def("rightRelations", &Route::rightRelations, "*all* lanelets right of a given lanelet within the Route") .def("conflictingInRoute", &Route::conflictingInRoute, "conflicting lanelets of a lanelet within the route") .def("conflictingInMap", &Route::conflictingInMap, "conflicting lanelets of a lanelet within all passable lanelets in the laneletMap") .def("allConflictingInMap", &Route::allConflictingInMap, "all lanelets in the map that conflict with any lanelet in the route") .def("forEachSuccessor", +[](Route& self, const ConstLanelet& from, object func) { self.forEachSuccessor(from, std::move(func)); }, "calls a function on each successor of lanelet with increasing cost. The function must receives a " "LaneletVisitInformation object as input and must return a bool whether followers of the current lanelet " "should be visited as well. The function can raise an exception if an early exit is desired", (arg("lanelet"), arg("func"))) .def("forEachPredecessor", +[](Route& self, const ConstLanelet& from, object func) { self.forEachPredecessor(from, std::move(func)); }, "similar to forEachSuccessor but instead goes backwards along the routing graph", (arg("lanelet"), arg("func"))) .def("checkValidity", &Route::checkValidity, "perform sanity check on the route"); }
67.316726
120
0.661715
[ "object" ]
8d90d7fa61f62041436a958db85f262e1c10cce4
1,556
cpp
C++
atcoder/abc102/D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc102/D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc102/D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; int N; vector<ll> A; ll solve() { assert(N >= 4); vector<ll> B; B.assign(N, 0); B[0] = A[0]; for (int i = 1; i < N; ++i) { B[i] = B[i-1] + A[i]; } vector<int> L(N, -1), R(N, -1); L[1] = 0; for (int i = 2; i < N; ++i) { L[i] = L[i-1]; while (i > L[i]) { ll sp0 = B[L[i]]; ll sq0 = B[i] - B[L[i]]; ll sp1 = B[L[i]+1]; ll sq1 = B[i] - B[L[i]+1]; if (abs(sp1 - sq1) >= abs(sp0 - sq0)) { break; } ++L[i]; } } R[N-2] = N-2; for (int i = N - 3; i >= 0; --i) { R[i] = R[i+1]; while (R[i] > i) { ll sr0 = B[R[i]] - B[i]; ll ss0 = B[N-1] - B[R[i]]; ll sr1 = B[R[i]-1] - B[i]; ll ss1 = B[N-1] - B[R[i]-1]; if (abs(sr1 - ss1) >= abs(sr0 - ss0)) { break; } --R[i]; } } ll ans = numeric_limits<ll>::max(); for (int i = 1; i + 2 < N; ++i) { ll p = B[L[i]]; ll q = B[i] - B[L[i]]; ll r = B[R[i]] - B[i]; ll s = B[N-1] - B[R[i]]; ans = min(ans, abs(max({ p , q, r, s }) - min({ p, q, r, s }))); } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> N; A.assign(N, 0); for (int i = 0; i < N; ++i) { cin >> A[i]; } cout << solve() << endl; return 0; }
21.027027
72
0.337404
[ "vector" ]
8d95dd769c1830f78e9e87f8e6d3dbdd327bcc83
534
cpp
C++
leetcode/115. Distinct Subsequences/s3.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/115. Distinct Subsequences/s3.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-08-08T18:44:24.000Z
2021-08-08T18:44:24.000Z
leetcode/115. Distinct Subsequences/s3.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
// OJ: https://leetcode.com/problems/distinct-subsequences // Author: github.com/lzl124631x // Time: O(ST) // Space: O(T) class Solution { typedef long long LL; public: int numDistinct(string s, string t) { int M = s.size(), N = t.size(); vector<LL> dp(N + 1); for (int i = M; i >= 0; --i) { for (int j = 0; j <= N; ++j) { if (i == M || j == N) dp[j] = j == N; else if (s[i] == t[j]) dp[j] += dp[j + 1]; } } return dp[0]; } };
28.105263
58
0.440075
[ "vector" ]
8d98b2328891ca3e79aa627e81efe7ea42dae687
8,518
cc
C++
src/Generator.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
src/Generator.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
src/Generator.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/time.h> #if defined(__FreeBSD__) || defined(__MACH__) || defined(__linux__) #include <sys/resource.h> #endif #include "Generator.h" #include "Utils.h" #include "Debug.h" #include "DebugMemory.h" void Generator::p_glow(int value) { if (p_history_offset == p_history_length) { if (p_history_length == p_history.length()) p_history.resize(p_history_length + 1); ++p_history_length; } p_history.set_char_at(p_history_offset++, value); } Generator::Generator(bool symmetric, int maximum_vertices_of_polygons) : Object(), p_type(symmetric ? GENERATOR_TYPE_SYMMETRIC : GENERATOR_TYPE_ORDINARY), p_scrap_no(1), p_n(0), p_m(0), p_h(0), p_minimum_polygons(5), p_maximum_vertices_of_polygons(maximum_vertices_of_polygons), p_state(GENERATOR_STATE_START_FROM_MINIMUM), p_history_length(0), p_history_offset(0) { } Generator::Generator(int n, int m, int h, int maximum_vertices_of_polygons) : Object(), p_type(GENERATOR_TYPE_TUBE), p_scrap_no(0), p_n(n), p_m(m), p_h(h), p_minimum_polygons(5), p_maximum_vertices_of_polygons(maximum_vertices_of_polygons), p_state(GENERATOR_STATE_START_FROM_MINIMUM), p_history_length(0), p_history_offset(0) { } Generator::Generator(const char* generator_formula, int maximum_vertices_of_polygons) : Object(), p_type(GENERATOR_TYPE_ORDINARY), p_scrap_no(0), p_n(0), p_m(0), p_h(0), p_minimum_polygons(5), p_maximum_vertices_of_polygons(maximum_vertices_of_polygons), p_state(GENERATOR_STATE_START_FROM_MINIMUM), p_history_length(0), p_history_offset(0) { const char* ptr = generator_formula; switch (*ptr++) { case 'A': p_scrap_no = character_to_No(*ptr++); break; case 'T': p_type = GENERATOR_TYPE_TUBE; p_n = strtol(ptr, (char**)&ptr, 10); if (*ptr == ',') ++ptr; p_m = strtol(ptr, (char**)&ptr, 10); if (*ptr == ',') ++ptr; p_h = strtol(ptr, (char**)&ptr, 10); break; case 'S': p_type = GENERATOR_TYPE_SYMMETRIC; p_scrap_no = character_to_No(*ptr++); break; default: p_type = GENERATOR_TYPE_ILLEGAL; break; } if (*ptr == '-') ++ptr; while (1) { if (*ptr == '\0') break; int No = digits10x10_to_No(ptr); int count = digits26x7_to_No(ptr); for (int i = 0; i < count; ++i) p_glow(No); } p_history_offset = 0; if (p_history_length > 0) p_state = GENERATOR_STATE_START_SPECIFIED; } Generator::Generator(const Generator& you) : Object(you), p_type(you.p_type), p_scrap_no(you.p_scrap_no), p_n(you.p_n), p_m(you.p_m), p_h(you.p_h), p_minimum_polygons(you.p_minimum_polygons), p_maximum_vertices_of_polygons(you.p_maximum_vertices_of_polygons), p_state(you.p_state), p_history_length(you.p_history_length), p_history_offset(you.p_history_offset), p_history(you.p_history) { } Generator& Generator::operator = (const Generator& you) { if (this != &you) { p_type = you.p_type; p_scrap_no = you.p_scrap_no; p_n = you.p_n; p_m = you.p_m; p_h = you.p_h; p_minimum_polygons = you.p_minimum_polygons; p_maximum_vertices_of_polygons = you.p_maximum_vertices_of_polygons; p_state = you.p_state; p_history_length = you.p_history_length; p_history_offset = you.p_history_offset; p_history = you.p_history; } return *this; } Generator::~Generator() { } void Generator::print_detail() const { MyString buffer; get_generator_formula(buffer); printf("%s\n", (char*)buffer); } void Generator::print_progress(int length) const { if (p_history_offset <= length) { MyString buffer; get_generator_formula(buffer, false); #if defined(__FreeBSD__) || defined(__MACH__) || defined(__linux__) struct rusage ru; if (getrusage(RUSAGE_SELF, &ru) == 0) { int sec; int usec; sec = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec; usec = ru.ru_utime.tv_usec + ru.ru_stime.tv_usec; if (usec >= 1000000) { sec++; usec -= 1000000; } printf("pg$ %s %f\n", (char*)buffer, sec + (double)usec / 1000000.0); } else #endif printf("pg$ %s\n", (char*)buffer); } } int Generator::glow_step() { if (p_history_offset >= p_history_length - 1) { if (p_history_length == p_history.length()) p_history.resize(p_history_length + 1); p_state = GENERATOR_STATE_START_FROM_MINIMUM; } else p_state = GENERATOR_STATE_START_SPECIFIED; #if defined(DEBUG_CONSTRUCTION_ALGORITHM) printf("@@@ glow_step() = %d history_offset = %d\n", p_history[p_history_offset], p_history_offset); printf("@@@ "); print_detail(); printf("@@@ now history_offset = %d\n", p_history_offset + 1); #endif return p_history[p_history_offset++]; } int Generator::history() { if (p_history_offset == p_history_length) return -1; return p_history[p_history_offset++]; } bool Generator::is_there_next_branch() const { if (p_state != GENERATOR_STATE_RUNNING) return true; if (p_history[p_history_offset] < p_maximum_vertices_of_polygons) return true; return false; } void Generator::next_branch() { #if defined(DEBUG_CONSTRUCTION_ALGORITHM) printf("@@@ next_branch() history_offset = %d\n", p_history_offset); #endif switch (p_state) { case GENERATOR_STATE_START_SPECIFIED: break; case GENERATOR_STATE_START_FROM_MINIMUM: p_history.set_char_at(p_history_offset, p_minimum_polygons); p_history_length = p_history_offset + 1; break; case GENERATOR_STATE_RUNNING: default: p_history[p_history_offset]++; p_history_length = p_history_offset + 1; break; } p_state = GENERATOR_STATE_RUNNING; } bool Generator::next_tree() { #if defined(DEBUG_CONSTRUCTION_ALGORITHM) printf("@@@ next_tree()\n"); #endif p_history_offset = p_history_length - 1; while (1) { p_history[p_history_offset]++; if (p_history[p_history_offset] <= p_maximum_vertices_of_polygons) { p_history_offset = 0; p_state = GENERATOR_STATE_START_SPECIFIED; return true; } else { if (p_history_length == 1) return false; --p_history_length; p_history_offset = p_history_length - 1; } } } bool Generator::next_by_rollback() { p_history_offset = p_history_length - 1; while (1) { p_history[p_history_offset]++; if (p_history[p_history_offset] <= p_maximum_vertices_of_polygons) { p_state = GENERATOR_STATE_START_SPECIFIED; #if defined(DEBUG_CONSTRUCTION_ALGORITHM) printf("@@@ next_by_rollback()\n@@@ now history_offset = %d\n", p_history_offset); #endif return true; } else { if (p_history_length == 1) return false; --p_history_length; p_history_offset = p_history_length - 1; } } } void Generator::get_generator_formula(MyString& buffer, bool compress) const { if (p_type == GENERATOR_TYPE_TUBE) { buffer = "T"; buffer.append_int(p_n); buffer.append_char(','); buffer.append_int(p_m); buffer.append_char(','); buffer.append_int(p_h); buffer.append_char('-'); } else if (p_type == GENERATOR_TYPE_SYMMETRIC) { buffer = "S"; buffer.append_int(p_scrap_no); buffer.append_char('-'); } else { buffer = "A"; buffer.append_int(p_scrap_no); buffer.append_char('-'); } if (compress) { int current_No = 0; int count = 0; for (int i = 0; i < p_history_length; ++i) { if (current_No == p_history[i]) ++count; else { if (count) No_No_to_digits10x10_digits26x7(current_No, count, buffer); current_No = p_history[i]; count = 1; } } No_No_to_digits10x10_digits26x7(current_No, count, buffer); } else { for (int i = 0; i < p_history_offset; ++i) buffer.append_char(p_history[i] + '0'); } } /* Local Variables: */ /* mode: c++ */ /* End: */
26.290123
85
0.634539
[ "object" ]
8d9ecbed039c26e15fdf034f6062fddd70b75e13
4,887
cpp
C++
CodeForces/Solutions/1062E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
5
2020-10-03T17:15:26.000Z
2022-03-29T21:39:22.000Z
CodeForces/Solutions/1062E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
null
null
null
CodeForces/Solutions/1062E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
1
2021-03-01T12:56:50.000Z
2021-03-01T12:56:50.000Z
#include <bits/stdc++.h> using namespace std; #define ll int #define pll pair <ll, ll> #define kom first #define boro second #define ln(node) (node << 1) #define rn(node) ( (node << 1) | 1) #define inf 1000000000 vector <ll> g[100009]; ll start[100009], stop[100009], TM = 0, id = 0; ll ara[400009], nodeOf[100009], indexOf[100009], lev[100009]; pll maxmin[400009], treeTM2[400009]; ll treeTM[1600009]; void dfs(ll u, ll lv) { start[u] = ++TM; nodeOf[TM] = u; ara[++id] = TM; indexOf[u] = id; lev[u] = lv; for(ll v: g[u]) { dfs(v, lv + 1); ara[++id] = start[u]; } stop[u] = TM; } void buildmm(ll lo, ll hi, ll node) { if(lo == hi) { maxmin[node] = make_pair(indexOf[lo], indexOf[lo]); return; } ll mid = (lo + hi) / 2; buildmm(lo, mid, 2 * node); buildmm(mid + 1, hi, 2 * node + 1); maxmin[node].kom = min(maxmin[ln(node)].kom, maxmin[rn(node)].kom); maxmin[node].boro = max(maxmin[ln(node)].boro, maxmin[rn(node)].boro); } pll querymm(ll lo, ll hi, ll left, ll right, ll node) { // cout << lo << " " << hi << " " << left << " " << right << endl; if(lo > right || hi < left) return pll(inf, -inf); if(lo >= left && hi <= right) return maxmin[node]; ll mid = (lo + hi) / 2; pll p1 = querymm(lo, mid, left, right, ln(node)); pll p2 = querymm(mid + 1, hi, left, right, rn(node)); return pll(min(p1.kom, p2.kom), max(p1.boro, p2.boro)); } void buildTM(ll lo, ll hi, ll node) { if(lo == hi) { treeTM[node] = ara[lo]; return; } ll mid = (lo + hi) / 2; buildTM(lo, mid, ln(node)); buildTM(mid + 1, hi, rn(node)); treeTM[node] = min(treeTM[ln(node)], treeTM[rn(node)]); } ll queryTM(ll lo, ll hi, ll left, ll right, ll node) { if(lo > right || hi < left) return inf; if(lo >= left && hi <= right) return treeTM[node]; ll mid = (lo + hi) / 2; ll p1 = queryTM(lo, mid, left, right, ln(node)); ll p2 = queryTM(mid + 1, hi, left, right, rn(node)); return min(p1, p2); } void buildTM2(ll lo, ll hi, ll node) { if(lo == hi) { treeTM2[node] = pll(start[lo], start[lo]); return; } ll mid = (lo + hi) / 2; buildTM2(lo, mid, ln(node)); buildTM2(mid + 1, hi, rn(node)); treeTM2[node].kom = min(treeTM2[ln(node)].kom, treeTM2[rn(node)].kom); treeTM2[node].boro = max(treeTM2[ln(node)].boro, treeTM2[rn(node)].boro); } pll queryTM2(ll lo, ll hi, ll left, ll right, ll node) { if(lo > right || hi < left) return pll(inf, -inf); if(lo >= left && hi <= right) return treeTM2[node]; ll mid = (lo + hi) / 2; pll p1 = queryTM2(lo, mid, left, right, ln(node)); pll p2 = queryTM2(mid + 1, hi, left, right, rn(node)); return pll(min(p1.kom, p2.kom), max(p1.boro, p2.boro)); } int main() { ll n, q; cin >> n >> q; for(ll i = 2; i <= n; i++) { ll inp; scanf("%d", &inp); g[inp].push_back(i); } dfs(1, 0); buildmm(1, n, 1); buildTM2(1, n, 1); buildTM(1, id, 1); while(q--) { ll u, v, ansNode = 0; scanf("%d %d", &u, &v); pll p = querymm(1, n, u, v, 1); // cout << p.first << endl; ll lcaTM = queryTM(1, id, p.kom, p.boro, 1); ll lca = nodeOf[lcaTM], lcaLeft, lcaRight; // cout << lca << endl; pll p2 = queryTM2(1, n, u, v, 1); ll leftNode = nodeOf[p2.kom], rightNode = nodeOf[p2.boro]; if(leftNode > rightNode) swap(leftNode, rightNode); if(leftNode == u) { pll p3 = querymm(1, n, u + 1, v, 1); ll lcaTM2 = queryTM(1, id, p3.kom, p3.boro, 1); lcaLeft = nodeOf[lcaTM2]; } else { pll p4 = querymm(1, n, u, leftNode - 1, 1); pll p5 = querymm(1, n, leftNode + 1, v, 1); p4.kom = min(p4.kom, p5.kom), p4.boro = max(p4.boro, p5.boro); ll lcaTM2 = queryTM(1, id, p4.kom, p4.boro, 1); lcaLeft = nodeOf[lcaTM2]; } if(rightNode == v) { pll p3 = querymm(1, n, u, v - 1, 1); ll lcaTM2 = queryTM(1, id, p3.kom, p3.boro, 1); lcaRight = nodeOf[lcaTM2]; } else { pll p4 = querymm(1, n, u, rightNode - 1, 1); pll p5 = querymm(1, n, rightNode + 1, v, 1); p4.kom = min(p4.kom, p5.kom), p4.boro = max(p4.boro, p5.boro); ll lcaTM2 = queryTM(1, id, p4.kom, p4.boro, 1); lcaRight = nodeOf[lcaTM2]; } if(lev[lcaLeft] > lev[lca]) { lca = lcaLeft; ansNode = leftNode; } if(lev[lcaRight] > lev[lca]) { lca = lcaRight; ansNode = rightNode; } printf("%d %d\n", ansNode==0?u:ansNode, lev[lca]); } return 0; }
24.807107
77
0.499693
[ "vector" ]
8d9f9f8d00bfc8fa653d1f3ede266f7bce28dbbd
3,054
hpp
C++
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerRTouch.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerRTouch.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerRTouch.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: OVRInput #include "GlobalNamespace/OVRInput.hpp" // Including type: OVRInput/OVRControllerBase #include "GlobalNamespace/OVRInput_OVRControllerBase.hpp" // Completed includes // Type namespace: namespace GlobalNamespace { // Autogenerated type: OVRInput/OVRControllerRTouch class OVRInput::OVRControllerRTouch : public GlobalNamespace::OVRInput::OVRControllerBase { public: // public System.Void .ctor() // Offset: 0xE71270 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::.ctor() // Base method: System.Void Object::.ctor() static OVRInput::OVRControllerRTouch* New_ctor(); // public override System.Void ConfigureButtonMap() // Offset: 0xE79080 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::ConfigureButtonMap() void ConfigureButtonMap(); // public override System.Void ConfigureTouchMap() // Offset: 0xE79254 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::ConfigureTouchMap() void ConfigureTouchMap(); // public override System.Void ConfigureNearTouchMap() // Offset: 0xE79318 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::ConfigureNearTouchMap() void ConfigureNearTouchMap(); // public override System.Void ConfigureAxis1DMap() // Offset: 0xE79370 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::ConfigureAxis1DMap() void ConfigureAxis1DMap(); // public override System.Void ConfigureAxis2DMap() // Offset: 0xE793C8 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Void OVRControllerBase::ConfigureAxis2DMap() void ConfigureAxis2DMap(); // public override System.Boolean WasRecentered() // Offset: 0xE7941C // Implemented from: OVRInput/OVRControllerBase // Base method: System.Boolean OVRControllerBase::WasRecentered() bool WasRecentered(); // public override System.Byte GetRecenterCount() // Offset: 0xE79430 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Byte OVRControllerBase::GetRecenterCount() uint8_t GetRecenterCount(); // public override System.Byte GetBatteryPercentRemaining() // Offset: 0xE79438 // Implemented from: OVRInput/OVRControllerBase // Base method: System.Byte OVRControllerBase::GetBatteryPercentRemaining() uint8_t GetBatteryPercentRemaining(); }; // OVRInput/OVRControllerRTouch } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRInput::OVRControllerRTouch*, "", "OVRInput/OVRControllerRTouch"); #pragma pack(pop)
44.26087
108
0.731172
[ "object" ]
8da42432caa9973f0d5e05d52b9d922551532945
15,190
cpp
C++
src/Pegasus/FQL/tests/clitest/main.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
1
2021-11-12T21:28:50.000Z
2021-11-12T21:28:50.000Z
src/Pegasus/FQL/tests/clitest/main.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
39
2021-01-18T19:28:41.000Z
2022-03-27T20:55:36.000Z
src/Pegasus/FQL/tests/clitest/main.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
4
2021-07-09T12:52:33.000Z
2021-12-21T15:05:59.000Z
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%//////////////////////////////////////////////////////////////////////////// /* This program executes a number of FQL queries against the server and analyzes the results. */ #include <Pegasus/Common/Config.h> #include <Pegasus/Common/PegasusAssert.h> #include <Pegasus/Client/CIMClient.h> #include <Pegasus/Common/StringConversion.h> #include <stdio.h> #include <stdlib.h> #include <cstdarg> #include <string.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; #define VCOUT if (verbose) cout Boolean verbose = false; #define TRACE cout << "line=" << __LINE__ << endl; //#define PROVIDERNS test/TestProvider //#define TEST_CLASS_DEFINE Test_CLITestProviderClass String namespace_opt = ""; String host_opt = ""; String user_opt = ""; String password_opt = ""; const CIMName TEST_CLASS("Test_CLITestProviderClass"); const CIMNamespaceName PROVIDERNS = CIMNamespaceName("test/TestProvider"); /* Execute a defined query and return the instances found */ void testEnumerate( CIMClient& client, const String& query, Uint32 testCount, CIMStatusCode expectedError = CIM_ERR_SUCCESS) { Array<CIMInstance> pulledInstances; Boolean endOfSequence = false; CIMEnumerationContext enumerationContext; try { pulledInstances = client.openEnumerateInstances( enumerationContext, endOfSequence, PROVIDERNS, TEST_CLASS, true, false, CIMPropertyList(), "DMTF:FQL", query, 30, false, 10); if (expectedError != CIM_ERR_SUCCESS) { cout << "ERROR. Error code expected but good response receied." << endl; } } catch (CIMException& e) { if (e.getCode() == expectedError) { VCOUT << "Error caught correctly. " << e.getCode() << endl; return; } else { cout << "Error Rtn expected but Incorrect code received" << " Query " << query << endl; exit(1); } } while (!endOfSequence) { Array<CIMInstance> cimInstancesPulled = client.pullInstancesWithPath( enumerationContext, endOfSequence, 10); pulledInstances.appendArray(cimInstancesPulled); } if (testCount != pulledInstances.size()) { cout << "Incorrect Count returned. Expected " << testCount << " Received " << pulledInstances.size() << " Query " << query << endl; exit(1); } else { return; } } void testAssociators( CIMClient& client, const String& query, CIMObjectPath targetPath, Uint32 testCount, CIMStatusCode expectedError = CIM_ERR_SUCCESS) { Array<CIMInstance> pulledInstances; Boolean endOfSequence = false; CIMEnumerationContext enumerationContext; //CIMObjectPath assoc = CIMObjectPath("TEST_CLASS.Id=\"Mike"\") try { pulledInstances = client.openAssociatorInstances( enumerationContext, endOfSequence, PROVIDERNS, targetPath, CIMName(), CIMName(), String(), String(), false, CIMPropertyList(), "DMTF:FQL", query, 30, false, 10); if (expectedError != CIM_ERR_SUCCESS) { cout << "ERROR. Error code expected but good response receied." << endl; } } catch (CIMException& e) { if (e.getCode() == expectedError) { VCOUT << "Error caught correctly. " << e.getCode() << endl; return; } else { cout << "Error Rtn expected but Incorrect code received" << " Query " << query << " Expected " << expectedError << " received " << e.getCode() << " msg " << e.getMessage() << endl; exit(1); } } while (!endOfSequence) { Array<CIMInstance> cimInstancesPulled = client.pullInstancesWithPath( enumerationContext, endOfSequence, 10); pulledInstances.appendArray(cimInstancesPulled); } VCOUT << "pullAssociators " << targetPath.toString() << " returned " << pulledInstances.size() << " instances." << endl; if (testCount != pulledInstances.size()) { cout << "Incorrect Count returned. Expected " << testCount << " Received " << pulledInstances.size() << " Query " << query << endl; exit(1); } else { return; } } void testReferences( CIMClient& client, const String& query, CIMObjectPath targetPath, Uint32 testCount, CIMStatusCode expectedError = CIM_ERR_SUCCESS) { Array<CIMInstance> pulledInstances; Boolean endOfSequence = false; CIMEnumerationContext enumerationContext; //CIMObjectPath assoc = CIMObjectPath("TEST_CLASS.Id=\"Mike"\") try { pulledInstances = client.openReferenceInstances( enumerationContext, endOfSequence, PROVIDERNS, targetPath, CIMName(), String(), false, CIMPropertyList(), "DMTF:FQL", query, 30, false, 10); if (expectedError != CIM_ERR_SUCCESS) { cout << "ERROR. Error code expected but good response receied." << endl; } } catch (CIMException& e) { if (e.getCode() == expectedError) { VCOUT << "Error caught correctly. " << e.getCode() << endl; return; } else { cout << "Error Rtn expected but Incorrect code received" << " Query " << query << " Expected " << expectedError << " received " << e.getCode() << " msg " << e.getMessage() << endl; exit(1); } } while (!endOfSequence) { Array<CIMInstance> cimInstancesPulled = client.pullInstancesWithPath( enumerationContext, endOfSequence, 10); pulledInstances.appendArray(cimInstancesPulled); } VCOUT << "pullAssociators " << targetPath.toString() << " returned " << pulledInstances.size() << " instances." << endl; if (testCount != pulledInstances.size()) { cout << "Incorrect Count returned. Expected " << testCount << " Received " << pulledInstances.size() << " Query " << query << endl; exit(1); } else { return; } } CIMObjectPath createInstance(CIMClient& client, CIMInstance& newInstance) { CIMObjectPath path = client.createInstance(PROVIDERNS, newInstance); return path; } bool setPropertyValue(CIMInstance& instance, const CIMName& propertyName, const CIMValue & value) { unsigned int pos = instance.findProperty(propertyName); if(pos != PEG_NOT_FOUND) { instance.getProperty(pos).setValue(value); return true; } return false; } /* Build an instance of the test class */ CIMInstance buildInstance(CIMClient& client, String& instanceId) { CIMClass cl = client.getClass(PROVIDERNS, TEST_CLASS); CIMInstance inst = cl.buildInstance(false, false, CIMPropertyList()); setPropertyValue(inst, "Id", CIMValue(instanceId)); return inst; } void deleteInstance(CIMClient& client, CIMObjectPath& path) { client.deleteInstance(PROVIDERNS, path); } // Parse Hostname input into name and port number Boolean parseHostName(const String arg, String& hostName, Uint32& port) { port = 5988; hostName = arg; Uint32 pos; if (!((pos = arg.reverseFind(':')) == PEG_NOT_FOUND)) { Uint64 temp; if (StringConversion::decimalStringToUint64( hostName.subString(pos+1).getCString(), temp) && StringConversion::checkUintBounds(temp,CIMTYPE_UINT32)) { hostName.remove(pos); port = (Uint32)temp; } else { return false; } } return true; } bool connectToHost(CIMClient& client, String host_opt = "") { try { if (host_opt == "") { VCOUT << "connectLocal" << endl; client.connectLocal(); } else { String hostName; Uint32 port; if (parseHostName(host_opt, hostName, port)) { VCOUT << " Connect to host " << hostName << ":" << port << endl; client.connect(hostName, port, user_opt, password_opt); } else { cerr << "Host name parameter error " << hostName << endl; PEGASUS_TEST_ASSERT(false); } } } catch (CIMException& e) { cerr << "CIMException Error: in connect " << e.getMessage() << endl; PEGASUS_TEST_ASSERT(false); } catch (Exception& e) { cerr << "Error: in connect " << e.getMessage() << endl; PEGASUS_TEST_ASSERT(false); } return true; } int main(int , char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE"); const char* arg0 = argv[0]; CIMClient client; if (!connectToHost(client)) { cerr << "Connection to host failed. Terminating" << endl; exit(1); } Array<CIMObjectPath> paths; // // Create instances that will have specified test properties in them // that we can use for queries. We used the class // Test_CLITestProviderClass because it has a broad set of testable // properties. // String id1 = "PropertyOpTest1"; CIMInstance inst1 = buildInstance(client, id1); { setPropertyValue(inst1,"scalBool", CIMValue(true)); setPropertyValue(inst1,"scalUint8",CIMValue(Uint8(12))); setPropertyValue(inst1,"scalSint8",CIMValue(Sint8(12))); setPropertyValue(inst1,"scalUint16",CIMValue(Uint16(500))); setPropertyValue(inst1,"scalSint16",CIMValue(Sint16(500))); setPropertyValue(inst1,"scalUint32",CIMValue(Uint32(9999))); setPropertyValue(inst1,"scalSint32",CIMValue(Sint32(9999))); setPropertyValue(inst1,"scalUint64",CIMValue(Uint64(9999))); setPropertyValue(inst1,"scalSint64",CIMValue(Sint64(9999))); setPropertyValue(inst1,"scalString",CIMValue(String("String1"))); Array<Uint32> lArrayUint32; lArrayUint32.append(0); lArrayUint32.append(128); lArrayUint32.append(256); lArrayUint32.append(65536); lArrayUint32.append(4294967295); setPropertyValue(inst1,"arrayUint32",CIMValue(lArrayUint32)); } CIMObjectPath p1 = createInstance(client, inst1); paths.append(p1); String id2 = "PropertyOpTest2"; CIMInstance inst2 = buildInstance(client, id2); { setPropertyValue(inst2,"scalBool", CIMValue(false)); setPropertyValue(inst2,"scalUint8",CIMValue(Uint8(20))); setPropertyValue(inst2,"scalSint8",CIMValue(Sint8(8))); setPropertyValue(inst2,"scalUint16",CIMValue(Uint16(1000))); setPropertyValue(inst2,"scalSint16",CIMValue(Sint16(500))); setPropertyValue(inst2,"scalUint32",CIMValue(Uint32(7698))); setPropertyValue(inst2,"scalSint32",CIMValue(Sint32(9999))); setPropertyValue(inst2,"scalUint64",CIMValue(Uint64(9999))); setPropertyValue(inst2,"scalSint64",CIMValue(Sint64(9999))); setPropertyValue(inst2,"scalString",CIMValue(String("String2"))); Array<Uint32> lArrayUint32; lArrayUint32.append(0); lArrayUint32.append(128); lArrayUint32.append(256); lArrayUint32.append(165536); lArrayUint32.append(4294967295); lArrayUint32.append(876543); setPropertyValue(inst2,"arrayUint32",CIMValue(lArrayUint32)); } CIMObjectPath p2 = createInstance(client, inst2); paths.append(p2); // // Execute the query tests // testEnumerate(client, "scalBool = true", 2); testEnumerate(client,"scalUint32 = 7698", 1); testEnumerate(client, "scalString = 'String2'", 1); testEnumerate(client, "arrayUint32[5] = 876543", 1); testEnumerate(client, "ANY arrayUint32 = 876543", 1); testEnumerate(client, "scalString <> 'NoSuchString'", 3); testEnumerate(client, "scalString = 'String2'", 1); // the following are error tests testEnumerate(client, "scalUint32 = 'NotANumber'", 0, CIMStatusCode(15)); testEnumerate(client, "scalUint32 = 123a", 0, CIMStatusCode(15)); testEnumerate(client, "scalbool = 1234", 0, CIMStatusCode(15)); // Test associator CIMObjectPath assoc = CIMObjectPath("Test_CLITestProviderClass.Id=\"Mike\""); testAssociators(client, "scalBool = true",assoc, 1); testAssociators(client, "scalBool = false",assoc, 0); // Cheap test because only possible comparison is cimobject path // and that means building correct object path for the query // KS_TODO create a valid CIMObjectPath and test it. testReferences(client, "scalBool = false", assoc,0); for (Uint32 i = 0; i < paths.size(); i++) { deleteInstance(client,paths[i]); } cout << arg0 << " +++++ passed all tests."; }
29.552529
79
0.596313
[ "object" ]
8dacea78394a7afa2166594b8b020b678e94bf25
3,704
cpp
C++
ngraph/test/onnx/onnx_import_exceptions.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
1
2022-01-19T15:36:45.000Z
2022-01-19T15:36:45.000Z
ngraph/test/onnx/onnx_import_exceptions.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
22
2021-02-03T12:41:51.000Z
2022-02-21T13:04:48.000Z
ngraph/test/onnx/onnx_import_exceptions.cpp
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
1
2021-07-28T17:30:46.000Z
2021-07-28T17:30:46.000Z
//***************************************************************************** // Copyright 2017-2021 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. //***************************************************************************** #include <exception> #include "exceptions.hpp" #include "gtest/gtest.h" #include "ngraph/file_util.hpp" #include "ngraph/ngraph.hpp" #include "onnx_import/onnx.hpp" #include "util/type_prop.hpp" using namespace ngraph; TEST(onnx_importer, exception_throws_ngraph_error) { EXPECT_THROW(onnx_import::import_onnx_model(file_util::path_join( SERIALIZED_ZOO, "onnx/depth_to_space_bad_blocksize.prototxt")), ngraph_error); } TEST(onnx_importer, exception_msg_ngraph_error) { try { onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/depth_to_space_bad_blocksize.prototxt")); // Should have thrown, so fail if it didn't FAIL() << "ONNX Importer did not detected incorrect model!"; } catch (const ngraph_error& e) { EXPECT_HAS_SUBSTRING(e.what(), std::string("While validating ONNX node '<Node(DepthToSpace)")); EXPECT_HAS_SUBSTRING(e.what(), std::string("While validating node 'v0::DepthToSpace")); } catch (...) { FAIL() << "The ONNX model importer failed for unexpected reason"; } } TEST(onnx_importer, exception_msg_onnx_node_validation_failure) { try { onnx_import::import_onnx_model( file_util::path_join(SERIALIZED_ZOO, "onnx/instance_norm_bad_scale_type.prototxt")); // Should have thrown, so fail if it didn't FAIL() << "ONNX Importer did not detected incorrect model!"; } catch (const ::ngraph::onnx_import::error::OnnxNodeValidationFailure& e) { EXPECT_HAS_SUBSTRING( e.what(), std::string("While validating ONNX node '<Node(InstanceNormalization)")); } // On MacOS after we re-throw OnnxNodeValidationFailure exception, we couldn't catch it as is, // thus below workaround. catch (const std::exception& e) { EXPECT_HAS_SUBSTRING( e.what(), std::string("While validating ONNX node '<Node(InstanceNormalization)")); } catch (...) { FAIL() << "The ONNX model importer failed for unexpected reason"; } } // This test aims to check for wrapping all std::exception not deriving from ngraph_error. // This test should throw a std error because of attempt to access shape from dynamic tensor. TEST(onnx_importer, exception_msg_std_err_wrapped) { try { onnx_import::import_onnx_model(file_util::path_join( SERIALIZED_ZOO, "onnx/dynamic_shapes/eye_link_dyn_shape.prototxt")); // Should have thrown, so fail if it didn't FAIL() << "ONNX Importer did not detected incorrect model!"; } catch (const std::exception& e) { EXPECT_HAS_SUBSTRING(e.what(), std::string("While validating ONNX node '<Node(EyeLike): y")); } catch (...) { FAIL() << "The ONNX model importer failed for unexpected reason"; } }
35.615385
98
0.641469
[ "shape", "model" ]
8dae3f438642d23db9fce6aa58a0231d3c08183e
32,492
hpp
C++
include/System/Collections/Concurrent/ConcurrentQueue_1.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Collections/Concurrent/ConcurrentQueue_1.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Collections/Concurrent/ConcurrentQueue_1.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Collections.Generic.IReadOnlyCollection`1 #include "System/Collections/Generic/IReadOnlyCollection_1.hpp" // Including type: System.Collections.Concurrent.PaddedHeadAndTail #include "System/Collections/Concurrent/PaddedHeadAndTail.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Concurrent namespace System::Collections::Concurrent { // Skipping declaration: Segment because it is already included! // Skipping declaration: <Enumerate>d__27 because it is already included! } // Forward declaring namespace: System namespace System { // Forward declaring type: Array class Array; } // Forward declaring namespace: System::Collections namespace System::Collections { // Skipping declaration: IEnumerator because it is already included! } // Completed forward declares // Type namespace: System.Collections.Concurrent namespace System::Collections::Concurrent { // WARNING Size may be invalid! // Autogenerated type: System.Collections.Concurrent.ConcurrentQueue`1 // [DebuggerDisplayAttribute] Offset: D804E4 // [DebuggerTypeProxyAttribute] Offset: D804E4 template<typename T> class ConcurrentQueue_1 : public ::Il2CppObject/*, public System::Collections::ICollection, public System::Collections::Generic::IReadOnlyCollection_1<T>*/ { public: // Nested type: System::Collections::Concurrent::ConcurrentQueue_1::Segment<T> class Segment; // Nested type: System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27<T> class $Enumerate$d__27; // WARNING Size may be invalid! // Autogenerated type: System.Collections.Concurrent.ConcurrentQueue`1/Segment // [DebuggerDisplayAttribute] Offset: D8056C class Segment : public ::il2cpp_utils::il2cpp_type_check::NestedType, public ::Il2CppObject { public: using declaring_type = ConcurrentQueue_1<T>*; static constexpr std::string_view NESTED_NAME = "Segment"; // Nested type: System::Collections::Concurrent::ConcurrentQueue_1::Segment::Slot<T> struct Slot; // WARNING Size may be invalid! // Autogenerated type: System.Collections.Concurrent.ConcurrentQueue`1/Segment/Slot // [DebuggerDisplayAttribute] Offset: D805A4 struct Slot : public ::il2cpp_utils::il2cpp_type_check::NestedType/*, public System::ValueType*/ { public: using declaring_type = typename ConcurrentQueue_1<T>::Segment*; static constexpr std::string_view NESTED_NAME = "Slot"; // public T Item // Size: 0xFFFFFFFF // Offset: 0x0 T Item; // public System.Int32 SequenceNumber // Size: 0x4 // Offset: 0x0 int SequenceNumber; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: Slot constexpr Slot(T Item_ = {}, int SequenceNumber_ = {}) noexcept : Item{Item_}, SequenceNumber{SequenceNumber_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } }; // System.Collections.Concurrent.ConcurrentQueue`1/Segment/Slot // Could not write size check! Type: System.Collections.Concurrent.ConcurrentQueue`1/Segment/Slot is generic, or has no fields that are valid for size checks! // readonly System.Collections.Concurrent.ConcurrentQueue`1/Segment/Slot<T>[] _slots // Size: 0x8 // Offset: 0x0 ::Array<typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment::Slot>* slots; // Field size check static_assert(sizeof(::Array<typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment::Slot>*) == 0x8); // readonly System.Int32 _slotsMask // Size: 0x4 // Offset: 0x0 int slotsMask; // Field size check static_assert(sizeof(int) == 0x4); // System.Collections.Concurrent.PaddedHeadAndTail _headAndTail // Size: 0x104 // Offset: 0x0 System::Collections::Concurrent::PaddedHeadAndTail headAndTail; // Field size check static_assert(sizeof(System::Collections::Concurrent::PaddedHeadAndTail) == 0x104); // System.Boolean _preservedForObservation // Size: 0x1 // Offset: 0x0 bool preservedForObservation; // Field size check static_assert(sizeof(bool) == 0x1); // System.Boolean _frozenForEnqueues // Size: 0x1 // Offset: 0x0 bool frozenForEnqueues; // Field size check static_assert(sizeof(bool) == 0x1); // System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> _nextSegment // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* nextSegment; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // Creating value type constructor for type: Segment Segment(::Array<typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment::Slot>* slots_ = {}, int slotsMask_ = {}, System::Collections::Concurrent::PaddedHeadAndTail headAndTail_ = {}, bool preservedForObservation_ = {}, bool frozenForEnqueues_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* nextSegment_ = {}) noexcept : slots{slots_}, slotsMask{slotsMask_}, headAndTail{headAndTail_}, preservedForObservation{preservedForObservation_}, frozenForEnqueues{frozenForEnqueues_}, nextSegment{nextSegment_} {} // public System.Void .ctor(System.Int32 boundedLength) // Offset: 0xFFFFFFFF template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static typename ConcurrentQueue_1<T>::Segment* New_ctor(int boundedLength) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<typename ConcurrentQueue_1<T>::Segment*, creationType>(boundedLength))); } // System.Int32 get_Capacity() // Offset: 0xFFFFFFFF int get_Capacity() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::get_Capacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Capacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // System.Int32 get_FreezeOffset() // Offset: 0xFFFFFFFF int get_FreezeOffset() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::get_FreezeOffset"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_FreezeOffset", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // System.Void EnsureFrozenForEnqueues() // Offset: 0xFFFFFFFF void EnsureFrozenForEnqueues() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::EnsureFrozenForEnqueues"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EnsureFrozenForEnqueues", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // public System.Boolean TryDequeue(out T item) // Offset: 0xFFFFFFFF bool TryDequeue(T& item) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::TryDequeue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryDequeue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<T&>()}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, item); } // public System.Boolean TryEnqueue(T item) // Offset: 0xFFFFFFFF bool TryEnqueue(T item) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Segment::TryEnqueue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryEnqueue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, item); } }; // System.Collections.Concurrent.ConcurrentQueue`1/Segment // Could not write size check! Type: System.Collections.Concurrent.ConcurrentQueue`1/Segment is generic, or has no fields that are valid for size checks! // WARNING Size may be invalid! // Autogenerated type: System.Collections.Concurrent.ConcurrentQueue`1/<Enumerate>d__27 // [CompilerGeneratedAttribute] Offset: D805DC class $Enumerate$d__27 : public ::il2cpp_utils::il2cpp_type_check::NestedType, public ::Il2CppObject/*, public System::Collections::Generic::IEnumerator_1<T>*/ { public: using declaring_type = ConcurrentQueue_1<T>*; static constexpr std::string_view NESTED_NAME = "$Enumerate$d__27"; // private System.Int32 <>1__state // Size: 0x4 // Offset: 0x0 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // private T <>2__current // Size: 0xFFFFFFFF // Offset: 0x0 T $$2__current; // public System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> head // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // public System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> tail // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // public System.Int32 tailTail // Size: 0x4 // Offset: 0x0 int tailTail; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 headHead // Size: 0x4 // Offset: 0x0 int headHead; // Field size check static_assert(sizeof(int) == 0x4); // public System.Collections.Concurrent.ConcurrentQueue`1<T> <>4__this // Size: 0x8 // Offset: 0x0 System::Collections::Concurrent::ConcurrentQueue_1<T>* $$4__this; // Field size check static_assert(sizeof(System::Collections::Concurrent::ConcurrentQueue_1<T>*) == 0x8); // private System.Int32 <i>5__1 // Size: 0x4 // Offset: 0x0 int $i$5__1; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <headTail>5__2 // Size: 0x4 // Offset: 0x0 int $headTail$5__2; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <i>5__3 // Size: 0x4 // Offset: 0x0 int $i$5__3; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <i>5__4 // Size: 0x4 // Offset: 0x0 int $i$5__4; // Field size check static_assert(sizeof(int) == 0x4); // private System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> <s>5__5 // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* $s$5__5; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // private System.Int32 <i>5__6 // Size: 0x4 // Offset: 0x0 int $i$5__6; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <sTail>5__7 // Size: 0x4 // Offset: 0x0 int $sTail$5__7; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <i>5__8 // Size: 0x4 // Offset: 0x0 int $i$5__8; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: $Enumerate$d__27 $Enumerate$d__27(int $$1__state_ = {}, T $$2__current_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail_ = {}, int tailTail_ = {}, int headHead_ = {}, System::Collections::Concurrent::ConcurrentQueue_1<T>* $$4__this_ = {}, int $i$5__1_ = {}, int $headTail$5__2_ = {}, int $i$5__3_ = {}, int $i$5__4_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* $s$5__5_ = {}, int $i$5__6_ = {}, int $sTail$5__7_ = {}, int $i$5__8_ = {}) noexcept : $$1__state{$$1__state_}, $$2__current{$$2__current_}, head{head_}, tail{tail_}, tailTail{tailTail_}, headHead{headHead_}, $$4__this{$$4__this_}, $i$5__1{$i$5__1_}, $headTail$5__2{$headTail$5__2_}, $i$5__3{$i$5__3_}, $i$5__4{$i$5__4_}, $s$5__5{$s$5__5_}, $i$5__6{$i$5__6_}, $sTail$5__7{$sTail$5__7_}, $i$5__8{$i$5__8_} {} // Creating interface conversion operator: operator System::Collections::Generic::IEnumerator_1<T> operator System::Collections::Generic::IEnumerator_1<T>() noexcept { return *reinterpret_cast<System::Collections::Generic::IEnumerator_1<T>*>(this); } // public System.Void .ctor(System.Int32 <>1__state) // Offset: 0xFFFFFFFF template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static typename ConcurrentQueue_1<T>::$Enumerate$d__27* New_ctor(int $$1__state) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<typename ConcurrentQueue_1<T>::$Enumerate$d__27*, creationType>($$1__state))); } // private System.Void System.IDisposable.Dispose() // Offset: 0xFFFFFFFF void System_IDisposable_Dispose() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::System.IDisposable.Dispose"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.IDisposable.Dispose", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // private System.Boolean MoveNext() // Offset: 0xFFFFFFFF bool MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::MoveNext"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "MoveNext", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // private T System.Collections.Generic.IEnumerator<T>.get_Current() // Offset: 0xFFFFFFFF T System_Collections_Generic_IEnumerator$T$_get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::System.Collections.Generic.IEnumerator<T>.get_Current"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.Generic.IEnumerator<T>.get_Current", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<T, false>(this, ___internal__method); } // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0xFFFFFFFF void System_Collections_IEnumerator_Reset() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::System.Collections.IEnumerator.Reset"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.IEnumerator.Reset", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0xFFFFFFFF ::Il2CppObject* System_Collections_IEnumerator_get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::$Enumerate$d__27::System.Collections.IEnumerator.get_Current"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.IEnumerator.get_Current", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method); } }; // System.Collections.Concurrent.ConcurrentQueue`1/<Enumerate>d__27 // Could not write size check! Type: System.Collections.Concurrent.ConcurrentQueue`1/<Enumerate>d__27 is generic, or has no fields that are valid for size checks! // private System.Object _crossSegmentLock // Size: 0x8 // Offset: 0x0 ::Il2CppObject* crossSegmentLock; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // private System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> _tail // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // private System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> _head // Size: 0x8 // Offset: 0x0 typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head; // Field size check static_assert(sizeof(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*) == 0x8); // Creating value type constructor for type: ConcurrentQueue_1 ConcurrentQueue_1(::Il2CppObject* crossSegmentLock_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail_ = {}, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head_ = {}) noexcept : crossSegmentLock{crossSegmentLock_}, tail{tail_}, head{head_} {} // Creating interface conversion operator: operator System::Collections::ICollection operator System::Collections::ICollection() noexcept { return *reinterpret_cast<System::Collections::ICollection*>(this); } // Creating interface conversion operator: operator System::Collections::Generic::IReadOnlyCollection_1<T> operator System::Collections::Generic::IReadOnlyCollection_1<T>() noexcept { return *reinterpret_cast<System::Collections::Generic::IReadOnlyCollection_1<T>*>(this); } // private System.Void System.Collections.ICollection.CopyTo(System.Array array, System.Int32 index) // Offset: 0xFFFFFFFF void System_Collections_ICollection_CopyTo(System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::System.Collections.ICollection.CopyTo"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.ICollection.CopyTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(index)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, array, index); } // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0xFFFFFFFF System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::System.Collections.IEnumerable.GetEnumerator"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.IEnumerable.GetEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method); } // public T[] ToArray() // Offset: 0xFFFFFFFF ::Array<T>* ToArray() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::ToArray"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ToArray", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<T>*, false>(this, ___internal__method); } // public System.Int32 get_Count() // Offset: 0xFFFFFFFF int get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::get_Count"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Count", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // static private System.Int32 GetCount(System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> s, System.Int32 head, System.Int32 tail) // Offset: 0xFFFFFFFF static int GetCount(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* s, int head, int tail) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::GetCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ConcurrentQueue_1<T>*>::get(), "GetCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s), ::il2cpp_utils::ExtractType(head), ::il2cpp_utils::ExtractType(tail)}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, s, head, tail); } // static private System.Int64 GetCount(System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> head, System.Int32 headHead, System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> tail, System.Int32 tailTail) // Offset: 0xFFFFFFFF static int64_t GetCount(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head, int headHead, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail, int tailTail) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::GetCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ConcurrentQueue_1<T>*>::get(), "GetCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(head), ::il2cpp_utils::ExtractType(headHead), ::il2cpp_utils::ExtractType(tail), ::il2cpp_utils::ExtractType(tailTail)}))); return ::il2cpp_utils::RunMethodThrow<int64_t, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, head, headHead, tail, tailTail); } // public System.Void CopyTo(T[] array, System.Int32 index) // Offset: 0xFFFFFFFF void CopyTo(::Array<T>* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::CopyTo"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(index)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, array, index); } // public System.Collections.Generic.IEnumerator`1<T> GetEnumerator() // Offset: 0xFFFFFFFF System::Collections::Generic::IEnumerator_1<T>* GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::GetEnumerator"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::IEnumerator_1<T>*, false>(this, ___internal__method); } // private System.Void SnapForObservation(out System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> head, out System.Int32 headHead, out System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> tail, out System.Int32 tailTail) // Offset: 0xFFFFFFFF void SnapForObservation(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*& head, int& headHead, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*& tail, int& tailTail) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::SnapForObservation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SnapForObservation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*&>(), ::il2cpp_utils::ExtractIndependentType<int&>(), ::il2cpp_utils::ExtractIndependentType<typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment*&>(), ::il2cpp_utils::ExtractIndependentType<int&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, head, headHead, tail, tailTail); } // private T GetItemWhenAvailable(System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> segment, System.Int32 i) // Offset: 0xFFFFFFFF T GetItemWhenAvailable(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* segment, int i) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::GetItemWhenAvailable"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetItemWhenAvailable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(segment), ::il2cpp_utils::ExtractType(i)}))); return ::il2cpp_utils::RunMethodThrow<T, false>(this, ___internal__method, segment, i); } // private System.Collections.Generic.IEnumerator`1<T> Enumerate(System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> head, System.Int32 headHead, System.Collections.Concurrent.ConcurrentQueue`1/Segment<T> tail, System.Int32 tailTail) // Offset: 0xFFFFFFFF System::Collections::Generic::IEnumerator_1<T>* Enumerate(typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* head, int headHead, typename System::Collections::Concurrent::ConcurrentQueue_1<T>::Segment* tail, int tailTail) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Enumerate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Enumerate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(head), ::il2cpp_utils::ExtractType(headHead), ::il2cpp_utils::ExtractType(tail), ::il2cpp_utils::ExtractType(tailTail)}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::IEnumerator_1<T>*, false>(this, ___internal__method, head, headHead, tail, tailTail); } // public System.Void Enqueue(T item) // Offset: 0xFFFFFFFF void Enqueue(T item) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::Enqueue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Enqueue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, item); } // private System.Void EnqueueSlow(T item) // Offset: 0xFFFFFFFF void EnqueueSlow(T item) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::EnqueueSlow"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EnqueueSlow", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, item); } // public System.Boolean TryDequeue(out T result) // Offset: 0xFFFFFFFF bool TryDequeue(T& result) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::TryDequeue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryDequeue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<T&>()}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, result); } // private System.Boolean TryDequeueSlow(out T item) // Offset: 0xFFFFFFFF bool TryDequeueSlow(T& item) { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::TryDequeueSlow"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryDequeueSlow", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<T&>()}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, item); } // public System.Void .ctor() // Offset: 0xFFFFFFFF // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ConcurrentQueue_1<T>* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Collections::Concurrent::ConcurrentQueue_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ConcurrentQueue_1<T>*, creationType>())); } }; // System.Collections.Concurrent.ConcurrentQueue`1 // Could not write size check! Type: System.Collections.Concurrent.ConcurrentQueue`1 is generic, or has no fields that are valid for size checks! } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::Collections::Concurrent::ConcurrentQueue_1, "System.Collections.Concurrent", "ConcurrentQueue`1");
71.254386
913
0.705835
[ "object", "vector" ]
8dae8ccad90865d11400d984ec99eb1ca5ee0fea
17,827
cpp
C++
Engine/source/math/util/frustum.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
null
null
null
Engine/source/math/util/frustum.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
null
null
null
Engine/source/math/util/frustum.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
1
2018-10-26T03:18:22.000Z
2018-10-26T03:18:22.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "platform/platform.h" #include "math/util/frustum.h" #include "math/mMathFn.h" #include "math/mathUtils.h" #include "math/mSphere.h" #include "platform/profiler.h" //TODO: For OBB/frustum intersections and ortho frustums, we can resort to a much quicker AABB/OBB test // Must be CW ordered for face[0] of each edge! Keep in mind that normals // are pointing *inwards* and thus what appears CCW outside is CW inside. FrustumData::EdgeListType FrustumData::smEdges ( PolyhedronData::Edge( PlaneNear, PlaneTop, NearTopRight, NearTopLeft ), PolyhedronData::Edge( PlaneNear, PlaneBottom, NearBottomLeft, NearBottomRight ), PolyhedronData::Edge( PlaneNear, PlaneLeft, NearTopLeft, NearBottomLeft ), PolyhedronData::Edge( PlaneNear, PlaneRight, NearTopRight, NearBottomRight ), PolyhedronData::Edge( PlaneFar, PlaneTop, FarTopLeft, FarTopRight ), PolyhedronData::Edge( PlaneFar, PlaneBottom, FarBottomRight, FarBottomLeft ), PolyhedronData::Edge( PlaneFar, PlaneLeft, FarBottomLeft, FarTopLeft ), PolyhedronData::Edge( PlaneFar, PlaneRight, FarTopRight, FarBottomRight ), PolyhedronData::Edge( PlaneTop, PlaneLeft, FarTopLeft, NearTopLeft ), PolyhedronData::Edge( PlaneTop, PlaneRight, NearTopRight, FarTopRight ), PolyhedronData::Edge( PlaneBottom, PlaneLeft, NearBottomLeft, FarBottomLeft ), PolyhedronData::Edge( PlaneBottom, PlaneRight, FarBottomRight, NearBottomRight ) ); //----------------------------------------------------------------------------- Frustum::Frustum( bool isOrtho, F32 nearLeft, F32 nearRight, F32 nearTop, F32 nearBottom, F32 nearDist, F32 farDist, const MatrixF &transform ) { mTransform = transform; mPosition = transform.getPosition(); mNearLeft = nearLeft; mNearRight = nearRight; mNearTop = nearTop; mNearBottom = nearBottom; mNearDist = nearDist; mFarDist = farDist; mIsOrtho = isOrtho; mNumTiles = 1; mCurrTile.set(0,0); mTileOverlap.set(0.0f, 0.0f); mProjectionOffset.zero(); mProjectionOffsetMatrix.identity(); } //----------------------------------------------------------------------------- void Frustum::set( bool isOrtho, F32 fovYInRadians, F32 aspectRatio, F32 nearDist, F32 farDist, const MatrixF &transform ) { F32 left, right, top, bottom; MathUtils::makeFrustum( &left, &right, &top, &bottom, fovYInRadians, aspectRatio, nearDist ); tile( &left, &right, &top, &bottom, mNumTiles, mCurrTile, mTileOverlap ); set( isOrtho, left, right, top, bottom, nearDist, farDist, transform ); } //----------------------------------------------------------------------------- void Frustum::set( bool isOrtho, F32 nearLeft, F32 nearRight, F32 nearTop, F32 nearBottom, F32 nearDist, F32 farDist, const MatrixF &transform ) { mTransform = transform; mPosition = mTransform.getPosition(); mNearLeft = nearLeft; mNearRight = nearRight; mNearTop = nearTop; mNearBottom = nearBottom; mNearDist = nearDist; mFarDist = farDist; mIsOrtho = isOrtho; mDirty = true; } //----------------------------------------------------------------------------- #if 0 void Frustum::set( const MatrixF &projMat, bool normalize ) { // From "Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix" // by Gil Gribb and Klaus Hartmann. // // http://www2.ravensoft.com/users/ggribb/plane%20extraction.pdf // Right clipping plane. mPlanes[ PlaneRight ].set( projMat[3] - projMat[0], projMat[7] - projMat[4], projMat[11] - projMat[8], projMat[15] - projMat[12] ); // Left clipping plane. mPlanes[ PlaneLeft ].set( projMat[3] + projMat[0], projMat[7] + projMat[4], projMat[11] + projMat[8], projMat[15] + projMat[12] ); // Bottom clipping plane. mPlanes[ PlaneBottom ].set( projMat[3] + projMat[1], projMat[7] + projMat[5], projMat[11] + projMat[9], projMat[15] + projMat[13] ); // Top clipping plane. mPlanes[ PlaneTop ].set( projMat[3] - projMat[1], projMat[7] - projMat[5], projMat[11] - projMat[9], projMat[15] - projMat[13] ); // Near clipping plane mPlanes[ PlaneNear ].set( projMat[3] + projMat[2], projMat[7] + projMat[6], projMat[11] + projMat[10], projMat[15] + projMat[14] ); // Far clipping plane. mPlanes[ PlaneFar ].set( projMat[3] - projMat[2], projMat[7] - projMat[6], projMat[11] - projMat[10], projMat[15] - projMat[14] ); if( normalize ) { for( S32 i = 0; i < PlaneCount; ++ i ) mPlanes[ i ].normalize(); } /* // Create the corner points via plane intersections. mPlanes[ PlaneNear ].intersect( mPlanes[ PlaneTop ], mPlanes[ PlaneLeft ], &mPoints[ NearTopLeft ] ); mPlanes[ PlaneNear ].intersect( mPlanes[ PlaneTop ], mPlanes[ PlaneRight ], &mPoints[ NearTopRight ] ); mPlanes[ PlaneNear ].intersect( mPlanes[ PlaneBottom ], mPlanes[ PlaneLeft ], &mPoints[ NearBottomLeft ] ); mPlanes[ PlaneNear ].intersect( mPlanes[ PlaneBottom ], mPlanes[ PlaneRight ], &mPoints[ NearBottomRight ] ); mPlanes[ PlaneFar ].intersect( mPlanes[ PlaneTop ], mPlanes[ PlaneLeft ], &mPoints[ FarTopLeft ] ); mPlanes[ PlaneFar ].intersect( mPlanes[ PlaneTop ], mPlanes[ PlaneRight ], &mPoints[ FarTopRight ] ); mPlanes[ PlaneFar ].intersect( mPlanes[ PlaneBottom ], mPlanes[ PlaneLeft ], &mPoints[ FarBottomLeft ] ); mPlanes[ PlaneFar ].intersect( mPlanes[ PlaneBottom ], mPlanes[ PlaneRight ], &mPoints[ FarBottomRight ] ); */ // Update the axis aligned bounding box. _updateBounds(); } #endif //----------------------------------------------------------------------------- void Frustum::setNearDist( F32 nearDist ) { setNearFarDist( nearDist, mFarDist ); } //----------------------------------------------------------------------------- void Frustum::setFarDist( F32 farDist ) { setNearFarDist( mNearDist, farDist ); } //----------------------------------------------------------------------------- void Frustum::setNearFarDist( F32 nearDist, F32 farDist ) { if( mNearDist == nearDist && mFarDist == farDist ) return; // Recalculate the frustum. MatrixF xfm( mTransform ); set( mIsOrtho, getFov(), getAspectRatio(), nearDist, farDist, xfm ); } //----------------------------------------------------------------------------- void Frustum::cropNearFar(F32 newNearDist, F32 newFarDist) { const F32 newOverOld = newNearDist / mNearDist; set( mIsOrtho, mNearLeft * newOverOld, mNearRight * newOverOld, mNearTop * newOverOld, mNearBottom * newOverOld, newNearDist, newFarDist, mTransform); } //----------------------------------------------------------------------------- void FrustumData::_update() const { if( !mDirty ) return; PROFILE_SCOPE( Frustum_update ); const Point3F& cameraPos = mPosition; // Build the frustum points in camera space first. if( mIsOrtho ) { mPoints[ NearTopLeft ].set( mNearLeft, mNearDist, mNearTop ); mPoints[ NearTopRight ].set( mNearRight, mNearDist, mNearTop ); mPoints[ NearBottomLeft ].set( mNearLeft, mNearDist, mNearBottom ); mPoints[ NearBottomRight ].set( mNearRight, mNearDist, mNearBottom ); mPoints[ FarTopLeft ].set( mNearLeft, mFarDist, mNearTop ); mPoints[ FarTopRight ].set( mNearRight, mFarDist, mNearTop ); mPoints[ FarBottomLeft ].set( mNearLeft, mFarDist, mNearBottom ); mPoints[ FarBottomRight ].set( mNearRight, mFarDist, mNearBottom ); } else { const F32 farOverNear = mFarDist / mNearDist; mPoints[ NearTopLeft ].set( mNearLeft, mNearDist, mNearTop ); mPoints[ NearTopRight ].set( mNearRight, mNearDist, mNearTop ); mPoints[ NearBottomLeft ].set( mNearLeft, mNearDist, mNearBottom ); mPoints[ NearBottomRight ].set( mNearRight, mNearDist, mNearBottom ); mPoints[ FarTopLeft ].set( mNearLeft * farOverNear, mFarDist, mNearTop * farOverNear ); mPoints[ FarTopRight ].set( mNearRight * farOverNear, mFarDist, mNearTop * farOverNear ); mPoints[ FarBottomLeft ].set( mNearLeft * farOverNear, mFarDist, mNearBottom * farOverNear ); mPoints[ FarBottomRight ].set( mNearRight * farOverNear, mFarDist, mNearBottom * farOverNear ); } // Transform the points into the desired culling space. for( U32 i = 0; i < mPoints.size(); ++ i ) mTransform.mulP( mPoints[ i ] ); // Update the axis aligned bounding box from // the newly transformed points. mBounds = Box3F::aroundPoints( mPoints.address(), mPoints.size() ); // Finally build the planes. if( mIsOrtho ) { mPlanes[ PlaneLeft ].set( mPoints[ NearBottomLeft ], mPoints[ FarTopLeft ], mPoints[ FarBottomLeft ] ); mPlanes[ PlaneRight ].set( mPoints[ NearTopRight ], mPoints[ FarBottomRight ], mPoints[ FarTopRight ] ); mPlanes[ PlaneTop ].set( mPoints[ FarTopRight ], mPoints[ NearTopLeft ], mPoints[ NearTopRight ] ); mPlanes[ PlaneBottom ].set( mPoints[ NearBottomRight ], mPoints[ FarBottomLeft ], mPoints[ FarBottomRight ] ); mPlanes[ PlaneNear ].set( mPoints[ NearTopLeft ], mPoints[ NearBottomLeft ], mPoints[ NearTopRight ] ); mPlanes[ PlaneFar ].set( mPoints[ FarTopLeft ], mPoints[ FarTopRight ], mPoints[ FarBottomLeft ] ); } else { mPlanes[ PlaneLeft ].set( cameraPos, mPoints[ NearTopLeft ], mPoints[ NearBottomLeft ] ); mPlanes[ PlaneRight ].set( cameraPos, mPoints[ NearBottomRight ], mPoints[ NearTopRight ] ); mPlanes[ PlaneTop ].set( cameraPos, mPoints[ NearTopRight ], mPoints[ NearTopLeft ] ); mPlanes[ PlaneBottom ].set( cameraPos, mPoints[ NearBottomLeft ], mPoints[ NearBottomRight ] ); mPlanes[ PlaneNear ].set( mPoints[ NearTopLeft ], mPoints[ NearBottomLeft ], mPoints[ NearTopRight ] ); mPlanes[ PlaneFar ].set( mPoints[ FarTopLeft ], mPoints[ FarTopRight ], mPoints[ FarBottomLeft ] ); } // If the frustum plane orientation doesn't match mIsInverted // now, invert all the plane normals. // // Note that if we have a transform matrix with a negative scale, // then the initial planes we have computed will always be inverted. const bool inverted = mPlanes[ PlaneNear ].whichSide( cameraPos ) == PlaneF::Front; if( inverted != mIsInverted ) { for( U32 i = 0; i < mPlanes.size(); ++ i ) mPlanes[ i ].invert(); } AssertFatal( mPlanes[ PlaneNear ].whichSide( cameraPos ) != PlaneF::Front, "Frustum::_update - Viewpoint lies on front side of near plane!" ); // And now the center points which are mostly just used in debug rendering. mPlaneCenters[ PlaneLeftCenter ] = ( mPoints[ NearTopLeft ] + mPoints[ NearBottomLeft ] + mPoints[ FarTopLeft ] + mPoints[ FarBottomLeft ] ) / 4.0f; mPlaneCenters[ PlaneRightCenter ] = ( mPoints[ NearTopRight ] + mPoints[ NearBottomRight ] + mPoints[ FarTopRight ] + mPoints[ FarBottomRight ] ) / 4.0f; mPlaneCenters[ PlaneTopCenter ] = ( mPoints[ NearTopLeft ] + mPoints[ NearTopRight ] + mPoints[ FarTopLeft ] + mPoints[ FarTopRight ] ) / 4.0f; mPlaneCenters[ PlaneBottomCenter ] = ( mPoints[ NearBottomLeft ] + mPoints[ NearBottomRight ] + mPoints[ FarBottomLeft ] + mPoints[ FarBottomRight ] ) / 4.0f; mPlaneCenters[ PlaneNearCenter ] = ( mPoints[ NearTopLeft ] + mPoints[ NearTopRight ] + mPoints[ NearBottomLeft ] + mPoints[ NearBottomRight ] ) / 4.0f; mPlaneCenters[ PlaneFarCenter ] = ( mPoints[ FarTopLeft ] + mPoints[ FarTopRight ] + mPoints[ FarBottomLeft ] + mPoints[ FarBottomRight ] ) / 4.0f; // Done. mDirty = false; } //----------------------------------------------------------------------------- void Frustum::invert() { mIsInverted = !mIsInverted; _update(); } //----------------------------------------------------------------------------- void Frustum::setTransform( const MatrixF &mat ) { mTransform = mat; mPosition = mTransform.getPosition(); mDirty = true; } //----------------------------------------------------------------------------- void Frustum::scaleFromCenter( F32 scale ) { // Extract the fov and aspect ratio. F32 fovInRadians = mAtan2( (mNearTop - mNearBottom)*mNumTiles/2.0f, mNearDist ) * 2.0f; F32 aspectRatio = (mNearRight - mNearLeft)/(mNearTop - mNearBottom); // Now move the near and far planes out. F32 halfDist = ( mFarDist - mNearDist ) / 2.0f; mNearDist -= halfDist * ( scale - 1.0f ); mFarDist += halfDist * ( scale - 1.0f ); // Setup the new scaled frustum. set( mIsOrtho, fovInRadians, aspectRatio, mNearDist, mFarDist, mTransform ); } //----------------------------------------------------------------------------- void Frustum::mul( const MatrixF& mat ) { mTransform.mul( mat ); mDirty = true; } //----------------------------------------------------------------------------- void Frustum::mulL( const MatrixF& mat ) { MatrixF last( mTransform ); mTransform.mul( mat, last ); mDirty = true; } //----------------------------------------------------------------------------- void Frustum::setProjectionOffset(const Point2F& offsetMat) { mProjectionOffset = offsetMat; mProjectionOffsetMatrix.identity(); mProjectionOffsetMatrix.setPosition(Point3F(mProjectionOffset.x, mProjectionOffset.y, 0.0f)); } //----------------------------------------------------------------------------- void Frustum::getProjectionMatrix( MatrixF *proj, bool gfxRotate ) const { if (mIsOrtho) { MathUtils::makeOrthoProjection(proj, mNearLeft, mNearRight, mNearTop, mNearBottom, mNearDist, mFarDist, gfxRotate); proj->mulL(mProjectionOffsetMatrix); } else { MathUtils::makeProjection(proj, mNearLeft, mNearRight, mNearTop, mNearBottom, mNearDist, mFarDist, gfxRotate); proj->mulL(mProjectionOffsetMatrix); } } //----------------------------------------------------------------------------- void Frustum::tileFrustum(U32 numTiles, const Point2I& curTile, Point2F overlap) { //These will be stored to re-tile the frustum if needed mNumTiles = numTiles; mCurrTile = curTile; mTileOverlap = overlap; tile(&mNearLeft, &mNearRight, &mNearTop, &mNearBottom, mNumTiles, mCurrTile, mTileOverlap); } //----------------------------------------------------------------------------- void Frustum::tile( F32 *left, F32 *right, F32 *top, F32 *bottom, U32 numTiles, const Point2I& curTile, Point2F overlap ) { if (numTiles == 1) return; Point2F tileSize( ( *right - *left ) / (F32)numTiles, ( *top - *bottom ) / (F32)numTiles ); F32 leftOffset = tileSize.x*overlap.x; F32 rightOffset = tileSize.x*overlap.x*2; F32 bottomOffset = tileSize.y*overlap.y; F32 topOffset = tileSize.y*overlap.y*2; *left += tileSize.x * curTile.x - leftOffset; *right = *left + tileSize.x + rightOffset; *bottom += tileSize.y * curTile.y - bottomOffset; *top = *bottom + tileSize.y + topOffset; }
37.530526
121
0.52471
[ "transform" ]
8db4f5f6c4a699e57e8b08eb7ff548bd8ca60c44
3,099
cpp
C++
benchmarks/linear_algebra/cg/compute_residual.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
benchmarks/linear_algebra/cg/compute_residual.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
benchmarks/linear_algebra/cg/compute_residual.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
13
2017-07-03T15:24:53.000Z
2022-03-05T14:57:10.000Z
//@HEADER // ************************************************************************ // // HPCCG: Simple Conjugate Gradient Benchmark Code // Copyright (2006) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Michael A. Heroux (maherou@sandia.gov) // // ************************************************************************ //@HEADER ///////////////////////////////////////////////////////////////////////// // Routine to compute the 1-norm difference between two vectors where: // n - number of vector elements (on this processor) // v1, v2 - input vectors // residual - pointer to scalar value, on exit will contain result. ///////////////////////////////////////////////////////////////////////// #include <cmath> // needed for fabs using std::fabs; #include "compute_residual.hpp" int compute_residual(const int n, const double * const v1, const double * const v2, double * const residual) { double local_residual = 0.0; for (int i=0; i<n; i++) { double diff = fabs(v1[i] - v2[i]); if (diff > local_residual) local_residual = diff; } #ifdef USING_MPI // Use MPI's reduce function to collect all partial sums double global_residual = 0; MPI_Allreduce(&local_residual, &global_residual, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); *residual = global_residual; #else *residual = local_residual; #endif return(0); }
37.792683
81
0.656018
[ "vector" ]
8db8707e94f2e2da71d6167b74a3e8c4203d41b4
2,060
hpp
C++
ngraph/core/include/ngraph/op/util/fused_op.hpp
ethz-asl/openvino
b4ad7a1755b4799f92ef042bacc719ec3c0c1cbd
[ "Apache-2.0" ]
1
2020-07-07T10:13:00.000Z
2020-07-07T10:13:00.000Z
ngraph/core/include/ngraph/op/util/fused_op.hpp
ethz-asl/openvino
b4ad7a1755b4799f92ef042bacc719ec3c0c1cbd
[ "Apache-2.0" ]
105
2020-06-04T00:23:29.000Z
2022-02-21T13:04:33.000Z
ngraph/core/include/ngraph/op/util/fused_op.hpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
3
2021-04-25T06:52:41.000Z
2021-05-07T02:01:44.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/op/op.hpp" namespace ngraph { namespace op { namespace util { /// \brief Abstract base class for fused ops, i.e ops that can be broken down into core /// ngraph ops /// class NGRAPH_DEPRECATED( "FusedOp approach was deprecated! " "Please use inheritance from usual Op instead of FusedOp") NGRAPH_API FusedOp : public Op { public: NGRAPH_RTTI_DECLARATION; // Fused op decomposition can be performed in the presence of // partial shapes virtual bool can_decompose_with_partial_shapes() { return false; } // Shape inference that will use fused op decomposition to infer // shapes and types of output elements. Ops can choose to override // and provide a more direct implementation. void validate_and_infer_types() override; // Pre-validation hook that will be invoked before op // decomposition in validate_and_infer_types(). // Can be used for attribute validation and setting types/shapes // that can be inferred without requiring op decomposition. // Can also be used to set shape specialization hints // (set_input_is_relevant_to_shape()) virtual void pre_validate_and_infer_types() {} // Post-validation hook that will be invoked after op decomposition // in validate_and_infer_types(). virtual void post_validate_and_infer_types() {} protected: FusedOp(); /// \brief Constructs a FusedOp /// FusedOp(const OutputVector& args); }; } // namespace util } // namespace op } // namespace ngraph
37.454545
99
0.56699
[ "shape" ]
8dc06c8fe84207745bb6a1c9baa9322114a616d8
30,397
hpp
C++
include/public/coherence/net/cache/CachingMap.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/public/coherence/net/cache/CachingMap.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/public/coherence/net/cache/CachingMap.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_CACHING_MAP_HPP #define COH_CACHING_MAP_HPP #include "coherence/lang.ns" #include "coherence/internal/net/NamedCacheDeactivationListener.hpp" #include "coherence/net/cache/CacheMap.hpp" #include "coherence/net/cache/SimpleCacheStatistics.hpp" #include "coherence/net/NamedCache.hpp" #include "coherence/util/AbstractMapListener.hpp" #include "coherence/util/Collection.hpp" #include "coherence/util/ConcurrentMap.hpp" #include "coherence/util/Filter.hpp" #include "coherence/util/List.hpp" #include "coherence/util/Map.hpp" #include "coherence/util/MapListener.hpp" #include "coherence/util/MapListenerSupport.hpp" #include "coherence/util/MultiplexingMapListener.hpp" #include "coherence/util/Set.hpp" #include "coherence/util/filter/CacheEventFilter.hpp" #include "coherence/util/filter/MapEventFilter.hpp" COH_OPEN_NAMESPACE3(coherence,net,cache) using coherence::internal::net::NamedCacheDeactivationListener; using coherence::net::NamedCache; using coherence::util::AbstractMapListener; using coherence::util::Collection; using coherence::util::ConcurrentMap; using coherence::util::Filter; using coherence::util::List; using coherence::util::Map; using coherence::util::MapListener; using coherence::util::MapListenerSupport; using coherence::util::MultiplexingMapListener; using coherence::util::Set; using coherence::util::filter::CacheEventFilter; using coherence::util::filter::MapEventFilter; /** * Map implementation that wraps two maps - a front map (assumed to be * "inexpensive" and probably "incomplete") and a back map (assumed to * be "complete" and "correct", but more "expensive") - using a * read-through/write-through approach. * * If the back map implements ObservableMap interface, the CachingMap provides * four different strategies of invalidating the front map entries that have * changed by other processes in the back map: * * listen_none strategy instructs the cache not to listen for invalidation * events at all. This is the best choice for raw performance and * scalability when business requirements permit the use of data which * might not be absolutely current. Freshness of data can be guaranteed * by use of a sufficiently brief eviction policy for the front map; * listen_present strategy instructs the CachingMap to listen to the * back map events related <b>only</b> to the items currently present in * the front map. This strategy works best when each instance of a front * map contains distinct subset of data relative to the other front map * instances (e.g. sticky data access patterns); * listen_all strategy instructs the CachingMap to listen to <b>all</b> * back map events. This strategy is optimal for read-heavy tiered access * patterns where there is significant overlap between the different * instances of front maps; * listen_auto strategy instructs the CachingMap implementation to switch * automatically between listen_present and listen_all strategies based * on the cache statistics. * listen_logical strategy instructs the CachingMap to listen to <b>all</b> * back map events that are <b>not synthetic</b>. A synthetic event could * be emitted as a result of eviction or expiration. With this * invalidation strategy, it is possible for the front map to contain * cache entries that have been synthetically removed from the back * (though any subsequent re-insertion will cause the corresponding * entries in the front map to be invalidated). * * The front map implementation is assumed to be thread safe; additionally * any modifications to the front map are allowed only after the corresponding * lock is acquired against the ControlMap. * * <b>Note:</b> NULL values are not cached in the front map and therefore this * implementation is not optimized for maps that allow NULL values to be * stored. * * @author tb 2008.06.12 */ class COH_EXPORT CachingMap : public class_spec<CachingMap, extends<Object>, implements<Map> > { friend class factory<CachingMap>; // ----- handle definitions (needed for nested classes) ----------------- public: typedef this_spec::Handle Handle; typedef this_spec::View View; typedef this_spec::Holder Holder; // ----- enums ---------------------------------------------------------- public: /** * Enum for invalidation strategies */ enum InvalidationStrategy { /** * No invalidation strategy. */ listen_none, /** * Invalidation strategy that instructs the CachingMap to listen * to the back map events related <b>only</b> to the items * currently present in the front map; this strategy serves best * when the changes to the back map come mostly from the * CachingMap itself. */ listen_present, /** * Invalidation strategy that instructs the CachingMap to listen * to <b>all</b> back map events; this strategy is preferred when * updates to the back map are frequent and with high probability * come from the outside of this CachingMap; for example multiple * CachingMap instances using the same back map with a large * degree of key set overlap between front maps. */ listen_all, /** * Invalidation strategy that instructs the CachingMap * implementation to switch automatically between listen_present * and listen_all strategies based on the cache statistics. */ listen_auto, /** * Invalidation strategy that instructs the CachingMap to listen * to <b>all</b> back map events that are <b>not synthetic</b>. A * synthetic event could be emitted as a result of eviction or * expiration. With this invalidation strategy, it is possible * for the front map to contain cache entries that have been * synthetically removed from the back (though any subsequent * re-insertion will cause the corresponding entries in the front * map to be invalidated). */ listen_logical }; // ----- constructors --------------------------------------------------- protected: /** * Construct a CachingMap using two specified maps: * <i>FrontMap</i> (aka "cache", "near" or "shallow") and * <i>BackMap</i> (aka "actual", "real" or "deep"). * * If the BackMap implements the ObservableMap interface a listener * will be added to the BackMap to invalidate FrontMap items updated * [externally] in the back map using the listen_auto strategy. * * If no MapControl is specified then a new one is created. * * @param hMapFront front map * @param hMapBack back map * @param strategy specifies the strategy used for the front map * invalidation; valid values are LISTEN_* * constants * @param hMapControl the ConcurrentMap to keep track of front map * updates; may be NULL */ CachingMap(CacheMap::Handle hMapFront, CacheMap::Handle hMapBack, InvalidationStrategy strategy = listen_auto, ConcurrentMap::Handle hMapControl = NULL); // ----- life-cycle ----------------------------------------------------- public: /** * Release the CachingMap. If the BackMap implements an ObservableMap * calling this method is necessary to remove the BackMap listener. * Any access to the CachingMap which has been released will cause * IllegalStateException. * * @throws IllegalStateException if accessing the CachingMap * which has been released */ virtual void release(); // ----- accessors ------------------------------------------------------ public: /** * Obtain the front map reference. * * <b>Note:</b> direct modifications of the returned map may cause an * unpredictable behavior of the CachingMap. * * @return the front Map */ virtual CacheMap::Handle getFrontMap() const; /** * Obtain the back map reference. * * <b>Note:</b> direct modifications of the returned map may cause an * unpredictable behavior of the CachingMap. * * @return the back Map */ virtual CacheMap::Handle getBackMap() const; /** * Obtain the invalidation strategy used by this CachingMap. * * @return one of LISTEN_* values */ virtual InvalidationStrategy getInvalidationStrategy() const; /** * Obtain the ConcurrentMap that should be used to synchronize * the front map modification access. * * @return a ConcurrentMap controlling the front map modifications */ virtual ConcurrentMap::Handle getControlMap() const; /** * Obtain the CacheStatistics for this cache. * * @return a CacheStatistics object */ virtual CacheStatistics::Handle getCacheStatistics() const; /** * Determine the rough number of front map invalidation hits since * the cache statistics were last reset. * * An invalidation hit is an externally induced map event for an entry * that exists in the front map. * * @return the number of cache invalidation hits */ virtual int64_t getInvalidationHits() const; /** * Determine the rough number of front map invalidation misses since * the cache statistics were last reset. * * An invalidation miss is an externally induced map event for an * entry that does not exists in the front map. * * @return the number of cache invalidation misses */ virtual int64_t getInvalidationMisses() const; /** * Determine the total number of registerListener(Object::View vKey) * operations since the cache statistics were last reset. * * @return the total number of listener registrations */ virtual int64_t getTotalRegisterListener() const; protected: /** * Determine if changes to the back map affect the front map so that * data in the front map stays in sync. * * @return true if the front map has a means to stay in sync with the * back map so that it does not contain stale data */ virtual bool isCoherent() const; // ----- CachingMap interface ------------------------------------------- protected: /** * Invalidate the key from the front. The caller must have the key * locked. * * @param vKey the key to invalidate */ virtual void invalidateFront(Object::View vKey) const; /** * Helper method used by put() and putAll() to perform common * maintanence tasks after completing an operation against the back. * This includes removing the keys from the control map, and * evaluating if it is safe to update the front with the "new" value. * The implementation makes use of the following assumption: if * listEvents == IGNORE_LIST then oKey does not exist in the * front, and there is no key based listener for it. Any key passed * to this method must be locked in the control map by the caller. * * @param vKey the key * @param ohValue the new value * @param hlistEvents the event list associated with the key * @param cMillis the number of milliseconds until the cache entry * will expire */ virtual void finalizePut(Object::View vKey, Object::Holder ohValue, List::Handle hlistEvents, int64_t cMillis); public: /** * Implementation of put method that optionally skips the return value * retrieval and allows to specify an expiry for the cache entry. * * @param vKey the key * @param ohValue the value * @param fReturn if true, the return value is required; otherwise * the return value will be ignored * @param cMillis the number of milliseconds until the cache entry * will expire * @return previous value (if required) * * @throws UnsupportedOperationException if the requested expiry is a * positive value and either the front map or the back map * implementations do not support the expiration functionality */ virtual Object::Holder put(Object::View vKey, Object::Holder ohValue, bool fReturn, int64_t cMillis); /** * Get all the specified keys, if they are in the cache. For each key * that is in the cache, that key and its corresponding value will be * placed in the map that is returned by this method. The absence of * a key in the returned map indicates that it was not in the cache, * which may imply (for caches that can load behind the scenes) that * the requested data could not be loaded. * * <b>Note:</b> this implementation does not differentiate between * missing keys or NULL values stored in the back map; in both cases * the returned map will not contain the corresponding entry. * * @param vColKeys a collection of keys that may be in the named * cache * * @return a Map of keys to values for the specified keys passed in * <tt>col</tt> */ virtual Map::View getAll(Collection::View vColKeys) const; // ----- Map interface -------------------------------------------------- public: /** * {@inheritDoc} */ virtual size32_t size() const; /** * {@inheritDoc} */ virtual bool isEmpty() const; /** * {@inheritDoc} */ virtual bool containsKey(Object::View vKey) const; /** * {@inheritDoc} */ virtual bool containsValue(Object::View vValue) const; /** * {@inheritDoc} */ virtual Object::Holder get(Object::View vKey) const; /** * {@inheritDoc} */ virtual Object::Holder get(Object::View vKey); /** * {@inheritDoc} */ virtual Object::Holder put(Object::View vKey, Object::Holder ohValue); /** * {@inheritDoc} */ virtual Object::Holder remove(Object::View vKey); using Map::remove; /** * {@inheritDoc} */ virtual void putAll(Map::View vMap); /** * {@inheritDoc} */ virtual void clear(); /** * {@inheritDoc} */ virtual Set::View keySet() const; /** * {@inheritDoc} */ virtual Set::Handle keySet(); /** * {@inheritDoc} */ virtual Collection::View values() const; /** * {@inheritDoc} */ virtual Collection::Handle values(); /** * {@inheritDoc} */ virtual Set::View entrySet() const; /** * {@inheritDoc} */ virtual Set::Handle entrySet(); // ----- Object interface ----------------------------------------------- public: /** * {@inheritDoc} */ virtual TypedHandle<const String> toString() const; protected: /** * {@inheritDoc} */ virtual void onInit(); // ----- back map listener support -------------------------------------- public: /** * Register the global back map listener. */ virtual void registerListener() const; /** * Unregister the global back map listener. */ virtual void unregisterListener() const; /** * Register the back map listener for the specified key. * * @param vKey the key */ virtual void registerListener(Object::View vKey) const; /** * Register the back map listeners for the specified set of keys. * * @param hSetKeys the key set * * @since 12.2.1 */ virtual void registerListeners(Set::Handle hSetKeys) const; /** * Unregister the back map listener for the specified key. * * @param vKey the key */ virtual void unregisterListener(Object::View vKey) const; /** * Unregister the back map listener for the specified keys. * * Note: all the keys in the passed-in set must be locked and will be * unlocked. * * @param hSetKeys Set of keys to unregister (and unlock) * * @since 12.2.1 */ virtual void unregisterListeners(Set::Handle hSetKeys) const; /** * Register the global front map listener. */ virtual void registerFrontListener() const; /** * Unregister the global front map listener. */ virtual void unregisterFrontListener() const; /** * Register back cache deactivation listener. */ virtual void registerDeactivationListener() const; /** * Unregister back cache deactivation listener. */ virtual void unregisterDeactivationListener() const; /** * Reset the front map */ virtual void resetFrontMap(); /** * Ensure that a strategy has been choosen and that any appropriate * global listeners have been registered. * * @return the current strategy */ virtual InvalidationStrategy ensureInvalidationStrategy() const; /** * Reset the "current invalidation strategy" flag. * * This method should be called <b>only</b> while the access to the * front map is fully synchronzied and the front map is empty to * prevent stalled data. */ virtual void resetInvalidationStrategy(); // ----- inner class: PrimingListener ----------------------------------- protected: /** * MapListener for back map responsible for keeping the front map * coherent with the back map. This listener is registered as a * synchronous listener for lite events (carrying only a key) and * generates a "priming" event when registered. * * @since 12.2.1 */ class PrimingListener : public class_spec<PrimingListener, extends<MultiplexingMapListener>, implements<MapListenerSupport::PrimingListener> > { friend class factory<PrimingListener>; // ----- constructors --------------------------------------- protected: /** * Construct a PrimingListener * * @param hMap the map associated with this listener */ PrimingListener(CachingMap::Handle hMap); // ----- MultiplexingMapListener interface ------------------ /** * {@inheritDoc} */ virtual void onMapEvent(MapEvent::View vEvent); // ---- data members ---------------------------------------- protected: /** * The map associated with this listener. */ WeakHandle<CachingMap> m_whMap; }; // ----- inner class: SimpleListener -------------------------------- protected: /** * MapListener for back map responsible for keeping the front map * coherent with the back map. This listener is registered as a * synchronous listener for lite events (carrying only a key). */ class SimpleListener : public class_spec<SimpleListener, extends<MultiplexingMapListener>, implements<MapListenerSupport::SynchronousListener> > { friend class factory<SimpleListener>; // ----- constructors --------------------------------------- protected: /** * Construct a SimpleListener * * @param hMap the map associated with this listener */ SimpleListener(CachingMap::Handle hMap); // ----- MultiplexingMapListener interface ------------------ /** * {@inheritDoc} */ virtual void onMapEvent(MapEvent::View vEvent); // ---- data members ---------------------------------------- protected: /** * The map associated with this listener. */ WeakHandle<CachingMap> m_whMap; }; // ----- inner class: DeactivationListener -------------------------- protected: /** * DeactivationListener for the back NamedCache. * The primary goal of that listener is invalidation of the front map * when the back cache is destroyed or all storage nodes are stopped. */ class DeactivationListener : public class_spec<DeactivationListener, extends<AbstractMapListener>, implements<NamedCacheDeactivationListener> > { friend class factory<DeactivationListener>; // ----- constructors --------------------------------------- protected: /** * Construct a DeactivationListener * * @param hMap the map associated with this listener */ DeactivationListener(CachingMap::Handle hMap); // ----- NamedCacheDeactivationListener interface ------------------ /** * {@inheritDoc} */ virtual void entryDeleted(MapEvent::View vEvent); /** * {@inheritDoc} */ virtual void entryUpdated(MapEvent::View vEvent); // ---- data members ---------------------------------------- protected: /** * The map associated with this listener. */ WeakHandle<CachingMap> m_whMap; }; // ----- inner class: FrontMapListener ---------------------------------- protected: /** * MapListener for back map responsible for keeping the front map * coherent with the back map. This listener is registered as a * synchronous listener for lite events (carrying only a key). */ class FrontMapListener : public class_spec<FrontMapListener, extends<AbstractMapListener>, implements<MapListenerSupport::SynchronousListener> > { friend class factory<FrontMapListener>; // ----- constructors --------------------------------------- protected: /** * Construct a FrontMapListener * * @param hMap the map associated with this listener */ FrontMapListener(CachingMap::Handle hMap); // ----- MapListener interface ------------------------------ public: /** * {@inheritDoc} */ virtual void entryDeleted(MapEvent::View vEvent); // ---- helper registration methods ------------------------- public: /** * Register this listener with the "front" map. */ virtual void registerWithMap(); /** * Unregister this listener with the "front" map. */ virtual void unregisterFromMap(); // ---- data members ---------------------------------------- protected: /** * The filter associated with this listener. */ FinalView<Filter> f_vFilter; /** * The map associated with this listener. */ WeakHandle<CachingMap> m_whMap; }; // ----- listener support ----------------------------------------------- protected: /** * Factory pattern: instantiate back map listener. * * @param strategy the strategy to instantiate a back map listener for * * @return an instance of back map listener responsible for keeping * the front map coherent with the back map */ virtual MapListener::Handle instantiateBackMapListener(InvalidationStrategy strategy); /** * Factory pattern: instantiate front map listener. * * @return an instance of front map listener */ virtual FrontMapListener::Handle instantiateFrontMapListener(); /** * Validate the front map entry for the specified back map event. * * @param vEvent the MapEvent from the back map */ virtual void validate(MapEvent::View vEvent); /** * Set up a thread local Set to hold all the keys that might be evicted * from the front cache. * * @return a Set to hold all the keys in the ThreadLocal object or null * if the bulk unregistering is not needed * * @since 12.2.1 */ virtual Set::Handle setKeyHolder() const; /** * Remove the key holder from the ThreadLocal object. * * @since 12.2.1 */ virtual void removeKeyHolder() const; /** * Check if the specified event is a "priming" one. * * @since 12.2.1 */ static bool isPriming(MapEvent::View vEvent); // ----- constants and data fields ------------------------------------- protected : /** * The "back" map, considered to be "complete" yet "expensive" to * access. */ mutable FinalHandle<CacheMap> f_hMapBack; /** * The "front" map, considered to be "incomplete" yet "inexpensive" to * access. */ mutable FinalHandle<CacheMap> f_hMapFront; /** * The invalidation strategy that this map is to use. */ mutable InvalidationStrategy m_strategyTarget; /** * The current invalidation strategy, which at times could be different * from the target strategy. */ mutable InvalidationStrategy m_strategyCurrent; /** * An optional listener for the "back" map. */ mutable MemberHandle<MapListener> m_hListener; /** * An optional Simplelistener for the "back" map. * @see note in CachingMap::onInit() * * @since 12.2.1 */ mutable MemberHandle<MapListener> m_hSimpleListener; /** * An optional DeactivationListener for the "back" map. * @see note in CachingMap::onInit() * * @since 12.1.3 */ mutable MemberHandle<DeactivationListener> m_hListenerDeactivation; /** * An optional listener for the "front" map. */ mutable FinalHandle<FrontMapListener> f_hListenerFront; /** * A filter that selects events for the back-map listener. */ mutable MemberHandle<Filter> m_hFilterListener; /** * The ConcurrentMap to keep track of front map updates. * Values are list of events received by the listener while the * corresponding key was locked. Use of LOCK_ALL is restricited to * non-blocking operations to prevent deadlock with the service thread. */ mutable FinalHandle<ConcurrentMap> f_hMapControl; /** * The CacheStatistics object maintained by this cache. */ mutable FinalHandle<SimpleCacheStatistics> f_hStats; /** * The rough (ie unsynchronized) number of times the front map entries * that were present in the front map were invalidated by the listener. */ mutable /*volatile stat*/ int64_t m_cInvalidationHits; /** * The rough (ie unsynchronized) number of times the front map entries * that were absent in the front map received invalidation event. */ mutable /*volatile stat*/ int64_t m_cInvalidationMisses; /** * The total number of registerListener(oKey) operations. */ mutable /*volatile stat*/ int64_t m_cRegisterListener; /** * True if the cache has been released. */ bool m_fReleased; /** * The ThreadLocal to hold all the keys that are evicted while the front cache * is updated during get or getAll operation. * * @since 12.2.1 */ mutable FinalHandle<ThreadLocalReference> f_htloKeys; // ----- constants ------------------------------------------------------ protected : /** * A unique Object that serves as a control key for global operations * such as clear and release and synchronization point for the current * strategy change. */ FinalView<Object> f_vKeyGlobal; }; COH_CLOSE_NAMESPACE3 #endif // COH_CACHING_MAP_HPP
33.403297
94
0.564003
[ "object" ]
8dc2d25836fffcc3a362a7bf46e1574b16c99aef
61,718
cpp
C++
src/nn/wasm/src/bind/src/binding.cpp
akineeic/webml-polyfill
a58f9f5340ca87eca4cda18db019f42752317f9e
[ "Apache-2.0" ]
162
2018-03-30T00:57:00.000Z
2022-01-28T08:04:55.000Z
src/nn/wasm/src/bind/src/binding.cpp
akineeic/webml-polyfill
a58f9f5340ca87eca4cda18db019f42752317f9e
[ "Apache-2.0" ]
1,347
2018-03-29T02:24:39.000Z
2021-09-16T07:44:59.000Z
src/nn/wasm/src/bind/src/binding.cpp
ibelem/webml-polyfill
aaf1ba4f5357eaf6e89bf9990f5bdfb543cd2bc2
[ "Apache-2.0" ]
71
2018-04-02T05:40:28.000Z
2022-03-14T04:19:05.000Z
#include <emscripten/bind.h> #include <emscripten/val.h> #include "external/tensorflow/tensorflow/lite/kernels/cpu_backend_context.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/types.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/optimized/cpu_check.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/optimized/depthwiseconv_float.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/optimized/depthwiseconv_uint8.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/reference/prelu.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/reference/binary_function.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/reference/integer_ops/conv.h" #include "external/tensorflow/tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "fixedpoint/fixedpoint.h" #include "public/gemmlowp.h" #include <vector> #include <cmath> #include <iostream> using namespace emscripten; using namespace tflite; namespace binding_utils { static gemmlowp::GemmContext gemm_context; static CpuBackendContext cpu_backend_context; static CpuFlags cpu_flags; // help functions void set_gemm_context_threads_num(int threads_num) { gemm_context.set_max_num_threads(threads_num); } void set_cpu_context_threads_num(int max_num_threads) { cpu_backend_context.SetMaxNumThreads(max_num_threads); } // Operation Implements. template<typename T> void Maximum(const RuntimeShape& input1_shape, const T* input1_data, const T* input2_data, const RuntimeShape& output_shape, T* output_data) { auto input1_map = optimized_ops::MapAsVector(input1_data, input1_shape); auto input2_map = optimized_ops::MapAsVector(input2_data, output_shape); auto output_map = optimized_ops::MapAsVector(output_data, output_shape); output_map.array() = input1_map.array().max(input2_map.array()); } template <typename T> T ApplyPrelu(T input, T alpha) { return input >= 0.0 ? input : input * alpha; } constexpr size_t kStaticBufferSize = 1605632; char static_scratch_buffer[kStaticBufferSize]; #define CONV_PARAMETERS(Type) \ uint32_t height = inputShape.Dims(1); \ uint32_t width = inputShape.Dims(2); \ uint32_t filterHeight = filterShape.Dims(1); \ uint32_t filterWidth = filterShape.Dims(2); \ uint32_t outHeight = outputShape.Dims(1); \ uint32_t outWidth = outputShape.Dims(2); \ uint32_t inDepth = inputShape.Dims(3); \ \ uint32_t paddingHeight = (uint32_t)convParams.padding_values.height; \ uint32_t paddingWidth = (uint32_t)convParams.padding_values.width; \ \ tflite::RuntimeShape im2colDim(4); \ im2colDim.SetDim(0, (int)outputShape.Dims(0)); \ im2colDim.SetDim(1, (int)outputShape.Dims(1)); \ im2colDim.SetDim(2, (int)outputShape.Dims(2)); \ im2colDim.SetDim(3, (int)inDepth * filterHeight * filterWidth); \ \ Type* im2colData = nullptr; \ uint64_t im2colByteSize = sizeof(Type); \ std::unique_ptr<Type[]> im2colGuard; \ for (int i = 0; i < 4; i++) { \ im2colByteSize *= im2colDim.Dims(i); \ } \ /* http://b/77982879, tflite::optimized_ops::Conv uses int for offsets */ \ if (im2colByteSize >= 0x7fffffff) { \ throw std::string("Conv size is too large, not enough memory"); \ } \ if (im2colByteSize <= kStaticBufferSize) { \ im2colData = reinterpret_cast<Type*>(static_scratch_buffer); \ } else { \ im2colData = new (std::nothrow) Type[im2colByteSize / sizeof(Type)]; \ if (im2colData == nullptr) { \ throw std::string("Conv size is too large, not enough memory"); \ } \ im2colGuard.reset(im2colData); \ } // Convert int8 quantized values to uint8 assuming that the scale is the same // and the distance between offsets is 128. void convertInt8ToUInt8(const int8_t* input, std::vector<uint8_t>* output) { assert(input != nullptr); assert(output != nullptr); for (int i = 0; i < output->size(); ++i) { (*output)[i] = static_cast<uint8_t>(static_cast<int32_t>(input[i]) + 128); } } // Convert uint8 quantized values to int8 assuming that the scale is the same // and the distance between offsets is 128. void convertUInt8ToInt8(const std::vector<uint8_t>& input, int8_t* output) { assert(output != nullptr); for (int i = 0; i < input.size(); ++i) { output[i] = static_cast<int8_t>(static_cast<int32_t>(input[i]) - 128); } } // Operation wrappers. void addFloat32Wrapper(const ArithmeticParams& op_params, const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::Add(op_params, input1_shape, (const float*) input1_data, input2_shape, (const float*) input2_data, output_shape, (float*) output_data); } void addUint8Wrapper(const ArithmeticParams& op_params, const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::Add(op_params, input1_shape, (const uint8_t*) input1_data, input2_shape, (const uint8_t*) input2_data, output_shape, (uint8_t*) output_data); } void broadCastAddFloat32Wrapper(const ArithmeticParams& op_params, const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::BroadcastAdd4DSlow(op_params, input1_shape, (const float*) input1_data, input2_shape, (const float*) input2_data, output_shape, (float*) output_data); } void mulFloat32Wrapper(const ArithmeticParams& op_params, const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::Mul(op_params, input1_shape, (const float*) input1_data, input2_shape, (const float*) input2_data, output_shape, (float*) output_data); } void broadCastMulFloat32Wrapper(const ArithmeticParams& op_params, const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::BroadcastMul4DSlow(op_params, input1_shape, (const float*) input1_data, input2_shape, (const float*) input2_data, output_shape, (float*) output_data); } void floorFloat32Wrapper(const RuntimeShape& input_shape, const intptr_t inputData, const RuntimeShape& output_shape, intptr_t outputData) { optimized_ops::Floor(input_shape, (const float*)inputData, output_shape, (float*)outputData); } void depthwiseConvFloat32Wrapper(const DepthwiseParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { tflite::GetCpuFlags(&cpu_backend_context, &cpu_flags); optimized_ops::DepthwiseConv(convParams, inputShape, (const float*)inputData, filterShape, (const float*)filterData, biasShape, (const float*)biasData, outputShape, (float*)outputData, cpu_flags); } void depthwiseConvUint8Wrapper(const DepthwiseParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::DepthwiseConv(convParams, inputShape, (const uint8_t*)inputData, filterShape, (const uint8_t*)filterData, biasShape, (const int32_t*)biasData, outputShape, (uint8_t*)outputData, &gemm_context); } void depthwiseConvInt8Wrapper(const DepthwiseParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { DepthwiseParams uint8ConvParams = convParams; std::vector<uint8_t> unsignedInput(inputShape.DimensionsCount()); convertInt8ToUInt8((const int8_t*)inputData, &unsignedInput); uint8ConvParams.input_offset += 128; std::vector<uint8_t> unsignedFilter(filterShape.DimensionsCount()); convertInt8ToUInt8((const int8_t*)filterData, &unsignedFilter); uint8ConvParams.weights_offset += 128; std::vector<uint8_t> unsignedOutput(outputShape.DimensionsCount()); uint8ConvParams.output_offset += 128; optimized_ops::DepthwiseConv(convParams, inputShape, unsignedInput.data(), filterShape, unsignedFilter.data(), biasShape, (const int32_t*)biasData, outputShape, unsignedOutput.data(), &gemm_context); convertUInt8ToInt8(unsignedOutput, (int8_t*)outputData); } template <typename T> void depthwiseConvQuant8PerChannelNhwc(const DepthwiseParams& convParams, const int32_t* outputMultiplier, const int32_t* outputShift, const RuntimeShape& inputShape, const T* inputData, const RuntimeShape& filterShape, const int8_t* filterData, const RuntimeShape& biasShape, const int32_t* biasData, const RuntimeShape& outputShape, T* outputData) { int32_t depthMultiplier = convParams.depth_multiplier; uint32_t numBatches = inputShape.Dims(0); uint32_t inputHeight = inputShape.Dims(1); uint32_t inputWidth = inputShape.Dims(2); uint32_t inputDepth = inputShape.Dims(3); uint32_t filterHeight = filterShape.Dims(1); uint32_t filterWidth = filterShape.Dims(2); uint32_t filterDepth = filterShape.Dims(3); uint32_t outputHeight = outputShape.Dims(1); uint32_t outputWidth = outputShape.Dims(2); uint32_t outputDepth = outputShape.Dims(3); int32_t paddingLeft = convParams.padding_values.width; int32_t paddingRight = convParams.padding_values.width; int32_t paddingTop = convParams.padding_values.height; int32_t paddingBottom = convParams.padding_values.height; int32_t strideWidth = convParams.stride_width; int32_t strideHeight = convParams.stride_height; int32_t dilationWidthFactor = convParams.dilation_width_factor; int32_t dilationHeightFactor = convParams.dilation_height_factor; int32_t inputOffset = convParams.input_offset; int32_t outputOffset = convParams.output_offset; int32_t output_activation_min = convParams.quantized_activation_min; int32_t output_activation_max = convParams.quantized_activation_max; const T* inputBase = inputData; T* outPtr = outputData; for (uint32_t b = 0; b < numBatches; b++) { for (uint32_t h = 0; h < outputHeight; h++) { for (uint32_t w = 0; w < outputWidth; w++) { for (uint32_t ic = 0; ic < inputDepth; ic++) { for (uint32_t m = 0; m < depthMultiplier; m++) { int32_t wInputOrigin = static_cast<int32_t>(w) * strideWidth - paddingLeft; int32_t hInputOrigin = static_cast<int32_t>(h) * strideHeight - paddingTop; const int oc = m + ic * depthMultiplier; int32_t sum = 0.0f; for (uint32_t i = 0; i < filterHeight; i++) { for (uint32_t j = 0; j < filterWidth; j++) { int32_t hInput = hInputOrigin + dilationHeightFactor * static_cast<int32_t>(i); int32_t wInput = wInputOrigin + dilationWidthFactor * static_cast<int32_t>(j); if (hInput >= 0 && hInput < static_cast<int32_t>(inputHeight) && wInput >= 0 && wInput < static_cast<int32_t>(inputWidth)) { uint32_t filterIndex = i * filterWidth * filterDepth + j * filterDepth + oc; uint32_t inputIndex = hInput * inputWidth * inputDepth + wInput * inputDepth + ic; sum += (static_cast<int32_t>(filterData[filterIndex])) * (static_cast<int32_t>(inputBase[inputIndex]) + inputOffset); } } } sum += biasData[oc]; sum = tflite::MultiplyByQuantizedMultiplier(sum, outputMultiplier[oc], -outputShift[oc]); sum += outputOffset; sum = std::max(std::min(sum, output_activation_max), output_activation_min); outPtr[m] = static_cast<T>(sum); } outPtr += depthMultiplier; } } } inputBase += inputHeight * inputWidth * inputDepth; } } void depthwiseConvUint8PerChannelWrapper(const DepthwiseParams& convParams, const intptr_t outputMultiplierData, const intptr_t outputShiftData, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { depthwiseConvQuant8PerChannelNhwc(convParams, (const int32_t*)outputMultiplierData, (const int32_t*)outputShiftData, inputShape, (const uint8_t*)inputData, filterShape, (const int8_t*)filterData, biasShape, (const int32_t*)biasData, outputShape, (uint8_t*)outputData); } void depthwiseConvInt8PerChannelWrapper(const DepthwiseParams& convParams, const intptr_t outputMultiplierData, const intptr_t outputShiftData, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { depthwiseConvQuant8PerChannelNhwc(convParams, (const int32_t*)outputMultiplierData, (const int32_t*)outputShiftData, inputShape, (const int8_t*)inputData, filterShape, (const int8_t*)filterData, biasShape, (const int32_t*)biasData, outputShape, (int8_t*)outputData); } void convFloat32Wrapper(const ConvParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { CONV_PARAMETERS(float); optimized_ops::Conv(convParams, inputShape, (const float*)inputData, filterShape, (const float*)filterData, biasShape, (const float*)biasData, outputShape, (float*)outputData, im2colDim, (float*)im2colData, &cpu_backend_context); } void convUint8Wrapper(const ConvParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { CONV_PARAMETERS(uint8_t); optimized_ops::Conv(convParams, inputShape, (const uint8_t*)inputData, filterShape, (const uint8_t*)filterData, biasShape, (const int32_t*)biasData, outputShape, (uint8_t*)outputData, im2colDim, (uint8_t*)im2colData, &cpu_backend_context); } void convInt8Wrapper(const ConvParams& convParams, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { ConvParams uint8ConvParams = convParams; std::vector<uint8_t> unsignedInput(inputShape.DimensionsCount()); convertInt8ToUInt8((const int8_t*)inputData, &unsignedInput); uint8ConvParams.input_offset += 128; std::vector<uint8_t> unsignedFilter(filterShape.DimensionsCount()); convertInt8ToUInt8((const int8_t*)filterData, &unsignedFilter); uint8ConvParams.weights_offset += 128; std::vector<uint8_t> unsignedOutput(outputShape.DimensionsCount()); uint8ConvParams.output_offset += 128; CONV_PARAMETERS(uint8_t); optimized_ops::Conv(uint8ConvParams, inputShape, unsignedInput.data(), filterShape, unsignedFilter.data(), biasShape, (const int32_t*)biasData, outputShape, unsignedOutput.data(), im2colDim, (uint8_t*)im2colData, &cpu_backend_context); convertUInt8ToInt8(unsignedOutput, (int8_t*)outputData); } void convUint8PerChannelWrapper(const ConvParams& convParams, const intptr_t outputMultiplierData, const intptr_t outputShiftData, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { uint32_t numBatches = inputShape.Dims(0); uint32_t inputHeight = inputShape.Dims(1); uint32_t inputWidth = inputShape.Dims(2); uint32_t inputDepth = inputShape.Dims(3); uint32_t filterHeight = filterShape.Dims(1); uint32_t filterWidth = filterShape.Dims(2); uint32_t filterDepth = filterShape.Dims(3); uint32_t outputHeight = outputShape.Dims(1); uint32_t outputWidth = outputShape.Dims(2); uint32_t outputDepth = outputShape.Dims(3); int32_t paddingLeft = convParams.padding_values.width; int32_t paddingRight = convParams.padding_values.width; int32_t paddingTop = convParams.padding_values.height; int32_t paddingBottom = convParams.padding_values.height; int32_t strideWidth = convParams.stride_width; int32_t strideHeight = convParams.stride_height; int32_t dilationWidthFactor = convParams.dilation_width_factor; int32_t dilationHeightFactor = convParams.dilation_height_factor; int32_t inputOffset = convParams.input_offset; int32_t outputOffset = convParams.output_offset; int32_t output_activation_min = convParams.quantized_activation_min; int32_t output_activation_max = convParams.quantized_activation_max; const uint8_t* inputBase = (const uint8_t*)inputData; const int32_t* outputMultiplier = (const int32_t*)outputMultiplierData; const int32_t* outputShift = (const int32_t*)outputShiftData; uint8_t* outPtr = (uint8_t*)outputData; const int32_t* biasBase = (const int32_t*)biasData; for (uint32_t b = 0; b < numBatches; b++) { for (uint32_t h = 0; h < outputHeight; h++) { for (uint32_t w = 0; w < outputWidth; w++) { const int8_t* filterBase = (const int8_t*)filterData; for (uint32_t d = 0; d < outputDepth; d++) { int32_t wInputOrigin = static_cast<int32_t>(w) * strideWidth - paddingLeft; int32_t hInputOrigin = static_cast<int32_t>(h) * strideHeight - paddingTop; int32_t sum = 0.0f; for (uint32_t i = 0; i < filterHeight; i++) { for (uint32_t j = 0; j < filterWidth; j++) { for (uint32_t k = 0; k < filterDepth; k++) { int32_t hInput = hInputOrigin + dilationHeightFactor * static_cast<int32_t>(i); int32_t wInput = wInputOrigin + dilationWidthFactor * static_cast<int32_t>(j); uint32_t dInput = k; if (hInput >= 0 && hInput < static_cast<int32_t>(inputHeight) && wInput >= 0 && wInput < static_cast<int32_t>(inputWidth)) { uint32_t filterIndex = i * filterWidth * filterDepth + j * filterDepth + k; uint32_t inputIndex = hInput * inputWidth * inputDepth + wInput * inputDepth + dInput; sum += (static_cast<int32_t>(filterBase[filterIndex])) * (static_cast<int32_t>(inputBase[inputIndex]) + inputOffset); } } } } sum += biasBase[d]; sum = tflite::MultiplyByQuantizedMultiplier(sum, outputMultiplier[d], -outputShift[d]); sum += outputOffset; sum = std::max(std::min(sum, output_activation_max), output_activation_min); outPtr[d] = static_cast<uint8_t>(sum); filterBase += filterHeight * filterWidth * filterDepth; } outPtr += outputDepth; } } inputBase += inputHeight * inputWidth * inputDepth; } } // FIXME: tflite::reference_integer_ops::ConvPerChannel doesn't handle // min and max value correctly, copy its implementation here and fix it. void ConvPerChannel( const ConvParams& params, const int32* output_multiplier, const int32* output_shift, const RuntimeShape& input_shape, const int8* input_data, const RuntimeShape& filter_shape, const int8* filter_data, const RuntimeShape& bias_shape, const int32* bias_data, const RuntimeShape& output_shape, int8* output_data) { // Get parameters. const int32 input_offset = params.input_offset; // r = s(q - Z) const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int dilation_width_factor = params.dilation_width_factor; const int dilation_height_factor = params.dilation_height_factor; const int pad_width = params.padding_values.width; const int pad_height = params.padding_values.height; const int32 output_offset = params.output_offset; // Set min and max value of the output. const int32 output_activation_min = params.quantized_activation_min; const int32 output_activation_max = params.quantized_activation_max; // Sanity check. TFLITE_DCHECK_LE(output_activation_min, output_activation_max); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3); const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3); if (bias_data) { TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); } // Check dimensions of the tensors. const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); for (int batch = 0; batch < batches; ++batch) { for (int out_y = 0; out_y < output_height; ++out_y) { for (int out_x = 0; out_x < output_width; ++out_x) { for (int out_channel = 0; out_channel < output_depth; ++out_channel) { const int in_x_origin = (out_x * stride_width) - pad_width; const int in_y_origin = (out_y * stride_height) - pad_height; int32 acc = 0; for (int filter_y = 0; filter_y < filter_height; ++filter_y) { for (int filter_x = 0; filter_x < filter_width; ++filter_x) { for (int in_channel = 0; in_channel < input_depth; ++in_channel) { const int in_x = in_x_origin + dilation_width_factor * filter_x; const int in_y = in_y_origin + dilation_height_factor * filter_y; // Zero padding by omitting the areas outside the image. const bool is_point_inside_image = (in_x >= 0) && (in_x < input_width) && (in_y >= 0) && (in_y < input_height); if (is_point_inside_image) { int32 input_val = input_data[Offset(input_shape, batch, in_y, in_x, in_channel)]; int32 filter_val = filter_data[Offset(filter_shape, out_channel, filter_y, filter_x, in_channel)]; // Accumulate with 32 bits accumulator. // In the nudging process during model quantization, we force // real value of 0.0 be represented by a quantized value. This // guarantees that the input_offset is a int8, even though it // is represented using int32. // int32 += int8 * (int8 - int8) so the highest value we can // get from each accumulation is [-127, 127] * ([-128, 127] - // [-128, 127]), which is [-32512, 32512]. log2(32512) // = 14.98, which means we can accumulate at least 2^16 // multiplications without overflow. The accumulator is // applied to a filter so the accumulation logic will hold as // long as the filter size (filter_y * filter_x * in_channel) // does not exceed 2^16, which is the case in all the models // we have seen so far. // TODO(jianlijianli): Add a check to make sure the // accumulator depth is smaller than 2^16. acc += filter_val * (input_val + input_offset); } } } } if (bias_data) { acc += bias_data[out_channel]; } acc = MultiplyByQuantizedMultiplier( acc, output_multiplier[out_channel], output_shift[out_channel]); acc += output_offset; acc = std::max(acc, output_activation_min); acc = std::min(acc, output_activation_max); output_data[Offset(output_shape, batch, out_y, out_x, out_channel)] = static_cast<int8_t>(acc); } } } } } void convInt8PerChannelWrapper(const ConvParams& convParams, const intptr_t outputMultiplierData, const intptr_t outputShiftData, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& filterShape, const intptr_t filterData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { ConvPerChannel( convParams, (const int32_t*)outputMultiplierData, (const int32_t*)outputShiftData, inputShape, (const int8_t*)inputData, filterShape, (const int8_t*)filterData, biasShape, (const int32_t*)biasData, outputShape, (int8_t*)outputData); } void averagePoolFloat32Wrapper(const PoolParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::AveragePool(op_params, inputShape, (const float*)inputData, outputShape, (float*)outputData); } void averagePoolUint8Wrapper(const PoolParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::AveragePool(op_params, inputShape, (const uint8_t*)inputData, outputShape, (uint8_t*)outputData); } void averagePoolInt8Wrapper(const PoolParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { tflite::reference_integer_ops::AveragePool(op_params, inputShape, (const int8_t*)inputData, outputShape, (int8_t*)outputData); } void maxPoolFloat32Wrapper(const PoolParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::MaxPool(op_params, inputShape, (const float*)inputData, outputShape, (float*)outputData); } void maxPoolUint8Wrapper(const PoolParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::MaxPool(op_params, inputShape, (const uint8_t*)inputData, outputShape, (uint8_t*)outputData); } void softmaxFloat32Wrapper(const SoftmaxParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::Softmax(op_params, inputShape, (const float*)inputData, outputShape, (float*)outputData); } void softmaxUint8Wrapper(const SoftmaxParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::Softmax(op_params, inputShape, (const uint8_t*)inputData, outputShape, (uint8_t*)outputData); } void reshapeFloat32Wrapper(const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { // implement it by self due to no reshape op in tflite::optimized_ops uint32_t size_count = (uint32_t)(inputShape.FlatSize() * sizeof(float)); memcpy((float*)outputData, (const float*)inputData, size_count); } void reshapeUint8Wrapper(const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { // implement it by self due to no reshape op in tflite::optimized_ops uint32_t size_count = (uint32_t)(inputShape.FlatSize() * sizeof(uint8_t)); memcpy((uint8_t*)outputData, (const uint8_t*)inputData, size_count); } void concatenationFloat32Wrapper(const ConcatenationParams& op_params, const std::vector<RuntimeShape*> inputShapes, const std::vector<intptr_t>& inputDataPtrs, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::Concatenation<float>(op_params, inputShapes.data(), ((const std::vector<const float*>&)inputDataPtrs).data(), outputShape, (float*)outputData); } void concatenationUint8Wrapper(ConcatenationParams& op_params, const std::vector<RuntimeShape*> inputShapes, const std::vector<intptr_t>& inputDataPtrs, val inputScales, val inputZeroPoints, const RuntimeShape& outputShape, intptr_t outputData) { const std::vector<float>& inputScaleRef = vecFromJSArray<float>(inputScales); const std::vector<int32_t>& inputZeroPointRef = vecFromJSArray<int32_t>(inputZeroPoints); op_params.input_scale = inputScaleRef.data(); op_params.input_zeropoint = inputZeroPointRef.data(); optimized_ops::ConcatenationWithScaling(op_params, inputShapes.data(), ((const std::vector<const uint8_t*>&)inputDataPtrs).data(), outputShape, (uint8_t*)outputData); } void fullyConnectedFloat32Wrapper(const FullyConnectedParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& weightsShape, const intptr_t weightsData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::FullyConnected(op_params, inputShape, (const float*)inputData, weightsShape, (const float*)weightsData, biasShape, (const float*)biasData, outputShape, (float*)outputData, &cpu_backend_context); } void fullyConnectedUint8Wrapper(const FullyConnectedParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& weightsShape, const intptr_t weightsData, const RuntimeShape& biasShape, const intptr_t biasData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::FullyConnected(op_params, inputShape, (const uint8_t*)inputData, weightsShape, (const uint8_t*)weightsData, biasShape, (const int32_t*)biasData, outputShape, (uint8_t*)outputData, &cpu_backend_context); } void resizeBilinearFloat32Wrapper(const ResizeBilinearParams op_params, const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outSizeShape, const intptr_t outSizeData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::ResizeBilinear(op_params, inputShape, (const float*)inputData, outSizeShape, (const int32_t*)outSizeData, outputShape, (float*)outputData); } void tanhFloat32Wrapper(const RuntimeShape& inputShape, const intptr_t inputData, const RuntimeShape& outputShape, intptr_t outputData) { optimized_ops::Tanh(inputShape, (const float*)inputData, outputShape, (float*)outputData); } void maximumFloat32Wrapper(const RuntimeShape& input1_shape, const intptr_t input1_data, const RuntimeShape& input2_shape, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { binding_utils::Maximum(input1_shape, (const float*)input1_data, (const float*)input2_data, output_shape, (float*) output_data); } void batchToSpaceNDFloat32Wrapper(const RuntimeShape& unextended_input1_shape, const intptr_t input1_data, const RuntimeShape& unextended_input2_shape, const intptr_t block_shape_data, const RuntimeShape& unextended_input3_shape, const intptr_t crops_data, const RuntimeShape& unextended_output_shape, intptr_t output_data) { optimized_ops::BatchToSpaceND(unextended_input1_shape, (const float*) input1_data, unextended_input2_shape, (const int32_t*) block_shape_data, unextended_input3_shape, (const int32_t*) crops_data, unextended_output_shape, (float*) output_data); } void transposeFloat32Wrapper(const TransposeParams& op_params, const RuntimeShape& unextended_input_shape, const intptr_t input_data, const RuntimeShape& unextended_output_shape, intptr_t output_data) { optimized_ops::Transpose(op_params, unextended_input_shape, (const float*) input_data, unextended_output_shape, (float*) output_data); } void argMaxFloat32Wrapper(const RuntimeShape& input1_shape, const intptr_t input1_data, const intptr_t input2_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::ArgMax(input1_shape, (const float*) input1_data, (const int32_t*) input2_data, output_shape, (int32_t*) output_data); } void logisticFloat32Wrapper(const RuntimeShape& input_shape, const intptr_t inputData, const RuntimeShape& output_shape, intptr_t outputData) { optimized_ops::Logistic(input_shape, (const float*) inputData, output_shape, (float*) outputData); } void logisticUint8Wrapper(const LogisticParams& params, const RuntimeShape& input_shape, const intptr_t input_data, const RuntimeShape& output_shape, intptr_t output_data) { optimized_ops::Logistic(params, input_shape, (const uint8_t*) input_data, output_shape, (uint8_t*) output_data); } void preluFloat32Wrapper(const RuntimeShape& input_shape, const intptr_t input_data, const RuntimeShape& alpha_shape, const intptr_t alpha_data, const RuntimeShape& output_shape, intptr_t output_data) { reference_ops::BroadcastBinaryFunction4DSlow<float, float, float>( input_shape, (const float*) input_data, alpha_shape, (const float*) alpha_data, output_shape, (float*) output_data, ApplyPrelu<float>); } void preluUint8Wrapper(const PreluParams& params, const RuntimeShape& input_shape, const intptr_t input_data, const RuntimeShape& alpha_shape, const intptr_t alpha_data, const RuntimeShape& output_shape, intptr_t output_data) { reference_ops::BroadcastPrelu4DSlow(params, input_shape, (const uint8_t*) input_data, alpha_shape, (const uint8_t*) alpha_data, output_shape, (uint8_t*) output_data); } } EMSCRIPTEN_BINDINGS(nn) { constant("FLOAT_MAX", std::numeric_limits<float>::max()); constant("FLOAT_LOWEST", std::numeric_limits<float>::lowest()); constant("FLOAT_MIN", std::numeric_limits<float>::min()); constant("UINT8_MAX", std::numeric_limits<uint8_t>::max()); constant("UINT8_LOWEST", std::numeric_limits<uint8_t>::lowest()); constant("UINT8_MIN", std::numeric_limits<uint8_t>::min()); constant("INT32_MAX", std::numeric_limits<int32_t>::max()); constant("INT8_MIN", std::numeric_limits<int8_t>::min()); constant("INT8_MAX", std::numeric_limits<int8_t>::max()); class_<RuntimeShape>("RuntimeShape") .constructor<int>() .function("DimensionsCount", &RuntimeShape::DimensionsCount) .function("Dims", &RuntimeShape::Dims) .function("SetDim", &RuntimeShape::SetDim) ; value_object<PaddingValues>("PaddingValues") .field("width", &PaddingValues::width) .field("height", &PaddingValues::height) ; value_object<ConvParams>("ConvParams") .field("padding_values", &ConvParams::padding_values) .field("stride_width", &ConvParams::stride_width) .field("stride_height", &ConvParams::stride_height) .field("dilation_width_factor", &ConvParams::dilation_width_factor) .field("dilation_height_factor", &ConvParams::dilation_height_factor) // float activation params. .field("float_activation_min", &ConvParams::float_activation_min) .field("float_activation_max", &ConvParams::float_activation_max) // uint8 inference params. .field("input_offset", &ConvParams::input_offset) .field("weights_offset", &ConvParams::weights_offset) .field("output_offset", &ConvParams::output_offset) .field("output_multiplier", &ConvParams::output_multiplier) .field("output_shift", &ConvParams::output_shift) // uint8, etc, activation params. .field("quantized_activation_min", &ConvParams::quantized_activation_min) .field("quantized_activation_max", &ConvParams::quantized_activation_max) ; value_object<DepthwiseParams>("DepthwiseParams") .field("padding_values", &DepthwiseParams::padding_values) .field("stride_width", &DepthwiseParams::stride_width) .field("stride_height", &DepthwiseParams::stride_height) .field("dilation_width_factor", &DepthwiseParams::dilation_width_factor) .field("dilation_height_factor", &DepthwiseParams::dilation_height_factor) .field("depth_multiplier", &DepthwiseParams::depth_multiplier) // float activation params. .field("float_activation_min", &DepthwiseParams::float_activation_min) .field("float_activation_max", &DepthwiseParams::float_activation_max) // uint8 inference params. .field("input_offset", &DepthwiseParams::input_offset) .field("weights_offset", &DepthwiseParams::weights_offset) .field("output_offset", &DepthwiseParams::output_offset) .field("output_multiplier", &DepthwiseParams::output_multiplier) .field("output_shift", &DepthwiseParams::output_shift) // uint8, etc, activation params. .field("quantized_activation_min", &DepthwiseParams::quantized_activation_min) .field("quantized_activation_max", &DepthwiseParams::quantized_activation_max) ; value_object<SoftmaxParams>("SoftmaxParams") .field("beta", &SoftmaxParams::beta) // uint8 inference params. Used even when beta defaults to 1.0. .field("input_multiplier", &SoftmaxParams::input_multiplier) .field("input_left_shift", &SoftmaxParams::input_left_shift) .field("diff_min", &SoftmaxParams::diff_min) ; value_object<PoolParams>("PoolParams") .field("padding_values", &PoolParams::padding_values) .field("stride_width", &PoolParams::stride_width) .field("stride_height", &PoolParams::stride_height) .field("filter_width", &PoolParams::filter_width) .field("filter_height", &PoolParams::filter_height) // float activation params. .field("float_activation_min", &PoolParams::float_activation_min) .field("float_activation_max", &PoolParams::float_activation_max) // uint8, etc, activation params. .field("quantized_activation_min", &PoolParams::quantized_activation_min) .field("quantized_activation_max", &PoolParams::quantized_activation_max) ; value_object<ResizeBilinearParams>("ResizeBilinearParams") .field("align_corners", &ResizeBilinearParams::align_corners) ; value_object<ConcatenationParams>("ConcatenationParams") .field("axis", &ConcatenationParams::axis) .field("inputs_count", &ConcatenationParams::inputs_count) .field("output_scale", &ConcatenationParams::output_scale) .field("output_zeropoint", &ConcatenationParams::output_zeropoint) ; value_object<FullyConnectedParams>("FullyConnectedParams") // float activation params. .field("float_activation_min", &FullyConnectedParams::float_activation_min) .field("float_activation_max", &FullyConnectedParams::float_activation_max) // uint8 inference params. .field("input_offset", &FullyConnectedParams::input_offset) .field("weights_offset", &FullyConnectedParams::weights_offset) .field("output_offset", &FullyConnectedParams::output_offset) .field("output_multiplier", &FullyConnectedParams::output_multiplier) .field("output_shift", &FullyConnectedParams::output_shift) // uint8, etc, activation params. .field("quantized_activation_min", &FullyConnectedParams::quantized_activation_min) .field("quantized_activation_max", &FullyConnectedParams::quantized_activation_max) ; value_object<ArithmeticParams>("ArithmeticParams") // float activation params. .field("float_activation_min", &ArithmeticParams::float_activation_min) .field("float_activation_max", &ArithmeticParams::float_activation_max) // uint8 inference params. .field("input1_offset", &ArithmeticParams::input1_offset) .field("input2_offset", &ArithmeticParams::input2_offset) .field("output_offset", &ArithmeticParams::output_offset) .field("output_multiplier", &ArithmeticParams::output_multiplier) .field("output_shift", &ArithmeticParams::output_shift) // Add / Sub, not Mul, uint8 inference params. .field("left_shift", &ArithmeticParams::left_shift) .field("input1_multiplier", &ArithmeticParams::input1_multiplier) .field("input1_shift", &ArithmeticParams::input1_shift) .field("input2_multiplier", &ArithmeticParams::input2_multiplier) .field("input2_shift", &ArithmeticParams::input2_shift) // uint8, etc, activation params. .field("quantized_activation_min", &ArithmeticParams::quantized_activation_min) .field("quantized_activation_max", &ArithmeticParams::quantized_activation_max) ; value_object<TransposeParams>("TransposeParams") .field("perm", &TransposeParams::perm) .field("perm_count", &TransposeParams::perm_count) ; value_object<LogisticParams>("LogisticParams") // uint8 inference params. .field("input_zero_point", &LogisticParams::input_zero_point) .field("input_range_radius", &LogisticParams::input_range_radius) .field("input_multiplier", &LogisticParams::input_multiplier) .field("input_left_shift", &LogisticParams::input_left_shift) ; value_object<PreluParams>("PreluParams") .field("input_offset", &PreluParams::input_offset) .field("alpha_offset", &PreluParams::alpha_offset) .field("output_offset", &PreluParams::output_offset) .field("output_multiplier", &PreluParams::output_multiplier) .field("output_shift", &PreluParams::output_shift) ; value_array<std::array<int32_t, 4>>("array_int32_4") .element(emscripten::index<0>()) .element(emscripten::index<1>()) .element(emscripten::index<2>()) .element(emscripten::index<3>()) ; register_vector<RuntimeShape*>("VectorShape"); register_vector<intptr_t>("VectorPtr"); // help functions function("set_gemm_context_threads_num", &binding_utils::set_gemm_context_threads_num); function("set_cpu_context_threads_num", &binding_utils::set_cpu_context_threads_num); // Operations. function("addFloat32", &binding_utils::addFloat32Wrapper, allow_raw_pointers()); function("addUint8", &binding_utils::addUint8Wrapper, allow_raw_pointers()); function("broadCastAddFloat32", &binding_utils::broadCastAddFloat32Wrapper, allow_raw_pointers()); function("mulFloat32", &binding_utils::mulFloat32Wrapper, allow_raw_pointers()); function("broadCastMulFloat32", &binding_utils::broadCastMulFloat32Wrapper, allow_raw_pointers()); function("floorFloat32", &binding_utils::floorFloat32Wrapper, allow_raw_pointers()); function("depthwiseConvFloat32", &binding_utils::depthwiseConvFloat32Wrapper, allow_raw_pointers()); function("depthwiseConvUint8", &binding_utils::depthwiseConvUint8Wrapper, allow_raw_pointers()); function("depthwiseConvInt8", &binding_utils::depthwiseConvInt8Wrapper, allow_raw_pointers()); function("depthwiseConvUint8PerChannel", &binding_utils::depthwiseConvUint8PerChannelWrapper, allow_raw_pointers()); function("depthwiseConvInt8PerChannel", &binding_utils::depthwiseConvInt8PerChannelWrapper, allow_raw_pointers()); function("convFloat32", &binding_utils::convFloat32Wrapper, allow_raw_pointers()); function("convUint8", &binding_utils::convUint8Wrapper, allow_raw_pointers()); function("convUint8PerChannel", &binding_utils::convUint8PerChannelWrapper, allow_raw_pointers()); function("convInt8", &binding_utils::convInt8Wrapper, allow_raw_pointers()); function("convInt8PerChannel", &binding_utils::convInt8PerChannelWrapper, allow_raw_pointers()); function("averagePoolFloat32", &binding_utils::averagePoolFloat32Wrapper, allow_raw_pointers()); function("averagePoolUint8", &binding_utils::averagePoolUint8Wrapper, allow_raw_pointers()); function("averagePoolInt8", &binding_utils::averagePoolInt8Wrapper, allow_raw_pointers()); function("softmaxFloat32", &binding_utils::softmaxFloat32Wrapper, allow_raw_pointers()); function("softmaxUint8", &binding_utils::softmaxUint8Wrapper, allow_raw_pointers()); function("reshapeFloat32", &binding_utils::reshapeFloat32Wrapper, allow_raw_pointers()); function("reshapeUint8", &binding_utils::reshapeUint8Wrapper, allow_raw_pointers()); function("maxPoolFloat32", &binding_utils::maxPoolFloat32Wrapper, allow_raw_pointers()); function("maxPoolUint8", &binding_utils::maxPoolUint8Wrapper, allow_raw_pointers()); function("concatenationFloat32", &binding_utils::concatenationFloat32Wrapper, allow_raw_pointers()); function("concatenationUint8", &binding_utils::concatenationUint8Wrapper, allow_raw_pointers()); function("fullyConnectedFloat32", &binding_utils::fullyConnectedFloat32Wrapper, allow_raw_pointers()); function("fullyConnectedUint8", &binding_utils::fullyConnectedUint8Wrapper, allow_raw_pointers()); function("resizeBilinearFloat32", &binding_utils::resizeBilinearFloat32Wrapper, allow_raw_pointers()); function("tanhFloat32", &binding_utils::tanhFloat32Wrapper, allow_raw_pointers()); function("maximumFloat32", &binding_utils::maximumFloat32Wrapper, allow_raw_pointers()); function("batchToSpaceNDFloat32", &binding_utils::batchToSpaceNDFloat32Wrapper, allow_raw_pointers()); function("transposeFloat32", &binding_utils::transposeFloat32Wrapper, allow_raw_pointers()); function("argMaxFloat32", &binding_utils::argMaxFloat32Wrapper, allow_raw_pointers()); function("logisticFloat32", &binding_utils::logisticFloat32Wrapper, allow_raw_pointers()); function("logisticUint8", &binding_utils::logisticUint8Wrapper, allow_raw_pointers()); function("preluFloat32", &binding_utils::preluFloat32Wrapper, allow_raw_pointers()); function("preluUint8", &binding_utils::preluUint8Wrapper, allow_raw_pointers()); // TODO: operation wrappers /* function("l2PoolFloat32", &binding_utils::l2PoolFloat32Wrapper, allow_raw_pointers()); function("maxPoolQuant8", &binding_utils::maxPoolQuant8Wrapper, allow_raw_pointers()); function("reluFloat32", &binding_utils::reluFloat32Wrapper, allow_raw_pointers()); function("relu1Float32", &binding_utils::relu1Float32Wrapper, allow_raw_pointers()); function("relu6Float32", &binding_utils::relu6Float32Wrapper, allow_raw_pointers()); function("reluQuant8", &binding_utils::reluQuant8Wrapper, allow_raw_pointers()); function("relu1Quant8", &binding_utils::relu1Quant8Wrapper, allow_raw_pointers()); function("relu6Quant8", &binding_utils::relu6Quant8Wrapper, allow_raw_pointers()); function("fullyConnectedQuant8", &binding_utils::fullyConnectedQuant8Wrapper, allow_raw_pointers()); function("concatenationQuant8", &binding_utils::concatenationQuant8Wrapper, allow_raw_pointers()); function("l2normFloat32", &binding_utils::l2normFloat32Wrapper, allow_raw_pointers()); function("l2normQuant8", &binding_utils::l2normQuant8Wrapper, allow_raw_pointers()); function("localResponseNormFloat32", &binding_utils::localResponseNormFloat32Wrapper, allow_raw_pointers()); function("depthToSpaceGeneric", &binding_utils::depthToSpaceGenericWrapper, allow_raw_pointers()); function("spaceToDepthGeneric", &binding_utils::spaceToDepthGenericWrapper, allow_raw_pointers()); */ }
54.329225
118
0.578713
[ "vector", "model" ]
44f252a99f912587018a83c400f915da72efb130
6,281
cpp
C++
Ethereal/Private/Characters/Enemy/Standard/UndeadWarrior.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
216
2016-08-28T18:22:06.000Z
2022-03-22T09:08:15.000Z
Ethereal/Private/Characters/Enemy/Standard/UndeadWarrior.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
1
2017-08-10T06:14:32.000Z
2017-08-12T00:16:27.000Z
Ethereal/Private/Characters/Enemy/Standard/UndeadWarrior.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
49
2016-08-28T18:22:31.000Z
2022-02-23T16:22:37.000Z
// © 2014 - 2017 Soverance Studios // http://www.soverance.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Ethereal.h" #include "Widgets/Tutorial.h" #include "UndeadWarrior.h" #define LOCTEXT_NAMESPACE "EtherealText" // Sets default values AUndeadWarrior::AUndeadWarrior(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { static ConstructorHelpers::FObjectFinder<USkeletalMesh> EnemyMesh(TEXT("SkeletalMesh'/Game/EtherealParty/Skeleton/mSkeleton.mSkeleton'")); static ConstructorHelpers::FObjectFinder<UClass> AnimBP(TEXT("AnimBlueprint'/Game/EtherealParty/Skeleton/Skeleton_AnimBP.Skeleton_AnimBP_C'")); static ConstructorHelpers::FObjectFinder<USoundCue> DeathAudioObject(TEXT("SoundCue'/Game/Audio/Party/SoulEater_Death_Cue.SoulEater_Death_Cue'")); S_DeathAudio = DeathAudioObject.Object; // Default Config Name = EEnemyNames::EN_UndeadWarrior; NameText = LOCTEXT("UndeadWarriorText", "Undead Warrior"); Realm = ERealms::R_Arcadia; BattleType = EBattleTypes::BT_Standard; CommonDrop = EMasterGearList::GL_None; UncommonDrop = EMasterGearList::GL_Potion; RareDrop = EMasterGearList::GL_Ether; AttackDelay = 3.0f; BaseEyeHeight = 16; GetCapsuleComponent()->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f)); GetCharacterMovement()->MaxAcceleration = 30; GetCharacterMovement()->RotationRate = FRotator(0, 5, 0); // seems to do nothing? // Pawn A.I. config PawnSensing->HearingThreshold = 400; PawnSensing->LOSHearingThreshold = 500; PawnSensing->SightRadius = 500; PawnSensing->SetPeripheralVisionAngle(40.0f); AcceptanceRadius = 50.0f; RunAI = false; // Mesh Config GetMesh()->SkeletalMesh = EnemyMesh.Object; GetMesh()->SetAnimInstanceClass(AnimBP.Object); GetMesh()->SetRelativeScale3D(FVector(1, 1, 1)); GetMesh()->SetRelativeLocation(FVector(0, 0, -90)); GetMesh()->SetRelativeRotation(FRotator(0, -90, 0)); // Melee Radius Config MeleeRadius->SetSphereRadius(100); MeleeRadius->SetRelativeLocation(FVector(50, 0, 0)); // Targeting Reticle config TargetingReticle->SetRelativeLocation(FVector(0, 0, 215)); TargetingReticle->SetRelativeRotation(FRotator(0, 0, 180)); TargetingReticle->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f)); // Death FX Config DeathFX->SetRelativeLocation(FVector(0, 0, -90)); DeathFX->SetRelativeScale3D(FVector(0.8f, 0.8f, 0.8f)); HitFX->SetRelativeLocation(FVector(0, 0, 40)); DisappearFX->SetRelativeLocation(FVector(0, 0, -20)); // Enemy-Specific Object Config DeathAudio = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("DeathAudio")); DeathAudio->Sound = S_DeathAudio; DeathAudio->bAutoActivate = false; DeathAudio->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void AUndeadWarrior::BeginPlay() { Super::BeginPlay(); PawnSensing->OnHearNoise.AddDynamic(this, &AUndeadWarrior::OnHearNoise); // bind the OnHearNoise event PawnSensing->OnSeePawn.AddDynamic(this, &AUndeadWarrior::OnSeePawn); // bind the OnSeePawn event OnDeath.AddDynamic(this, &AUndeadWarrior::CustomDeath); // bind the death fuction to the OnDeath event OnReachedTarget.AddDynamic(this, &AUndeadWarrior::MeleeAttack); // bind the attack function to the OnReachedTarget event // Get the Gatekeeper actor, so this enemy has a reference to it for tutorial progression for (TActorIterator<AGatekeeper> ActorItr(GetWorld()); ActorItr; ++ActorItr) { Gatekeeper = *ActorItr; // get the instance of the Gatekeeper actor } } // Called every frame void AUndeadWarrior::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AUndeadWarrior::MeleeAttack() { EnemyDealDamage(10); Attack = true; } void AUndeadWarrior::CustomDeath() { DeathAudio->Play(); // Play death audio //Target->EtherealPlayerState->EnemyKillReward(Level, CommonDrop, UncommonDrop, RareDrop); // reward the player for killing this enemy if (!Target->EtherealPlayerState->HasCompletedTutorial) // don't bother running this code if the player has completed the tutorial { if (Gatekeeper) // be sure Gatekeeper reference isn't NULL { if (Gatekeeper->Tutorial) // be sure the Tutorial widget isn't NULL { if (Target->AggroList.Num() == 0) // only progress with this function if the aggro list is empty { if (Gatekeeper->Tutorial->TutorialIndex == 2) // you killed this enemy while on the proper TutorialIndex, so we progress the Tutorial { FTimerHandle ConvoTimer; GetWorldTimerManager().SetTimer(ConvoTimer, this, &AUndeadWarrior::ShowTutorialConvo, 2.5f, false); } } } } } } void AUndeadWarrior::ShowTutorialConvo() { Gatekeeper->Tutorial->ShowConversation_05(); // show the Consumable Item tutorial panel } void AUndeadWarrior::OnHearNoise(APawn* PawnInstigator, const FVector& Location, float Volume) { if (!IsDead) { if (!IsAggroed) { //Aggro(PawnInstigator); IsAggroed = true; // Delay Aggro so the skeleton can get up from the ground FTimerDelegate DelegateAggro; DelegateAggro.BindUFunction(this, FName("Aggro"), PawnInstigator); FTimerHandle AggroTimer; GetWorldTimerManager().SetTimer(AggroTimer, DelegateAggro, 2.5f, false); } } } void AUndeadWarrior::OnSeePawn(APawn* Pawn) { if (!IsDead) { if (!IsAggroed) { //Aggro(Pawn); IsAggroed = true; // Delay Aggro so the skeleton can get up from the ground FTimerDelegate DelegateAggro; DelegateAggro.BindUFunction(this, FName("Aggro"), Pawn); FTimerHandle AggroTimer; GetWorldTimerManager().SetTimer(AggroTimer, DelegateAggro, 2.5f, false); } } } #undef LOCTEXT_NAMESPACE
34.894444
148
0.728706
[ "mesh", "object" ]
44f2fc51bf13d68e3a9bb3b1f9d6fe3c04307561
23,327
cpp
C++
af/src/v20200226/model/FinanceAntiFraudFilter.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
af/src/v20200226/model/FinanceAntiFraudFilter.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
af/src/v20200226/model/FinanceAntiFraudFilter.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/af/v20200226/model/FinanceAntiFraudFilter.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Af::V20200226::Model; using namespace std; FinanceAntiFraudFilter::FinanceAntiFraudFilter() : m_phoneNumberHasBeenSet(false), m_idNumberHasBeenSet(false), m_bankCardNumberHasBeenSet(false), m_userIpHasBeenSet(false), m_imeiHasBeenSet(false), m_idfaHasBeenSet(false), m_sceneHasBeenSet(false), m_nameHasBeenSet(false), m_emailAddressHasBeenSet(false), m_addressHasBeenSet(false), m_macHasBeenSet(false), m_imsiHasBeenSet(false), m_accountTypeHasBeenSet(false), m_uidHasBeenSet(false), m_appIdUHasBeenSet(false), m_wifiMacHasBeenSet(false), m_wifiSSIDHasBeenSet(false), m_wifiBSSIDHasBeenSet(false), m_businessIdHasBeenSet(false), m_phoneCryptoTypeHasBeenSet(false), m_idCryptoTypeHasBeenSet(false), m_nameCryptoTypeHasBeenSet(false) { } CoreInternalOutcome FinanceAntiFraudFilter::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("PhoneNumber") && !value["PhoneNumber"].IsNull()) { if (!value["PhoneNumber"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.PhoneNumber` IsString=false incorrectly").SetRequestId(requestId)); } m_phoneNumber = string(value["PhoneNumber"].GetString()); m_phoneNumberHasBeenSet = true; } if (value.HasMember("IdNumber") && !value["IdNumber"].IsNull()) { if (!value["IdNumber"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.IdNumber` IsString=false incorrectly").SetRequestId(requestId)); } m_idNumber = string(value["IdNumber"].GetString()); m_idNumberHasBeenSet = true; } if (value.HasMember("BankCardNumber") && !value["BankCardNumber"].IsNull()) { if (!value["BankCardNumber"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.BankCardNumber` IsString=false incorrectly").SetRequestId(requestId)); } m_bankCardNumber = string(value["BankCardNumber"].GetString()); m_bankCardNumberHasBeenSet = true; } if (value.HasMember("UserIp") && !value["UserIp"].IsNull()) { if (!value["UserIp"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.UserIp` IsString=false incorrectly").SetRequestId(requestId)); } m_userIp = string(value["UserIp"].GetString()); m_userIpHasBeenSet = true; } if (value.HasMember("Imei") && !value["Imei"].IsNull()) { if (!value["Imei"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Imei` IsString=false incorrectly").SetRequestId(requestId)); } m_imei = string(value["Imei"].GetString()); m_imeiHasBeenSet = true; } if (value.HasMember("Idfa") && !value["Idfa"].IsNull()) { if (!value["Idfa"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Idfa` IsString=false incorrectly").SetRequestId(requestId)); } m_idfa = string(value["Idfa"].GetString()); m_idfaHasBeenSet = true; } if (value.HasMember("Scene") && !value["Scene"].IsNull()) { if (!value["Scene"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Scene` IsString=false incorrectly").SetRequestId(requestId)); } m_scene = string(value["Scene"].GetString()); m_sceneHasBeenSet = true; } if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("EmailAddress") && !value["EmailAddress"].IsNull()) { if (!value["EmailAddress"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.EmailAddress` IsString=false incorrectly").SetRequestId(requestId)); } m_emailAddress = string(value["EmailAddress"].GetString()); m_emailAddressHasBeenSet = true; } if (value.HasMember("Address") && !value["Address"].IsNull()) { if (!value["Address"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Address` IsString=false incorrectly").SetRequestId(requestId)); } m_address = string(value["Address"].GetString()); m_addressHasBeenSet = true; } if (value.HasMember("Mac") && !value["Mac"].IsNull()) { if (!value["Mac"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Mac` IsString=false incorrectly").SetRequestId(requestId)); } m_mac = string(value["Mac"].GetString()); m_macHasBeenSet = true; } if (value.HasMember("Imsi") && !value["Imsi"].IsNull()) { if (!value["Imsi"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Imsi` IsString=false incorrectly").SetRequestId(requestId)); } m_imsi = string(value["Imsi"].GetString()); m_imsiHasBeenSet = true; } if (value.HasMember("AccountType") && !value["AccountType"].IsNull()) { if (!value["AccountType"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.AccountType` IsString=false incorrectly").SetRequestId(requestId)); } m_accountType = string(value["AccountType"].GetString()); m_accountTypeHasBeenSet = true; } if (value.HasMember("Uid") && !value["Uid"].IsNull()) { if (!value["Uid"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.Uid` IsString=false incorrectly").SetRequestId(requestId)); } m_uid = string(value["Uid"].GetString()); m_uidHasBeenSet = true; } if (value.HasMember("AppIdU") && !value["AppIdU"].IsNull()) { if (!value["AppIdU"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.AppIdU` IsString=false incorrectly").SetRequestId(requestId)); } m_appIdU = string(value["AppIdU"].GetString()); m_appIdUHasBeenSet = true; } if (value.HasMember("WifiMac") && !value["WifiMac"].IsNull()) { if (!value["WifiMac"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.WifiMac` IsString=false incorrectly").SetRequestId(requestId)); } m_wifiMac = string(value["WifiMac"].GetString()); m_wifiMacHasBeenSet = true; } if (value.HasMember("WifiSSID") && !value["WifiSSID"].IsNull()) { if (!value["WifiSSID"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.WifiSSID` IsString=false incorrectly").SetRequestId(requestId)); } m_wifiSSID = string(value["WifiSSID"].GetString()); m_wifiSSIDHasBeenSet = true; } if (value.HasMember("WifiBSSID") && !value["WifiBSSID"].IsNull()) { if (!value["WifiBSSID"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.WifiBSSID` IsString=false incorrectly").SetRequestId(requestId)); } m_wifiBSSID = string(value["WifiBSSID"].GetString()); m_wifiBSSIDHasBeenSet = true; } if (value.HasMember("BusinessId") && !value["BusinessId"].IsNull()) { if (!value["BusinessId"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.BusinessId` IsString=false incorrectly").SetRequestId(requestId)); } m_businessId = string(value["BusinessId"].GetString()); m_businessIdHasBeenSet = true; } if (value.HasMember("PhoneCryptoType") && !value["PhoneCryptoType"].IsNull()) { if (!value["PhoneCryptoType"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.PhoneCryptoType` IsString=false incorrectly").SetRequestId(requestId)); } m_phoneCryptoType = string(value["PhoneCryptoType"].GetString()); m_phoneCryptoTypeHasBeenSet = true; } if (value.HasMember("IdCryptoType") && !value["IdCryptoType"].IsNull()) { if (!value["IdCryptoType"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.IdCryptoType` IsString=false incorrectly").SetRequestId(requestId)); } m_idCryptoType = string(value["IdCryptoType"].GetString()); m_idCryptoTypeHasBeenSet = true; } if (value.HasMember("NameCryptoType") && !value["NameCryptoType"].IsNull()) { if (!value["NameCryptoType"].IsString()) { return CoreInternalOutcome(Core::Error("response `FinanceAntiFraudFilter.NameCryptoType` IsString=false incorrectly").SetRequestId(requestId)); } m_nameCryptoType = string(value["NameCryptoType"].GetString()); m_nameCryptoTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void FinanceAntiFraudFilter::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_phoneNumberHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PhoneNumber"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_phoneNumber.c_str(), allocator).Move(), allocator); } if (m_idNumberHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "IdNumber"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_idNumber.c_str(), allocator).Move(), allocator); } if (m_bankCardNumberHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BankCardNumber"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_bankCardNumber.c_str(), allocator).Move(), allocator); } if (m_userIpHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UserIp"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_userIp.c_str(), allocator).Move(), allocator); } if (m_imeiHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Imei"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_imei.c_str(), allocator).Move(), allocator); } if (m_idfaHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Idfa"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_idfa.c_str(), allocator).Move(), allocator); } if (m_sceneHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Scene"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_scene.c_str(), allocator).Move(), allocator); } if (m_nameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator); } if (m_emailAddressHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EmailAddress"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_emailAddress.c_str(), allocator).Move(), allocator); } if (m_addressHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Address"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_address.c_str(), allocator).Move(), allocator); } if (m_macHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Mac"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_mac.c_str(), allocator).Move(), allocator); } if (m_imsiHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Imsi"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_imsi.c_str(), allocator).Move(), allocator); } if (m_accountTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AccountType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_accountType.c_str(), allocator).Move(), allocator); } if (m_uidHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Uid"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_uid.c_str(), allocator).Move(), allocator); } if (m_appIdUHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AppIdU"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_appIdU.c_str(), allocator).Move(), allocator); } if (m_wifiMacHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WifiMac"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_wifiMac.c_str(), allocator).Move(), allocator); } if (m_wifiSSIDHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WifiSSID"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_wifiSSID.c_str(), allocator).Move(), allocator); } if (m_wifiBSSIDHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WifiBSSID"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_wifiBSSID.c_str(), allocator).Move(), allocator); } if (m_businessIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BusinessId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_businessId.c_str(), allocator).Move(), allocator); } if (m_phoneCryptoTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PhoneCryptoType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_phoneCryptoType.c_str(), allocator).Move(), allocator); } if (m_idCryptoTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "IdCryptoType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_idCryptoType.c_str(), allocator).Move(), allocator); } if (m_nameCryptoTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NameCryptoType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_nameCryptoType.c_str(), allocator).Move(), allocator); } } string FinanceAntiFraudFilter::GetPhoneNumber() const { return m_phoneNumber; } void FinanceAntiFraudFilter::SetPhoneNumber(const string& _phoneNumber) { m_phoneNumber = _phoneNumber; m_phoneNumberHasBeenSet = true; } bool FinanceAntiFraudFilter::PhoneNumberHasBeenSet() const { return m_phoneNumberHasBeenSet; } string FinanceAntiFraudFilter::GetIdNumber() const { return m_idNumber; } void FinanceAntiFraudFilter::SetIdNumber(const string& _idNumber) { m_idNumber = _idNumber; m_idNumberHasBeenSet = true; } bool FinanceAntiFraudFilter::IdNumberHasBeenSet() const { return m_idNumberHasBeenSet; } string FinanceAntiFraudFilter::GetBankCardNumber() const { return m_bankCardNumber; } void FinanceAntiFraudFilter::SetBankCardNumber(const string& _bankCardNumber) { m_bankCardNumber = _bankCardNumber; m_bankCardNumberHasBeenSet = true; } bool FinanceAntiFraudFilter::BankCardNumberHasBeenSet() const { return m_bankCardNumberHasBeenSet; } string FinanceAntiFraudFilter::GetUserIp() const { return m_userIp; } void FinanceAntiFraudFilter::SetUserIp(const string& _userIp) { m_userIp = _userIp; m_userIpHasBeenSet = true; } bool FinanceAntiFraudFilter::UserIpHasBeenSet() const { return m_userIpHasBeenSet; } string FinanceAntiFraudFilter::GetImei() const { return m_imei; } void FinanceAntiFraudFilter::SetImei(const string& _imei) { m_imei = _imei; m_imeiHasBeenSet = true; } bool FinanceAntiFraudFilter::ImeiHasBeenSet() const { return m_imeiHasBeenSet; } string FinanceAntiFraudFilter::GetIdfa() const { return m_idfa; } void FinanceAntiFraudFilter::SetIdfa(const string& _idfa) { m_idfa = _idfa; m_idfaHasBeenSet = true; } bool FinanceAntiFraudFilter::IdfaHasBeenSet() const { return m_idfaHasBeenSet; } string FinanceAntiFraudFilter::GetScene() const { return m_scene; } void FinanceAntiFraudFilter::SetScene(const string& _scene) { m_scene = _scene; m_sceneHasBeenSet = true; } bool FinanceAntiFraudFilter::SceneHasBeenSet() const { return m_sceneHasBeenSet; } string FinanceAntiFraudFilter::GetName() const { return m_name; } void FinanceAntiFraudFilter::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool FinanceAntiFraudFilter::NameHasBeenSet() const { return m_nameHasBeenSet; } string FinanceAntiFraudFilter::GetEmailAddress() const { return m_emailAddress; } void FinanceAntiFraudFilter::SetEmailAddress(const string& _emailAddress) { m_emailAddress = _emailAddress; m_emailAddressHasBeenSet = true; } bool FinanceAntiFraudFilter::EmailAddressHasBeenSet() const { return m_emailAddressHasBeenSet; } string FinanceAntiFraudFilter::GetAddress() const { return m_address; } void FinanceAntiFraudFilter::SetAddress(const string& _address) { m_address = _address; m_addressHasBeenSet = true; } bool FinanceAntiFraudFilter::AddressHasBeenSet() const { return m_addressHasBeenSet; } string FinanceAntiFraudFilter::GetMac() const { return m_mac; } void FinanceAntiFraudFilter::SetMac(const string& _mac) { m_mac = _mac; m_macHasBeenSet = true; } bool FinanceAntiFraudFilter::MacHasBeenSet() const { return m_macHasBeenSet; } string FinanceAntiFraudFilter::GetImsi() const { return m_imsi; } void FinanceAntiFraudFilter::SetImsi(const string& _imsi) { m_imsi = _imsi; m_imsiHasBeenSet = true; } bool FinanceAntiFraudFilter::ImsiHasBeenSet() const { return m_imsiHasBeenSet; } string FinanceAntiFraudFilter::GetAccountType() const { return m_accountType; } void FinanceAntiFraudFilter::SetAccountType(const string& _accountType) { m_accountType = _accountType; m_accountTypeHasBeenSet = true; } bool FinanceAntiFraudFilter::AccountTypeHasBeenSet() const { return m_accountTypeHasBeenSet; } string FinanceAntiFraudFilter::GetUid() const { return m_uid; } void FinanceAntiFraudFilter::SetUid(const string& _uid) { m_uid = _uid; m_uidHasBeenSet = true; } bool FinanceAntiFraudFilter::UidHasBeenSet() const { return m_uidHasBeenSet; } string FinanceAntiFraudFilter::GetAppIdU() const { return m_appIdU; } void FinanceAntiFraudFilter::SetAppIdU(const string& _appIdU) { m_appIdU = _appIdU; m_appIdUHasBeenSet = true; } bool FinanceAntiFraudFilter::AppIdUHasBeenSet() const { return m_appIdUHasBeenSet; } string FinanceAntiFraudFilter::GetWifiMac() const { return m_wifiMac; } void FinanceAntiFraudFilter::SetWifiMac(const string& _wifiMac) { m_wifiMac = _wifiMac; m_wifiMacHasBeenSet = true; } bool FinanceAntiFraudFilter::WifiMacHasBeenSet() const { return m_wifiMacHasBeenSet; } string FinanceAntiFraudFilter::GetWifiSSID() const { return m_wifiSSID; } void FinanceAntiFraudFilter::SetWifiSSID(const string& _wifiSSID) { m_wifiSSID = _wifiSSID; m_wifiSSIDHasBeenSet = true; } bool FinanceAntiFraudFilter::WifiSSIDHasBeenSet() const { return m_wifiSSIDHasBeenSet; } string FinanceAntiFraudFilter::GetWifiBSSID() const { return m_wifiBSSID; } void FinanceAntiFraudFilter::SetWifiBSSID(const string& _wifiBSSID) { m_wifiBSSID = _wifiBSSID; m_wifiBSSIDHasBeenSet = true; } bool FinanceAntiFraudFilter::WifiBSSIDHasBeenSet() const { return m_wifiBSSIDHasBeenSet; } string FinanceAntiFraudFilter::GetBusinessId() const { return m_businessId; } void FinanceAntiFraudFilter::SetBusinessId(const string& _businessId) { m_businessId = _businessId; m_businessIdHasBeenSet = true; } bool FinanceAntiFraudFilter::BusinessIdHasBeenSet() const { return m_businessIdHasBeenSet; } string FinanceAntiFraudFilter::GetPhoneCryptoType() const { return m_phoneCryptoType; } void FinanceAntiFraudFilter::SetPhoneCryptoType(const string& _phoneCryptoType) { m_phoneCryptoType = _phoneCryptoType; m_phoneCryptoTypeHasBeenSet = true; } bool FinanceAntiFraudFilter::PhoneCryptoTypeHasBeenSet() const { return m_phoneCryptoTypeHasBeenSet; } string FinanceAntiFraudFilter::GetIdCryptoType() const { return m_idCryptoType; } void FinanceAntiFraudFilter::SetIdCryptoType(const string& _idCryptoType) { m_idCryptoType = _idCryptoType; m_idCryptoTypeHasBeenSet = true; } bool FinanceAntiFraudFilter::IdCryptoTypeHasBeenSet() const { return m_idCryptoTypeHasBeenSet; } string FinanceAntiFraudFilter::GetNameCryptoType() const { return m_nameCryptoType; } void FinanceAntiFraudFilter::SetNameCryptoType(const string& _nameCryptoType) { m_nameCryptoType = _nameCryptoType; m_nameCryptoTypeHasBeenSet = true; } bool FinanceAntiFraudFilter::NameCryptoTypeHasBeenSet() const { return m_nameCryptoTypeHasBeenSet; }
28.727833
156
0.681571
[ "model" ]
44f9ebced0f52a40e3e3f7f5b5f71d29af55d303
4,389
cpp
C++
libs/full/checkpoint/tests/unit/checkpoint_component.cpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
1
2021-02-03T09:17:55.000Z
2021-02-03T09:17:55.000Z
libs/full/checkpoint/tests/unit/checkpoint_component.cpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
null
null
null
libs/full/checkpoint/tests/unit/checkpoint_component.cpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2018 Adrian Serio // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This example tests the interoperability of save_checkpoint and // restore_checkpoint with components. #include <hpx/config.hpp> #if !defined(HPX_COMPUTE_DEVICE_CODE) #include <hpx/hpx_main.hpp> #include <hpx/include/components.hpp> #include <hpx/modules/checkpoint.hpp> #include <hpx/modules/testing.hpp> #include <hpx/serialization/shared_ptr.hpp> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> using hpx::util::checkpoint; using hpx::util::prepare_checkpoint; using hpx::util::restore_checkpoint; using hpx::util::save_checkpoint; struct data_server : hpx::components::component_base<data_server> { data_server() = default; ~data_server() = default; data_server(std::vector<int>&& data) : data_(std::move(data)) { } std::vector<int> get_data() { return data_; } HPX_DEFINE_COMPONENT_ACTION(data_server, get_data, get_data_action); void print() { for (size_t i = 0; i < data_.size(); i++) { std::cout << data_[i]; if (data_.size() - 1 != i) { std::cout << ","; } } std::cout << std::endl; } HPX_DEFINE_COMPONENT_ACTION(data_server, print, print_action); std::vector<int> data_; // Serialization Definition friend class hpx::serialization::access; template <typename Archive> void serialize(Archive& arch, const unsigned int /* version */) { // clang-format off arch & data_; // clang-format on } }; using data_server_type = hpx::components::component<data_server>; HPX_REGISTER_COMPONENT(data_server_type, data_server); HPX_REGISTER_ACTION(data_server::get_data_action); HPX_REGISTER_ACTION(data_server::print_action); struct data_client : hpx::components::client_base<data_client, data_server> { using base_type = hpx::components::client_base<data_client, data_server>; data_client() = default; ~data_client() = default; data_client(hpx::id_type where, std::vector<int>&& data) : base_type(hpx::new_<data_server>(hpx::colocated(where), data)) { } data_client(hpx::id_type&& id) : base_type(std::move(id)) { } data_client(hpx::shared_future<hpx::id_type> const& id) : base_type(id) { } hpx::future<std::vector<int>> get_data() { data_server::get_data_action get_act; return hpx::async(get_act, get_id()); } hpx::future<void> print() { data_server::print_action print_act; return hpx::async(print_act, get_id()); } }; int main() { // Test 1 //[shared_ptr_example // test checkpoint a component using a shared_ptr std::vector<int> vec{1, 2, 3, 4, 5}; data_client A(hpx::find_here(), std::move(vec)); // Checkpoint Server hpx::id_type old_id = A.get_id(); hpx::future<std::shared_ptr<data_server>> f_a_ptr = hpx::get_ptr<data_server>(A.get_id()); std::shared_ptr<data_server> a_ptr = f_a_ptr.get(); hpx::future<checkpoint> f = save_checkpoint(a_ptr); auto&& data = f.get(); // test prepare_checkpoint API checkpoint c = prepare_checkpoint(hpx::launch::sync, a_ptr); HPX_TEST(c.size() == data.size()); // Restore Server // Create a new server instance std::shared_ptr<data_server> b_server; restore_checkpoint(data, b_server); //] HPX_TEST(A.get_data().get() == b_server->get_data()); // Re-create Client data_client B(std::move(old_id)); HPX_TEST(A.get_data().get() == B.get_data().get()); // Test 2 //[client_example // Try to checkpoint and restore a component with a client std::vector<int> vec3{10, 10, 10, 10, 10}; // Create a component instance through client constructor data_client D(hpx::find_here(), std::move(vec3)); hpx::future<checkpoint> f3 = save_checkpoint(D); // Create a new client data_client E; // Restore server inside client instance restore_checkpoint(f3.get(), E); //] HPX_TEST(D.get_data().get() == E.get_data().get()); return hpx::util::report_errors(); } #endif
26.125
79
0.649123
[ "vector" ]
44fbd3d8ba3ca91fc13e542fa4ceb0c006e9bab1
4,364
cpp
C++
iOS/G3MApp/G3MApp/G3M3DSymbologyDemoScene.cpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
1
2016-08-23T10:29:44.000Z
2016-08-23T10:29:44.000Z
iOS/G3MApp/G3MApp/G3M3DSymbologyDemoScene.cpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MApp/G3MApp/G3M3DSymbologyDemoScene.cpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
null
null
null
// // G3M3DSymbologyDemoScene.cpp // G3MApp // // Created by Diego Gomez Deck on 11/18/13. // Copyright (c) 2013 Igo Software SL. All rights reserved. // #include "G3M3DSymbologyDemoScene.hpp" #include <G3MiOSSDK/Sector.hpp> #include <G3MiOSSDK/MapBoxLayer.hpp> #include <G3MiOSSDK/LayerSet.hpp> #include <G3MiOSSDK/G3MWidget.hpp> #include <G3MiOSSDK/GEORenderer.hpp> #include <G3MiOSSDK/GEOSymbolizer.hpp> #include <G3MiOSSDK/JSONObject.hpp> #include <G3MiOSSDK/GEO2DPointGeometry.hpp> #include <G3MiOSSDK/GEOFeature.hpp> #include <G3MiOSSDK/BoxShape.hpp> #include <G3MiOSSDK/Mark.hpp> #include <G3MiOSSDK/GEOShapeSymbol.hpp> #include <G3MiOSSDK/GEOMarkSymbol.hpp> #include <G3MiOSSDK/PlanetRenderer.hpp> #include <G3MiOSSDK/SingleBilElevationDataProvider.hpp> #include "G3MDemoModel.hpp" class USCitiesSymbolizer : public GEOSymbolizer { public: std::vector<GEOSymbol*>* createSymbols(const GEO2DPointGeometry* geometry) const { std::vector<GEOSymbol*>* result = new std::vector<GEOSymbol*>(); const JSONObject* properties = geometry->getFeature()->getProperties(); const double popMax = properties->getAsNumber("POP_MAX", 0); const double boxExtent = 50000; const double baseArea = boxExtent * boxExtent; const double volume = popMax * boxExtent * 3500; const double height = volume / baseArea; BoxShape* bs = new BoxShape(new Geodetic3D(geometry->getPosition(), 0), RELATIVE_TO_GROUND, Vector3D(boxExtent / 4, boxExtent / 4, height / 2), 2, Color::fromRGBA(0.99f, 0.8f, 0.08f, 1.0f), Color::newFromRGBA(0.35f, 0.28f, 0.03f, 1.0f), true); result->push_back(new GEOShapeSymbol(bs)); const std::string label = IStringUtils::instance()->toString( IMathUtils::instance()->round(popMax / 1000) ); Mark* mark = new Mark(label, Geodetic3D(geometry->getPosition(), height / 5), RELATIVE_TO_GROUND); result->push_back(new GEOMarkSymbol(mark)); return result; } std::vector<GEOSymbol*>* createSymbols(const GEO2DLineStringGeometry* geometry) const { return NULL; } std::vector<GEOSymbol*>* createSymbols(const GEO2DMultiLineStringGeometry* geometry) const { return NULL; } std::vector<GEOSymbol*>* createSymbols(const GEO2DPolygonGeometry* geometry) const { return NULL; } std::vector<GEOSymbol*>* createSymbols(const GEO2DMultiPolygonGeometry* geometry) const { return NULL; } }; void G3M3DSymbologyDemoScene::rawSelectOption(const std::string& option, int optionIndex) { } void G3M3DSymbologyDemoScene::rawActivate(const G3MContext* context) { G3MDemoModel* model = getModel(); G3MWidget* g3mWidget = model->getG3MWidget(); PlanetRenderer* planetRenderer = model->getPlanetRenderer(); planetRenderer->setVerticalExaggeration(16); ElevationDataProvider* elevationDataProvider = new SingleBilElevationDataProvider(URL("file:///full-earth-2048x1024.bil"), Sector::fullSphere(), Vector2I(2048, 1024)); planetRenderer->setElevationDataProvider(elevationDataProvider, true); MapBoxLayer* layer = new MapBoxLayer("examples.map-qogxobv1", TimeInterval::fromDays(30), true, 3); model->getLayerSet()->addLayer(layer); g3mWidget->setBackgroundColor( Color::fromRGBA(0.19f, 0.23f, 0.22f, 1.0f) ); GEORenderer* geoRenderer = model->getGEORenderer(); geoRenderer->loadJSON(URL("file:///uscitieslite.geojson"), new USCitiesSymbolizer()); g3mWidget->setAnimatedCameraPosition(TimeInterval::fromSeconds(5), Geodetic3D::fromDegrees(25.5, -74.52, 1595850), Angle::zero(), //Angle::fromDegrees(45) Angle::fromDegrees(45 - 90) ); }
37.299145
124
0.605866
[ "geometry", "vector", "model" ]
78024a0d49d1b8c5476dc60f63fd574b4877d81d
4,644
cpp
C++
arangod/Aql/Collection.cpp
mikestaub/arangodb
1bdf414de29b31bcaf80769a095933f66f8256ce
[ "ICU", "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
arangod/Aql/Collection.cpp
mikestaub/arangodb
1bdf414de29b31bcaf80769a095933f66f8256ce
[ "ICU", "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
arangod/Aql/Collection.cpp
mikestaub/arangodb
1bdf414de29b31bcaf80769a095933f66f8256ce
[ "ICU", "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "Collection.h" #include "Basics/StaticStrings.h" #include "Basics/StringUtils.h" #include "Basics/Exceptions.h" #include "Cluster/ClusterInfo.h" #include "Cluster/ClusterMethods.h" #include "Cluster/ServerState.h" #include "VocBase/LogicalCollection.h" #include "VocBase/transaction.h" #include "VocBase/vocbase.h" #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using namespace arangodb::aql; /// @brief create a collection wrapper Collection::Collection(std::string const& name, TRI_vocbase_t* vocbase, TRI_transaction_type_e accessType) : collection(nullptr), currentShard(), name(name), vocbase(vocbase), accessType(accessType), isReadWrite(false) { TRI_ASSERT(!name.empty()); TRI_ASSERT(vocbase != nullptr); } /// @brief destroy a collection wrapper Collection::~Collection() {} /// @brief get the collection id TRI_voc_cid_t Collection::cid() const { TRI_ASSERT(collection != nullptr); return collection->cid(); } /// @brief count the number of documents in the collection size_t Collection::count() const { if (numDocuments == UNINITIALIZED) { if (arangodb::ServerState::instance()->isCoordinator()) { // cluster case uint64_t result; int res = arangodb::countOnCoordinator(vocbase->name(), name, result); if (res != TRI_ERROR_NO_ERROR) { THROW_ARANGO_EXCEPTION_MESSAGE( res, "could not determine number of documents in collection"); } numDocuments = static_cast<int64_t>(result); } else { // local case // cache the result numDocuments = static_cast<int64_t>(collection->numberDocuments()); } } return static_cast<size_t>(numDocuments); } /// @brief returns the collection's plan id TRI_voc_cid_t Collection::getPlanId() const { auto clusterInfo = arangodb::ClusterInfo::instance(); auto collectionInfo = clusterInfo->getCollection(vocbase->name(), name); if (collectionInfo.get() == nullptr) { THROW_ARANGO_EXCEPTION_FORMAT(TRI_ERROR_INTERNAL, "collection not found '%s' -> '%s'", vocbase->name().c_str(), name.c_str()); } return collectionInfo.get()->cid(); } /// @brief returns the shard ids of a collection std::shared_ptr<std::vector<std::string>> Collection::shardIds() const { auto clusterInfo = arangodb::ClusterInfo::instance(); return clusterInfo->getShardList( arangodb::basics::StringUtils::itoa(getPlanId())); } /// @brief returns the shard keys of a collection std::vector<std::string> Collection::shardKeys() const { auto clusterInfo = arangodb::ClusterInfo::instance(); std::string id; if (arangodb::ServerState::instance()->isDBServer() && collection->planId() > 0) { id = std::to_string(collection->planId()); } else { id = name; } auto collectionInfo = clusterInfo->getCollection(vocbase->name(), id); if (collectionInfo.get() == nullptr) { THROW_ARANGO_EXCEPTION_FORMAT(TRI_ERROR_INTERNAL, "collection not found '%s' -> '%s'", vocbase->name().c_str(), name.c_str()); } std::vector<std::string> keys; for (auto const& x : collectionInfo.get()->shardKeys()) { keys.emplace_back(x); } return keys; } /// @brief whether or not the collection uses the default sharding bool Collection::usesDefaultSharding() const { // check if collection shard keys are only _key std::vector<std::string> sk(shardKeys()); if (sk.size() != 1 || sk[0] != StaticStrings::KeyString) { return false; } return true; }
32.027586
80
0.649871
[ "vector" ]
7802a0132c5f14a1af36ac4c5057e4bae5942bc8
40,318
cpp
C++
test/unit/math/fwd/mat/fun/dot_product_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
test/unit/math/fwd/mat/fun/dot_product_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
test/unit/math/fwd/mat/fun/dot_product_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/fwd/mat.hpp> #include <gtest/gtest.h> #include <vector> TEST(AgradFwdMatrixDotProduct, vector_vector_fd) { using stan::math::vector_d; using stan::math::vector_fd; vector_d vd_1(3), vd_2(3); vector_fd vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << 1, 3, -5; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vd_2 << 4, -2, -1; vv_2 << 4, -2, -1; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; EXPECT_FLOAT_EQ(3, stan::math::dot_product(vv_1, vd_2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(vd_1, vv_2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(vv_1, vv_2).val_); EXPECT_FLOAT_EQ(1, stan::math::dot_product(vv_1, vd_2).d_); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(vd_1, vv_2).d_); EXPECT_FLOAT_EQ(0, stan::math::dot_product(vv_1, vv_2).d_); } TEST(AgradFwdMatrixDotProduct, vector_vector_fd_exception) { using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); vector_d d2(2); vector_fd v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_fd) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; row_vector_d d1(3); row_vector_fd v1(3); vector_d d2(3); vector_fd v2(3); d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_fd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; row_vector_d d1(3); row_vector_fd v1(3); vector_d d2(2); vector_fd v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_fd) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); row_vector_d d2(3); row_vector_fd v2(3); d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_fd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); row_vector_d d2(2); row_vector_fd v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_fd) { using stan::math::row_vector_d; using stan::math::row_vector_fd; row_vector_d d1(3), d2(3); row_vector_fd v1(3), v2(3); d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_fd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_fd; row_vector_d d1(3), d2(2); row_vector_fd v1(3), v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, stdvector_stdvector_fd) { using stan::math::fvar; using std::vector; vector<fvar<double> > fv1; vector<fvar<double> > fv2; vector<double> dv; fvar<double> a = 1.0; fvar<double> b = 3.0; fvar<double> c = 5.0; a.d_ = 1.0; b.d_ = 1.0; c.d_ = 1.0; fv1.push_back(a); fv1.push_back(b); fv1.push_back(c); fv2.push_back(a); fv2.push_back(b); fv2.push_back(c); dv.push_back(2.0); dv.push_back(4.0); dv.push_back(6.0); EXPECT_FLOAT_EQ(44.0, dot_product(fv1, dv).val_); EXPECT_FLOAT_EQ(44.0, dot_product(dv, fv1).val_); EXPECT_FLOAT_EQ(35.0, dot_product(fv1, fv2).val_); EXPECT_FLOAT_EQ(12.0, dot_product(fv1, dv).d_); EXPECT_FLOAT_EQ(12.0, dot_product(dv, fv1).d_); EXPECT_FLOAT_EQ(18.0, dot_product(fv1, fv2).d_); } TEST(AgradFwdMatrixDotProduct, matrix_matrix_fd_exception) { using stan::math::dot_product; using stan::math::matrix_d; using stan::math::matrix_fd; matrix_d d1(3, 3); matrix_d d2(3, 2); matrix_d d3(2, 3); matrix_fd v1(3, 3); matrix_fd v2(3, 3); matrix_fd v3(3, 2); matrix_fd v4(3, 2); matrix_fd v5(2, 3); matrix_fd v6(2, 3); d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; v2 << 4, -2, -1, 2, 1, 2, 1, 3, -5; v3 << 4, -2, -1, 2, 1, 2; v4 << 4, -2, -1, 2, 1, 2; v5 << 4, -2, -1, 2, 1, 2; v6 << 4, -2, -1, 2, 1, 2; EXPECT_THROW(dot_product(v1, d1), std::invalid_argument); EXPECT_THROW(dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(dot_product(v1, d3), std::invalid_argument); EXPECT_THROW(dot_product(v1, v2), std::invalid_argument); EXPECT_THROW(dot_product(v1, v3), std::invalid_argument); EXPECT_THROW(dot_product(v1, v4), std::invalid_argument); EXPECT_THROW(dot_product(v1, v5), std::invalid_argument); EXPECT_THROW(dot_product(v1, v6), std::invalid_argument); EXPECT_THROW(dot_product(v2, d1), std::invalid_argument); EXPECT_THROW(dot_product(v2, d2), std::invalid_argument); EXPECT_THROW(dot_product(v2, d3), std::invalid_argument); EXPECT_THROW(dot_product(v2, v1), std::invalid_argument); EXPECT_THROW(dot_product(v2, v3), std::invalid_argument); EXPECT_THROW(dot_product(v2, v4), std::invalid_argument); EXPECT_THROW(dot_product(v2, v5), std::invalid_argument); EXPECT_THROW(dot_product(v2, v6), std::invalid_argument); EXPECT_THROW(dot_product(d1, v1), std::invalid_argument); EXPECT_THROW(dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(dot_product(d1, v3), std::invalid_argument); EXPECT_THROW(dot_product(d1, v4), std::invalid_argument); EXPECT_THROW(dot_product(d1, v5), std::invalid_argument); EXPECT_THROW(dot_product(d1, v6), std::invalid_argument); EXPECT_THROW(dot_product(d2, v1), std::invalid_argument); EXPECT_THROW(dot_product(d2, v2), std::invalid_argument); EXPECT_THROW(dot_product(d2, v3), std::invalid_argument); EXPECT_THROW(dot_product(d2, v4), std::invalid_argument); EXPECT_THROW(dot_product(d2, v5), std::invalid_argument); EXPECT_THROW(dot_product(d2, v6), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, vector_vector_fd_length) { using stan::math::vector_d; using stan::math::vector_fd; vector_d vd_1(3), vd_2(3); vector_fd vv_1(3), vv_2(3); stan::math::size_type length = 2; vd_1 << 1, 3, -5; vv_1 << 1, 3, -5; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vd_2 << 4, -2, -1; vv_2 << 4, -2, -1; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vv_1, vd_2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vd_1, vv_2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vv_1, vv_2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(vv_1, vd_2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(vd_1, vv_2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(vv_1, vv_2, length).d_); } TEST(AgradFwdMatrixDotProduct, vector_vector_fd_no_exception_length) { using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); vector_d d2(2); vector_fd v2(4); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2; v2 << 4, -2, -1, 2; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; v2(3).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_fd_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; row_vector_d d1(3); row_vector_fd v1(3); vector_d d2(3); vector_fd v2(3); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_fd_no_exception_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; row_vector_d d1(3); row_vector_fd v1(3); vector_d d2(2); vector_fd v2(4); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2; v2 << 4, -2, -1, 2; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; v2(3).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_fd_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); row_vector_d d2(3); row_vector_fd v2(3); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_fd_no_exception_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; using stan::math::vector_d; using stan::math::vector_fd; vector_d d1(3); vector_fd v1(3); row_vector_d d2(2); row_vector_fd v2(4); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2; v2 << 4, -2, -1, 2; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; v2(3).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_fd_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; row_vector_d d1(3), d2(3); row_vector_fd v1(3), v2(3); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2, -1; v2 << 4, -2, -1; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_fd_no_exception_length) { using stan::math::row_vector_d; using stan::math::row_vector_fd; row_vector_d d1(3), d2(2); row_vector_fd v1(3), v2(4); stan::math::size_type length = 2; d1 << 1, 3, -5; v1 << 1, 3, -5; v1(0).d_ = 1.0; v1(1).d_ = 1.0; v1(2).d_ = 1.0; d2 << 4, -2; v2 << 4, -2, -1, 2; v2(0).d_ = 1.0; v2(1).d_ = 1.0; v2(2).d_ = 1.0; v2(3).d_ = 1.0; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_); } TEST(AgradFwdMatrixDotProduct, stdvector_stdvector_fd_length) { using stan::math::fvar; using std::vector; vector<fvar<double> > fv1; vector<fvar<double> > fv2; vector<double> dv; stan::math::size_type length = 2; fvar<double> a = 1.0; fvar<double> b = 3.0; fvar<double> c = 5.0; a.d_ = 1.0; b.d_ = 1.0; c.d_ = 1.0; fv1.push_back(a); fv1.push_back(b); fv1.push_back(c); fv2.push_back(a); fv2.push_back(b); fv2.push_back(c); dv.push_back(2.0); dv.push_back(4.0); dv.push_back(6.0); EXPECT_FLOAT_EQ(14.0, dot_product(fv1, dv, length).val_); EXPECT_FLOAT_EQ(14.0, dot_product(dv, fv1, length).val_); EXPECT_FLOAT_EQ(10.0, dot_product(fv1, fv2, length).val_); EXPECT_FLOAT_EQ(6.0, dot_product(fv1, dv, length).d_); EXPECT_FLOAT_EQ(6.0, dot_product(dv, fv1, length).d_); EXPECT_FLOAT_EQ(8.0, dot_product(fv1, fv2, length).d_); } TEST(AgradFwdMatrixDotProduct, matrix_matrix_fd_exception_length) { using stan::math::dot_product; using stan::math::matrix_d; using stan::math::matrix_fd; stan::math::size_type length = 3; matrix_d d1(3, 3); matrix_d d2(3, 2); matrix_d d3(2, 3); matrix_fd v1(3, 3); matrix_fd v2(3, 3); matrix_fd v3(3, 2); matrix_fd v4(3, 2); matrix_fd v5(2, 3); matrix_fd v6(2, 3); d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; v2 << 4, -2, -1, 2, 1, 2, 1, 3, -5; v3 << 4, -2, -1, 2, 1, 2; v4 << 4, -2, -1, 2, 1, 2; v5 << 4, -2, -1, 2, 1, 2; v6 << 4, -2, -1, 2, 1, 2; EXPECT_THROW(dot_product(v1, d1, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, d2, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, d3, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d1, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d2, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d3, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v6, length), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, vector_vector_ffd) { using stan::math::fvar; using stan::math::vector_d; using stan::math::vector_ffd; vector_d vd_1(3), vd_2(3); vector_ffd vv_1(3), vv_2(3); fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = -5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; vd_1 << 1, 3, -5; vv_1 << a, b, c; vd_2 << 4, -2, -1; vv_2 << d, e, f; EXPECT_FLOAT_EQ(3, stan::math::dot_product(vv_1, vd_2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(vd_1, vv_2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(vv_1, vv_2).val_.val()); EXPECT_FLOAT_EQ(1, stan::math::dot_product(vv_1, vd_2).d_.val()); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(vd_1, vv_2).d_.val()); EXPECT_FLOAT_EQ(0, stan::math::dot_product(vv_1, vv_2).d_.val()); } TEST(AgradFwdMatrixDotProduct, vector_vector_ffd_exception) { using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3), d2(2); vector_ffd v1(3), v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_ffd) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; row_vector_d d1(3); row_vector_ffd v1(3); vector_d d2(3); vector_ffd v2(3); fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = -5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_.val()); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_.val()); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_.val()); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_ffd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; row_vector_d d1(3); row_vector_ffd v1(3); vector_d d2(2); vector_ffd v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_ffd) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3); vector_ffd v1(3); row_vector_d d2(3); row_vector_ffd v2(3); fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = -5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_.val()); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_.val()); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_.val()); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_.val()); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_ffd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3); vector_ffd v1(3); row_vector_d d2(2); row_vector_ffd v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_ffd) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; row_vector_d d1(3), d2(3); row_vector_ffd v1(3), v2(3); fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = -5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, d2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(d1, v2).val_.val()); EXPECT_FLOAT_EQ(3, stan::math::dot_product(v1, v2).val_.val()); EXPECT_FLOAT_EQ(1, stan::math::dot_product(v1, d2).d_.val()); EXPECT_FLOAT_EQ(-1, stan::math::dot_product(d1, v2).d_.val()); EXPECT_FLOAT_EQ(0, stan::math::dot_product(v1, v2).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_ffd_exception) { using stan::math::row_vector_d; using stan::math::row_vector_ffd; row_vector_d d1(3), d2(2); row_vector_ffd v1(3), v2(4); EXPECT_THROW(stan::math::dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(stan::math::dot_product(v1, v2), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, stdvector_stdvector_ffd) { using stan::math::fvar; using std::vector; vector<fvar<fvar<double> > > fv1, fv2; vector<double> dv; fvar<fvar<double> > a, b, c; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; fv1.push_back(a); fv1.push_back(b); fv1.push_back(c); fv2.push_back(a); fv2.push_back(b); fv2.push_back(c); dv.push_back(2.0); dv.push_back(4.0); dv.push_back(6.0); EXPECT_FLOAT_EQ(44.0, dot_product(fv1, dv).val_.val()); EXPECT_FLOAT_EQ(44.0, dot_product(dv, fv1).val_.val()); EXPECT_FLOAT_EQ(35.0, dot_product(fv1, fv2).val_.val()); EXPECT_FLOAT_EQ(12.0, dot_product(fv1, dv).d_.val()); EXPECT_FLOAT_EQ(12.0, dot_product(dv, fv1).d_.val()); EXPECT_FLOAT_EQ(18.0, dot_product(fv1, fv2).d_.val()); } TEST(AgradFwdMatrixDotProduct, matrix_matrix_ffd_exception) { using stan::math::dot_product; using stan::math::fvar; using stan::math::matrix_d; using stan::math::matrix_ffd; matrix_d d1(3, 3), d2(3, 2), d3(2, 3); matrix_ffd v1(3, 3), v2(3, 3), v3(3, 2), v4(3, 2), v5(2, 3), v6(2, 3); fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << a, b, c, d, e, f, a, b, c; v2 << a, b, c, d, e, f, a, b, c; v3 << d, e, f, a, b, c; v4 << d, e, f, a, b, c; v5 << d, e, f, a, b, c; v6 << d, e, f, a, b, c; EXPECT_THROW(dot_product(v1, d1), std::invalid_argument); EXPECT_THROW(dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(dot_product(v1, d3), std::invalid_argument); EXPECT_THROW(dot_product(v1, v2), std::invalid_argument); EXPECT_THROW(dot_product(v1, v3), std::invalid_argument); EXPECT_THROW(dot_product(v1, v4), std::invalid_argument); EXPECT_THROW(dot_product(v1, v5), std::invalid_argument); EXPECT_THROW(dot_product(v1, v6), std::invalid_argument); EXPECT_THROW(dot_product(v2, d1), std::invalid_argument); EXPECT_THROW(dot_product(v2, d2), std::invalid_argument); EXPECT_THROW(dot_product(v2, d3), std::invalid_argument); EXPECT_THROW(dot_product(v2, v1), std::invalid_argument); EXPECT_THROW(dot_product(v2, v3), std::invalid_argument); EXPECT_THROW(dot_product(v2, v4), std::invalid_argument); EXPECT_THROW(dot_product(v2, v5), std::invalid_argument); EXPECT_THROW(dot_product(v2, v6), std::invalid_argument); EXPECT_THROW(dot_product(d1, v1), std::invalid_argument); EXPECT_THROW(dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(dot_product(d1, v3), std::invalid_argument); EXPECT_THROW(dot_product(d1, v4), std::invalid_argument); EXPECT_THROW(dot_product(d1, v5), std::invalid_argument); EXPECT_THROW(dot_product(d1, v6), std::invalid_argument); EXPECT_THROW(dot_product(d2, v1), std::invalid_argument); EXPECT_THROW(dot_product(d2, v2), std::invalid_argument); EXPECT_THROW(dot_product(d2, v3), std::invalid_argument); EXPECT_THROW(dot_product(d2, v4), std::invalid_argument); EXPECT_THROW(dot_product(d2, v5), std::invalid_argument); EXPECT_THROW(dot_product(d2, v6), std::invalid_argument); } TEST(AgradFwdMatrixDotProduct, vector_vector_ffd_length) { using stan::math::fvar; using stan::math::vector_d; using stan::math::vector_ffd; vector_d vd_1(3), vd_2(3); vector_ffd vv_1(3), vv_2(3); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; vd_1 << 1, 3, -5; vv_1 << a, b, c; vd_2 << 4, -2, -1; vv_2 << d, e, f; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vv_1, vd_2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vd_1, vv_2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(vv_1, vv_2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(vv_1, vd_2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(vd_1, vv_2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(vv_1, vv_2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, vector_vector_ffd_no_exception_length) { using stan::math::fvar; using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3), d2(2); vector_ffd v1(3), v2(4); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2; v2 << d, e, f, -e; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_ffd_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; row_vector_d d1(3); row_vector_ffd v1(3); vector_d d2(3); vector_ffd v2(3); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_vector_no_exception_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; row_vector_d d1(3); row_vector_ffd v1(3); vector_d d2(2); vector_ffd v2(4); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2; v2 << d, e, f, -e; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_ffd_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3); vector_ffd v1(3); row_vector_d d2(3); row_vector_ffd v2(3); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, vector_rowvector_ffd_no_exception_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; using stan::math::vector_d; using stan::math::vector_ffd; vector_d d1(3); vector_ffd v1(3); row_vector_d d2(2); row_vector_ffd v2(4); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2; v2 << d, e, f, -e; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_ffd_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; row_vector_d d1(3), d2(3); row_vector_ffd v1(3), v2(3); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2, -1; v2 << d, e, f; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, rowvector_rowvector_ffd_no_exception_length) { using stan::math::fvar; using stan::math::row_vector_d; using stan::math::row_vector_ffd; row_vector_d d1(3), d2(2); row_vector_ffd v1(3), v2(4); stan::math::size_type length = 2; fvar<fvar<double> > a, b, c, d, e, f; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; d.val_.val_ = 4.0; d.d_.val_ = 1.0; e.val_.val_ = -2.0; e.d_.val_ = 1.0; f.val_.val_ = -1.0; f.d_.val_ = 1.0; d1 << 1, 3, -5; v1 << a, b, c; d2 << 4, -2; v2 << d, e, f, -e; EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, d2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(d1, v2, length).val_.val()); EXPECT_FLOAT_EQ(-2, stan::math::dot_product(v1, v2, length).val_.val()); EXPECT_FLOAT_EQ(2, stan::math::dot_product(v1, d2, length).d_.val()); EXPECT_FLOAT_EQ(4, stan::math::dot_product(d1, v2, length).d_.val()); EXPECT_FLOAT_EQ(6, stan::math::dot_product(v1, v2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, stdvector_stdvector_ffd_length) { using stan::math::fvar; using std::vector; vector<fvar<fvar<double> > > fv1, fv2; vector<double> dv; stan::math::size_type length = 2; fvar<fvar<double> > a, b, c; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = 5.0; c.d_.val_ = 1.0; fv1.push_back(a); fv1.push_back(b); fv1.push_back(c); fv2.push_back(a); fv2.push_back(b); fv2.push_back(c); dv.push_back(2.0); dv.push_back(4.0); dv.push_back(6.0); EXPECT_FLOAT_EQ(14.0, dot_product(fv1, dv, length).val_.val()); EXPECT_FLOAT_EQ(14.0, dot_product(dv, fv1, length).val_.val()); EXPECT_FLOAT_EQ(10.0, dot_product(fv1, fv2, length).val_.val()); EXPECT_FLOAT_EQ(6.0, dot_product(fv1, dv, length).d_.val()); EXPECT_FLOAT_EQ(6.0, dot_product(dv, fv1, length).d_.val()); EXPECT_FLOAT_EQ(8.0, dot_product(fv1, fv2, length).d_.val()); } TEST(AgradFwdMatrixDotProduct, matrix_matrix_ffd_exception_length) { using stan::math::dot_product; using stan::math::fvar; using stan::math::matrix_d; using stan::math::matrix_ffd; stan::math::size_type length = 3; matrix_d d1(3, 3), d2(3, 2), d3(2, 3); matrix_ffd v1(3, 3), v2(3, 3), v3(3, 2), v4(3, 2), v5(2, 3), v6(2, 3); fvar<fvar<double> > a, b, c; a.val_.val_ = 1.0; a.d_.val_ = 1.0; b.val_.val_ = 3.0; b.d_.val_ = 1.0; c.val_.val_ = -5.0; c.d_.val_ = 1.0; d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << a, b, c, a, b, c, a, b, c; v2 << a, b, c, a, b, c, a, b, c; v3 << a, b, c, a, b, c; v4 << a, b, c, a, b, c; v5 << a, b, c, a, b, c; v6 << a, b, c, a, b, c; EXPECT_THROW(dot_product(v1, d1, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, d2, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, d3, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(v1, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d1, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d2, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, d3, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(v2, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(d1, v6, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v1, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v2, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v3, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v4, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v5, length), std::invalid_argument); EXPECT_THROW(dot_product(d2, v6, length), std::invalid_argument); }
31.79653
78
0.655935
[ "vector" ]
7803064fe0b7cde5def1b11cad24e4f0bcdd12a7
26,525
cpp
C++
src/magic.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
1
2018-09-16T03:17:50.000Z
2018-09-16T03:17:50.000Z
src/magic.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
src/magic.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
#include "system.h" const char* stype_name [] = { "offensive", "peaceful", "self_only", "object", "room", "continent", "peaceful_other", "weapon", "drink_container", "mob_only", "annoying", "corpse", "recall", "weapon_armor", "replicate", "astral", "non_combat_healing", "cross_continent", "universal", "annoying_evil", "annoying_good", "annoying_undead", "tree" }; const char* magic_entrap_word [] = { "ghost chains", "webs", "vines", "snare", "briars", "entangling vines", "prison of bone" }; int magic_entrap [] = { AFF_GHOST_CHAINS, AFF_ENTANGLED, AFF_ENSNARE, AFF_ENSNARE_TRAPPED, AFF_BRIARTANGLE, AFF_WEB_ENTANGLE, AFF_BONE_PRISON }; bool trigger_attack( char_data*, char_data* ); /* * LOCAL FUNCTIONS */ int check_mana ( char_data*, int ); int mana_cost ( char_data*, int ); void spell_action ( int action, char_data*, thing_data*, obj_data* ); void mod_element_damage( char_data*, int&, int ); /* * CAST_DATA CREATOR/DESTRUCTOR */ Cast_Data :: Cast_Data( ) { record_new( sizeof( cast_data ), MEM_SPELL ); target = NULL; customer = NULL; cast_type = 0; vzero( reagent, MAX_SPELL_WAIT ); vzero( tool, MAX_SPELL_WAIT ); } Cast_Data :: ~Cast_Data( ) { record_delete( sizeof( cast_data ), MEM_SPELL ); } /* * SANITY CHECK ROUTINES */ bool null_caster( char_data* ch, int spell ) { if( ch == NULL ) { bug( "%s: Null pointer for caster.", skill_table[spell].name ); return TRUE; } return FALSE; } bool null_corpse( obj_data* corpse, int spell ) { if( corpse == NULL ) { bug( "%s: Null pointer for corpse.", skill_table[spell].name ); return TRUE; } return FALSE; } /* * Check for Fizzle of Spells */ affect_data* find_affect( char_data* ch, int affect ) { affect_data* paf = NULL; if( affect < 0 ) return paf; for( int i = ch->affected.size-1; i >= 0; i-- ) { if( ch->affected[i]->type == affect ) { paf = ch->affected[i]; break; } } return paf; } bool Char_Data :: Fizzle( const char* word ) { int affect = -1; affect_data* paf = NULL; for( int i = 0; i < 7; i++ ) { affect = magic_entrap[i]; paf = find_affect( this, affect ); if( paf != NULL ) { if( number_range( 0, 100 ) < paf->mmodifier[1] ) { send( this, "%s interferes with your %s.\r\n", magic_entrap_word[i], word ); return TRUE; } } } return FALSE; } /* * CHECK_MANA ROUTINES */ int check_mana( char_data* ch, int spell ) { int i = mana_cost( ch, spell ); if( ch->mana < i ) { send( ch, "You need %d energy points to %s that.\r\n", i, ch->pcdata->clss == CLSS_DANCER ? "sing" : "cast" ); return -1; } return i; } int mana_cost( char_data* ch, int spell ) { int mana; bool error = FALSE; if( ch->species != NULL ) return 0; mana = evaluate( spell_table[spell].cast_mana, error, 10*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL ); if( error ) bug( "Mana_Cost: Evaluate failed for %s.", spell_table[spell].name ); if( ch->pcdata != NULL && ch->pcdata->clss == CLSS_MAGE ) mana += mana*mana_absorption( ch )/10000; return mana; } int song_cost( char_data* ch, int spell ) { int mana; bool error = FALSE; if( ch->species != NULL ) return 0; mana = evaluate( spell_table[spell].song_regen, error, 10*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL ); if( error ) bug( "Song Regen: Evaluate failed for %s.", spell_table[spell].name ); return mana; } int move_cost( char_data* ch, int skill ) { int move; bool error = FALSE; if( ch->species != NULL && ch->pcdata == NULL ) return 0; move = evaluate( skill_table[skill].move_cost, error, 10*ch->get_skill( skill )/MAX_SKILL_LEVEL ); if( error ) bug( "Move_Regen: Evaluate failed for %s.", skill_table[skill].name ); if( ch->pcdata != NULL && ch->pcdata->clss == CLSS_DANCER ) move += move*mana_absorption( ch )/10000; return move; } int mana_absorption( char_data* ch ) { obj_data* obj; int cost; int number; int total = 0; for( int i = 0; i < ch->wearing; i++ ) { obj = (obj_data*) ch->wearing[i]; if( obj->mana_absorbing_metal( ) && obj->pIndexData->item_type != ITEM_WEAPON ) { cost = 0; number = 0; for( int j = 0; j <= MAX_MATERIAL; j++ ) if( is_set( &obj->materials, j ) ) { number++; if( j >= MAT_METAL ) cost += obj->Empty_Weight( )*material_table[j].mana; } if( number > 0 ) total += cost/number; } } return total; } /* * REAGENT ROUTINE */ int used_reagent( cast_data* cast, obj_data* obj ) { int count = 0; int i; for( i = 0; i < MAX_SPELL_WAIT; i++ ) if( cast->reagent[i] == obj && spell_table[cast->spell].reagent[i] > 0 || cast->target == obj ) count++; return count; } obj_data* suitable_reagent( cast_data* cast, obj_clss_data* obj_clss, obj_data *obj ) { // sanity check, don't like invalid objects if( obj == NULL || !obj->Is_Valid( ) ) return NULL; if( ( obj->pIndexData == obj_clss || obj_clss->item_type == ITEM_CROSS && obj->pIndexData->item_type == ITEM_CROSS ) && used_reagent( cast, obj ) < obj->number ) { // this is the reagent, yippee return obj; } else if( obj->pIndexData->item_type == ITEM_CONTAINER ) { // search container for reagents for( int k = 0; k < obj->contents; k++ ) { obj_data* obj2 = object( obj->contents[k] ); // sanity check, don't like invalid objects if( obj2 == NULL || !obj2->Is_Valid( ) ) continue; if( obj2->pIndexData == obj_clss && used_reagent( cast, obj2 ) < obj2->number ) { // this is the reagent, yippee return obj2; } } } return NULL; } bool has_reagents( char_data* ch, cast_data* cast ) { int spell = cast->spell; bool prepare = cast->prepare; int wait_prepare = spell_table[spell].prepare; obj_clss_data* obj_clss; for( int i = ( prepare ? 0 : wait_prepare ); i < ( prepare ? wait_prepare : MAX_SPELL_WAIT ); i++ ) { // get object class for reagent if( ( obj_clss = get_obj_index( abs( spell_table[spell].reagent[i] ) ) ) == NULL ) continue; // sanity check - don't cast spell on a reagent obj_data* target = object( cast->target ); if( target != NULL && target->pIndexData->vnum == obj_clss->vnum ) { send( ch, "You can't cast a spell on one of its own reagents.\r\n" ); return FALSE; } // let's go reagent hunting! cast->reagent[i] = NULL; // scan inventory for reagents for( int j = 0; j < ch->contents; j++ ) { obj_data* obj = object( ch->contents[j] ); if( obj != NULL && obj->Is_Valid( ) && ( obj->pIndexData == obj_clss || obj_clss->item_type == ITEM_CROSS && obj->pIndexData->item_type == ITEM_CROSS ) && used_reagent( cast, obj ) < obj->number ) { cast->reagent[i] = obj; break; } } // scan worn stuff (including bags) if( cast->reagent[i] == NULL ) { for( int j = 0; j < ch->wearing; j++ ) { obj_data* obj = suitable_reagent( cast, obj_clss, object( ch->wearing[j] ) ); if( obj != NULL ) { cast->reagent[i] = obj; break; } } } // scan inventory inventory again (this time including bags) if( cast->reagent[i] == NULL ) { for( int j = 0; j < ch->contents; j++ ) { obj_data* obj = suitable_reagent( cast, obj_clss, object( ch->contents[j] ) ); if( obj != NULL ) { cast->reagent[i] = obj; break; } } } // if it's still NULL, it ain't looking good for the non-enlightened if( cast->reagent[i] == NULL ) { if( ch->pcdata == NULL || ch->shdata->level >= LEVEL_APPRENTICE ) { send( ch, "You create %s.\r\n", obj_clss->Name( ) ); obj_data* obj = create( obj_clss ); obj->To( ch ); cast->reagent[i] = obj; continue; } send( ch, "You need %s to cast %s.\r\n", obj_clss->Name( ), spell_table[spell].name ); return FALSE; } } return TRUE; } void remove_reagent( obj_data* reagent, char_data* ch ) { if( reagent->pIndexData->item_type != ITEM_REAGENT || reagent->value[0] <= 1 ) { // just the one item, or the last charge obj_data *temp = object( reagent->From( 1 ) ); if( temp && temp->Is_Valid() ) temp->Extract(); else roach( "remove_reagent: unable to remove reagent from %s [single]", ch ); } else if( reagent->number > 1 ) { if( reagent->array == ch->array ) { // special handling for reagents in the inventory obj_data *temp = object( reagent->From( reagent->number - 1 ) ); if( !temp || !temp->Is_Valid() ) { roach( "remove_reagent: unable to remove reagent from %s [multiple]", ch ); return; } // update reagent and give back to inventory reagent->value[0]--; temp->To( ch ); consolidate( temp ); } else { // special handling for reagents in bags obj_data *temp = object( reagent->From( 1 ) ); if( !temp || !temp->Is_Valid() ) { roach( "remove_reagent: unable to remove reagent from %s [multiple]", ch ); return; } // update reagent and give back to inventory temp->value[0]--; temp->To( ch ); consolidate( temp ); } } else { // subtract 1 from the charge reagent->value[0]--; } } /* * CASTING ROUTINES */ int find_spell( char_data* ch, char* argument, int length ) { int spell; for( spell = 0; spell < SPELL_COUNT; spell++ ) if( ( ch->species != NULL || ch->get_skill( SPELL_FIRST + spell ) != UNLEARNT ) && !strncasecmp( spell_table[ spell ].name, argument, abs( length ) ) ) return spell; if( length < 0 ) return -1; for( spell = 0; spell < SPELL_COUNT; spell++ ) if( !strncasecmp( spell_table[ spell ].name, argument, length ) ) break; if( ch->pcdata->clss == CLSS_DANCER ) { if( spell == SPELL_COUNT ) send( ch, "Unknown Song.\r\n" ); else send( ch, "You don't know the %s.\r\n", spell_table[ spell ].name ); return -1; } if( spell == SPELL_COUNT ) send( ch, "Unknown Spell.\r\n" ); else send( ch, "You don't know the spell %s.\r\n", spell_table[ spell ].name ); return -1; } void do_focus( char_data *ch, char* ) { send( "Function disabled.\r\n", ch ); } void do_cast( char_data* ch, char* argument ) { cast_data* cast; cast_data* prepare = NULL;; int spell = -1; int mana; if( is_confused_pet( ch ) || is_familiar( ch ) || is_shifted( ch ) ) return; if( is_set( ch->affected_by, AFF_SILENCE ) && !is_apprentice( ch ) ) { send( ch, "You are silenced and unable to cast spells!\r\n" ); return; } if( ch->cast != NULL && ch->cast->cast_type == UPDATE_SONG ) { send( ch, "You can't sing and cast spells at the same time.\r\n" ); return; } if( ch->Fizzle( "attempted casting of a spell" ) ) return; /* same as blade-dancer, better check put in after spell is found if( ch->pcdata->clss == CLSS_DANCER ) { send( ch, "You know nothing of casting spells.\r\n" ); return; } */ if( *argument == '\0' ) { send( ch, "What spell do you want to cast?\r\n" ); return; } // new spellfinding code int target = strlen( argument ); // loop until we find a spell or get down to zero arguments for( ;; ) { // see if we have a valid spell name spell = find_spell( ch, argument, -target ); if( spell != -1 ) break; // if not, go back to the previous word while( isspace( argument[ target ] ) ) target--; // to the start of that word for( ; argument[ target ] != ' ' && target > 0; target-- ); // and the spaces before that word while( isspace( argument[ target ] ) ) target--; // if we're down to zero it was the first argument of the spell, so // let it give the unknown spell message and exit if( target == 0 ) { spell = find_spell( ch, argument, strlen( argument ) ); if( spell == -1 ) return; } // increase target separator by 1 so rather than sitting on the // 'l rabbit' of 'fireball rabbit' it sits on the ' ' between the words target++; } mana = 0; if( spell_table[spell].prepare != 0 ) { if( ( prepare = has_prepared( ch, spell ) ) == NULL ) { send( ch, "You don't have that spell prepared.\r\n" ); return; } } else { if( ch->species == NULL && ( mana = check_mana( ch, spell ) ) < 0 ) return; } if( !allowed_location( ch, &spell_table[spell].location, "cast", spell_table[spell].name ) ) return; if( ch->species == NULL && ch->fighting != NULL ) if( spell_table[spell].type == STYPE_NON_COMBAT_HEALING ) { send( ch, "You can't cast that spell while fighting.\r\n" ); return; } if( spell_table[spell].song ) { send( ch, "That is a song, not a spell.\r\n" ); return; } cast = new cast_data; cast->spell = spell; cast->prepare = FALSE; cast->wait = spell_table[spell].prepare-1; cast->mana = mana; cast->cast_type = UPDATE_CAST; if( !get_target( ch, cast, &argument[ target] ) || !has_reagents( ch, cast ) ) { delete cast; return; } send( ch, "You begin casting %s.\r\n", spell_table[spell].name ); if( ch->species == NULL && spell_table[spell].prepare != 0 ) { if( --prepare->times == 0 ) { remove( ch->prepare, prepare ); delete prepare; } else if( is_set( &ch->pcdata->message, MSG_SPELL_COUNTER ) ) { send( ch, "[ You have %s %s spell%s remaining. ]\r\n", number_word( prepare->times, ch ), spell_table[spell].name, prepare->times == 1 ? "" : "s" ); } } ch->cast = cast; ch->mana -= mana; int delay = ch->species != NULL ? 6 : 15-10*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL; set_delay(ch, delay); return; } void do_prepare( char_data* ch, char* argument ) { char tmp [ MAX_INPUT_LENGTH ]; cast_data* cast; int spell; int mana; int length = strlen( argument ); if( ch->species != NULL ) { send( ch, "Only players can prepare spells.\r\n" ); return; } if( *argument == '\0' ) { if( ch->prepare == NULL ) { send( "You have no spells prepared.\r\n", ch ); return; } page_underlined( ch, "Num Spell Mana\r\n" ); for( cast = ch->prepare; cast != NULL; cast = cast->next ) { sprintf( tmp, "%3d %-25s%3d\r\n", cast->times, spell_table[cast->spell].name, cast->mana*cast->times ); page( ch, tmp ); } return; } if( !strcasecmp( "clear", argument ) ) { delete_list( ch->prepare ); send( ch, "All prepared spells forgotten.\r\n" ); update_max_mana( ch ); return; } if( is_set( ch->affected_by, AFF_SILENCE ) ) { send( "You are silenced and unable to prepare a spell!\r\n", ch ); return; } /* if( is_set( ch->affected_by, AFF_ENTANGLED ) || is_set( ch->affected_by, AFF_ENSNARE_TRAPPED ) ) { send( ch, "You are too entangled to prepare a spell.\r\n" ); return; } */ if( is_entangled( ch, "prepare", true ) ) return; if( ch->position < POS_RESTING ) { send( ch, "You cannot prepare spells while sleeping or meditating.\r\n" ); return; } if( ( spell = find_spell( ch, argument, length ) ) == -1 ) return; if( spell_table[ spell ].prepare == 0 ) { send( ch, "That is not a spell which you prepare.\r\n" ); return; } if( ( mana = check_mana( ch, spell ) ) < 0 ) return; cast = new cast_data; cast->spell = spell; cast->wait = -1; cast->prepare = TRUE; cast->mana = mana; if( !has_reagents( ch, cast ) ) { delete cast; return; } send( ch, "You begin preparing %s.\r\n", spell_table[spell].name ); ch->cast = cast; ch->mana -= mana; int delay = ch->species != NULL ? 12 : 16 - 5*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL; set_delay(ch, delay); return; } cast_data* has_prepared( char_data* ch, int spell ) { cast_data* prepare; if( ch->species == NULL && spell_table[spell].prepare != 0 ) for( prepare = ch->prepare; prepare != NULL; prepare = prepare->next ) if( prepare->spell == spell ) return prepare; return NULL; } /* * UPDATE ROUTINE */ void spell_update( char_data* ch ) { cast_data* cast = ch->cast; thing_data* target = cast->target; char_data* victim = character( target ); int spell = cast->spell; bool prepare = cast->prepare; int wait = ++cast->wait; char_data* rch; int skill; obj_data* reagent; int action; cast_data* prev; if( wait < ( cast->prepare ? spell_table[spell].prepare : spell_table[spell].wait ) ) { reagent = cast->reagent[wait]; action = spell_table[spell].action[wait]; msg_type = cast->prepare ? MSG_PREPARE : MSG_STANDARD; spell_action( action, ch, target, reagent ); if( reagent != NULL && spell_table[spell].reagent[wait] >= 0 ) remove_reagent( reagent, ch ); int delay = ch->species != NULL ? 31 : 35-10*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL; set_delay(ch, delay); return; } ch->cast = NULL; set_delay( ch, 2 ); update_max_mana( ch ); if( !prepare ) { delete cast; if( is_set( &ch->in_room->room_flags, RFLAG_NO_MAGIC ) && !is_apprentice( ch ) ) { fsend( ch, "As you cast %s, you feel the energy drain from you and nothing happens.\r\n", spell_table[spell].name ); send( *ch->array, "%s casts %s, but nothing happens.\r\n", ch, spell_table[spell].name ); return; } send( ch, "+++ You cast %s. +++\r\n", spell_table[spell].name ); send_seen( ch, "%s casts %s.\r\n", ch, spell_table[spell].name ); skill = ( ch->species != NULL ? 8 : 10*ch->get_skill( SPELL_FIRST+spell )/MAX_SKILL_LEVEL ); if( spell_table[spell].type == STYPE_ANNOYING ) { for( int i = 0; i < *ch->array; i++ ) { if( ( rch = mob( ch->array->list[i] ) ) != NULL && can_kill( ch, rch ) && rch->Seen( ch ) ) { check_killer( ch, rch ); if( ch->fighting == NULL ) { ch->fighting = rch; react_attack( ch, rch ); set_delay( ch, 15 ); init_attack( ch, rch ); } else init_attack( rch, ch ); } } } if( spell_table[spell].type == STYPE_ANNOYING_GOOD ) { for( int i = 0; i < *ch->array; i++ ) { if( ( rch = mob( ch->array->list[i] ) ) != NULL && can_kill( ch, rch ) && rch->Seen( ch ) && is_good( rch ) ) { check_killer( ch, rch ); trigger_attack( ch, rch ); if( ch->fighting == NULL ) { ch->fighting = rch; react_attack( ch, rch ); set_delay( ch, 15 ); init_attack( ch, rch ); } else init_attack( rch, ch ); } } } if( spell_table[spell].type == STYPE_ANNOYING_EVIL ) { for( int i = 0; i < *ch->array; i++ ) { if( ( rch = mob( ch->array->list[i] ) ) != NULL && can_kill( ch, rch ) && rch->Seen( ch ) && is_evil( rch ) ) { check_killer( ch, rch ); trigger_attack( ch, rch ); if( ch->fighting == NULL ) { ch->fighting = rch; react_attack( ch, rch ); set_delay( ch, 15 ); init_attack( ch, rch ); } else init_attack( rch, ch ); } } } if( spell_table[spell].type == STYPE_ANNOYING_UNDEAD ) { for( int i = 0; i < *ch->array; i++ ) { if( ( rch = mob( ch->array->list[i] ) ) != NULL && can_kill( ch, rch ) && rch->Seen( ch ) && rch->shdata->race == RACE_UNDEAD ) { check_killer( ch, rch ); trigger_attack( ch, rch ); if( ch->fighting == NULL ) { ch->fighting = rch; react_attack( ch, rch ); set_delay( ch, 15 ); init_attack( ch, rch ); } else init_attack( rch, ch ); } } } if( spell_table[spell].type == STYPE_OFFENSIVE ) { check_killer( ch, victim ); ch->fighting = victim; react_attack( ch, victim ); set_delay( ch, 15 ); init_attack( ch, victim ); } remove_bit( &ch->status, STAT_LEAPING ); remove_bit( &ch->status, STAT_WIMPY ); leave_camouflage(ch); leave_shadows(ch); strip_affect( ch, AFF_INVISIBLE ); remove_bit( ch->affected_by, AFF_INVISIBLE ); ch->improve_skill( SPELL_FIRST+spell ); ( *spell_table[spell].function )( ch, character( target ), target, skill, 0 ); return; } for( prev = ch->prepare; prev != NULL; prev = prev->next ) if( prev->spell == spell ) { prev->times++; delete cast; break; } if( prev == NULL ) { cast->times = 1; cast->next = ch->prepare; ch->prepare = cast; prev = cast; } if( prev->times > 1 ) { send( ch, "You now have %s incantations of %s prepared.\r\n", number_word( prev->times, ch ), spell_table[spell].name ); } else { send( ch, "You have prepared %s.\r\n", spell_table[spell].name ); } update_max_mana( ch ); } void spell_action( int action, char_data* ch, thing_data* target, obj_data* reagent ) { char_data* victim = NULL; if( action < 0 || action > table_max[ TABLE_SPELL_ACT ] ) { roach( "Spell_Action: Impossible action." ); roach( "-- Caster = %s", ch->Name( ) ); return; } if( reagent != NULL ) reagent->selected = 1; if( target == ch ) { act( ch, spell_act_table[action].self_self, ch, NULL, reagent ); act_notchar( spell_act_table[action].others_self, ch, NULL, reagent ); return; } victim = character( target ); if( victim != NULL ) act( ch, spell_act_table[action].self_other, ch, victim, reagent ); else // target isn't a character act( ch, spell_act_table[action].self_other, ch, NULL, reagent, target ); if( target != NULL && victim != NULL && spell_act_table[action].victim_other != empty_string ) { if( victim->position > POS_SLEEPING ) act( victim, spell_act_table[ action ].victim_other, ch, victim, reagent ); act_neither( spell_act_table[ action ].others_other, ch, victim, reagent ); } else { // target isn't a character act_notchar( spell_act_table[action].others_other, ch, NULL, reagent, target ); } } /* * RESISTANCE ROUTINES */ bool makes_save( char_data* victim, char_data* ch, int type, int spell, int level ) { // cast a spell on yourself, always fail if( ch == victim ) return FALSE; // if victim is null, assume passed if (victim == NULL) { roach("makes_save: NULL victim!"); return TRUE; } // if victim is being extracted, assume true if( victim->hit <= 0 ) return TRUE; // small chance of failing or succeeding right out if (number_range(0, 33) == 33) return number_range(0, 1) ? FALSE : TRUE; int chance; switch( type ) { case RES_MAGIC: chance = victim->Save_Magic() + victim->shdata->level / 2; break; case RES_MIND: chance = victim->Save_Mind() + victim->shdata->level / 2; break; case RES_STRENGTH: if (victim->position <= POS_RESTING) return FALSE; chance = 2 * victim->Strength() + victim->shdata->level / 2; break; case RES_DEXTERITY: if (victim->position <= POS_RESTING) return FALSE; chance = 2*victim->Dexterity( ) + victim->shdata->level / 5; break; case RES_HOLY: chance = victim->Save_Holy( ) + victim->shdata->level/2; break; case RES_POISON: chance = victim->Save_Poison( ) + victim->shdata->level/2; break; default: bug( "Makes_Save: Unknown Resistance." ); return TRUE; } if (ch != NULL) { chance += (victim->shdata->level - ch->shdata->level) / 5; chance -= 10*ch->get_skill( spell )/MAX_SKILL_LEVEL; } return (number_range( 0, 99 ) < chance); } /* * TABLE EVALUATE ROUTINES */ int spell_damage( int spell, int level, int var ) { int damage; bool error = FALSE; if( level < 0 ) level = (-level)%100; spell -= SPELL_FIRST; damage = evaluate( spell_table[spell].damage, error, level, var ); if( error ) bug( "Spell_Damage: Evaluate failed for %s.", spell_table[spell].name ); return damage; } int duration( int spell, int level, int var ) { int duration; bool error = FALSE; spell -= SPELL_FIRST; duration = evaluate( spell_table[spell].duration, error, level, var ); if( error ) bug( "Duration: Evaluate failed for %s.", spell_table[spell].name ); return duration; } int leech_regen( int spell, int level, int var ) { int regen; bool error = FALSE; spell -= SPELL_FIRST; regen = evaluate( spell_table[spell].regen, error, level, var ); if( error ) bug( "Leech_Regen: Evaluate failed for %s.", spell_table[spell].name ); return regen; } int leech_mana( int spell, int level, int var ) { int mana; bool error = FALSE; spell -= SPELL_FIRST; mana = evaluate( spell_table[spell].leech_mana, error, level, var ); if( error ) bug( "Leech_Mana: Evaluate failed for %s.", spell_table[spell].name ); return mana; } void spell_affect( char_data* ch, char_data* victim, int level, int time, int spell, int type, int var ) { if( !victim ) return; affect_data affect; affect.type = type; if( ch == NULL || time > 0 ) { affect.duration = time; affect.level = level; } else { affect.level = level; affect.duration = duration( spell, level, var ); if( spell_table[ spell-SPELL_FIRST ].regen != empty_string ) { affect.leech_regen = leech_regen( spell, level, var ); affect.leech_max = leech_mana( spell, level, var ); affect.leech = ch; } if( spell == SPELL_COMPANIONS_STRENGTH ) { affect.mlocation[ 0 ] = affect_loc[ victim->species->compan_str ]; affect.mmodifier[ 0 ] = victim->species->compan_amt; } } if( spell == SPELL_COMPANIONS_STRENGTH ) add_affect( ch, &affect ); else add_affect( victim, &affect ); return; }
25.928641
165
0.577644
[ "object", "3d" ]
7804da3c96626fb19e1b57471848475a36901093
4,274
cc
C++
src/webkit/compositor_bindings/web_layer_impl_fixed_bounds.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/webkit/compositor_bindings/web_layer_impl_fixed_bounds.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/webkit/compositor_bindings/web_layer_impl_fixed_bounds.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/compositor_bindings/web_layer_impl_fixed_bounds.h" #include "cc/layers/layer.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "third_party/skia/include/utils/SkMatrix44.h" using cc::Layer; namespace webkit { WebLayerImplFixedBounds::WebLayerImplFixedBounds() { } WebLayerImplFixedBounds::WebLayerImplFixedBounds(scoped_refptr<Layer> layer) : WebLayerImpl(layer) { } WebLayerImplFixedBounds::~WebLayerImplFixedBounds() { } void WebLayerImplFixedBounds::invalidateRect(const WebKit::WebFloatRect& rect) { // Partial invalidations seldom occur for such layers. // Simply invalidate the whole layer to avoid transformation of coordinates. invalidate(); } void WebLayerImplFixedBounds::setAnchorPoint( const WebKit::WebFloatPoint& anchor_point) { if (anchor_point != this->anchorPoint()) { layer_->SetAnchorPoint(anchor_point); UpdateLayerBoundsAndTransform(); } } void WebLayerImplFixedBounds::setBounds(const WebKit::WebSize& bounds) { if (original_bounds_ != gfx::Size(bounds)) { original_bounds_ = bounds; UpdateLayerBoundsAndTransform(); } } WebKit::WebSize WebLayerImplFixedBounds::bounds() const { return original_bounds_; } void WebLayerImplFixedBounds::setSublayerTransform(const SkMatrix44& matrix) { gfx::Transform transform; transform.matrix() = matrix; SetSublayerTransformInternal(transform); } SkMatrix44 WebLayerImplFixedBounds::sublayerTransform() const { return original_sublayer_transform_.matrix(); } void WebLayerImplFixedBounds::setTransform(const SkMatrix44& matrix) { gfx::Transform transform; transform.matrix() = matrix; SetTransformInternal(transform); } SkMatrix44 WebLayerImplFixedBounds::transform() const { return original_transform_.matrix(); } void WebLayerImplFixedBounds::SetFixedBounds(gfx::Size fixed_bounds) { if (fixed_bounds_ != fixed_bounds) { fixed_bounds_ = fixed_bounds; UpdateLayerBoundsAndTransform(); } } void WebLayerImplFixedBounds::SetSublayerTransformInternal( const gfx::Transform& transform) { if (original_sublayer_transform_ != transform) { original_sublayer_transform_ = transform; UpdateLayerBoundsAndTransform(); } } void WebLayerImplFixedBounds::SetTransformInternal( const gfx::Transform& transform) { if (original_transform_ != transform) { original_transform_ = transform; UpdateLayerBoundsAndTransform(); } } void WebLayerImplFixedBounds::UpdateLayerBoundsAndTransform() { if (fixed_bounds_.IsEmpty() || original_bounds_.IsEmpty() || fixed_bounds_ == original_bounds_ || // For now fall back to non-fixed bounds for non-zero anchor point. // TODO(wangxianzhu): Support non-zero anchor point for fixed bounds. anchorPoint().x || anchorPoint().y) { layer_->SetBounds(original_bounds_); layer_->SetTransform(original_transform_); layer_->SetSublayerTransform(original_sublayer_transform_); return; } layer_->SetBounds(fixed_bounds_); // Apply bounds scale (bounds/fixed_bounds) over original transform. gfx::Transform transform_with_bounds_scale(original_transform_); float bounds_scale_x = static_cast<float>(original_bounds_.width()) / fixed_bounds_.width(); float bounds_scale_y = static_cast<float>(original_bounds_.height()) / fixed_bounds_.height(); transform_with_bounds_scale.Scale(bounds_scale_x, bounds_scale_y); layer_->SetTransform(transform_with_bounds_scale); // As we apply extra scale transform on this layer which will propagate to the // sublayers, here undo the scale on sublayers. gfx::Transform sublayer_transform_with_inverse_bounds_scale; sublayer_transform_with_inverse_bounds_scale.Scale(1.f / bounds_scale_x, 1.f / bounds_scale_y); sublayer_transform_with_inverse_bounds_scale.PreconcatTransform( original_sublayer_transform_); layer_->SetSublayerTransform(sublayer_transform_with_inverse_bounds_scale); } } // namespace WebKit
33.131783
80
0.766495
[ "transform" ]
78072bafab9fd4f537470b717c8165ed52cc73cb
9,989
cpp
C++
jni/libjetbeep-jni/MFCApiProvider.cpp
jetbeep/libjetbeep-usb
4fc083dfec9873f435a460f8e3f43c582620d290
[ "MIT" ]
5
2019-11-29T04:43:32.000Z
2020-06-12T13:59:44.000Z
jni/libjetbeep-jni/MFCApiProvider.cpp
jetbeep/libjetbeep-usb
4fc083dfec9873f435a460f8e3f43c582620d290
[ "MIT" ]
null
null
null
jni/libjetbeep-jni/MFCApiProvider.cpp
jetbeep/libjetbeep-usb
4fc083dfec9873f435a460f8e3f43c582620d290
[ "MIT" ]
null
null
null
#include "../../lib/libjetbeep.hpp" #include "./include/com_jetbeep_nfc_mifare_classic_MFCApiProvider.h" #include "jni-utils.hpp" #include <future> using namespace std; using namespace JetBeep; using namespace JetBeep::NFC; using namespace JetBeep::NFC::MifareClassic; class MFCApiProviderJni { public: static Logger log; }; Logger MFCApiProviderJni::log = Logger("mfc_api_provider-jni"); static bool getMifareClassicProviderPointer(JNIEnv* env, jlong ptr, MifareClassicProvider** provider_p) { if (0 == ptr) { JniUtils::throwNullPointerException(env, "MifareClassicProvider pointer is null"); *provider_p = nullptr; return false; } *provider_p = static_cast<MifareClassicProvider*>((void*)ptr); return true; } JNIEXPORT void JNICALL Java_com_jetbeep_nfc_mifare_1classic_MFCApiProvider_saveObj(JNIEnv* env, jobject object, jlong ptr) { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); auto objGlobRef = env->NewGlobalRef(object); MifareClassicProvider * provider_p = nullptr; if (!getMifareClassicProviderPointer(env, ptr, &provider_p)) { MFCApiProviderJni::log.e() << "unable to getMifareClassicProviderPointer" << Logger::endl; return; } provider_p->opaque = objGlobRef; } JNIEXPORT void JNICALL Java_com_jetbeep_nfc_mifare_1classic_MFCApiProvider_free(JNIEnv* env, jobject object, jlong ptr) { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); MifareClassicProvider * provider_p = nullptr; if (!getMifareClassicProviderPointer(env, ptr, &provider_p)) { MFCApiProviderJni::log.e() << "unable to getMifareClassicProviderPointer" << Logger::endl; return; } auto ptrField = JniUtils::getPtrField(env, object, "MifareClassicProvider"); if (ptrField == nullptr) { MFCApiProviderJni::log.e() << "unable to get ptr field" << Logger::endl; return; } env->SetLongField(object, ptrField, 0); env->DeleteGlobalRef((jobject)(provider_p->opaque)); provider_p->opaque = nullptr; delete provider_p; } JNIEXPORT void JNICALL Java_com_jetbeep_nfc_mifare_1classic_MFCApiProvider_native_1readBlock(JNIEnv* env, jobject object, jlong ptr, jint jBlockNo, jobject jKey){ std::lock_guard<recursive_mutex> lock(JniUtils::mutex); MifareClassicProvider * provider_p = nullptr; if (!getMifareClassicProviderPointer(env, ptr, &provider_p)) { JniUtils::throwRuntimeException(env, "Unable to getMifareClassicProviderPointer"); return; } try { int blockNo = (int) jBlockNo; MifareBlockContent content = {}; MifareClassicKey key = {}; key.type = JetBeep::NFC::MifareClassic::MifareClassicKeyType::NONE; JniUtils::getMifareClassicKeyFromMFCKey(env, jKey, &key); string callBackName = "onReadResult"; string callSignature = "(Lcom/jetbeep/nfc/mifare_classic/MFCBlockData;Ljava/lang/Exception;)V"; provider_p->readBlock(blockNo,content, &key) .then([&, result = content, provider_p, callBackName, callSignature]() { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); auto env = JniUtils::attachCurrentThread(); if (env == nullptr) { MFCApiProviderJni::log.e() << "unable to get env" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jMFCProvider = (jobject) provider_p->opaque; if (jMFCProvider == nullptr) { MFCApiProviderJni::log.e() << "jMFCProvider == nullptr" << Logger::endl; return JniUtils::detachCurrentThread(); } auto jMFCProviderClass = env->GetObjectClass(jMFCProvider); if (jMFCProviderClass == nullptr) { MFCApiProviderJni::log.e() << "unable to env->GetObjectClass(jMFCProvider)" << Logger::endl; return JniUtils::detachCurrentThread(); } auto methodId = env->GetMethodID(jMFCProviderClass, callBackName.c_str(), callSignature.c_str()); if (methodId == nullptr) { MFCApiProviderJni::log.e() << "unable to find " << callBackName << " method" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jBlockContent = JniUtils::getMFCBlockDataFromMifareBlockContent(env, &result); env->CallVoidMethod(jMFCProvider, methodId, jBlockContent, nullptr); return JniUtils::detachCurrentThread(); }) .catchError([&, provider_p, callBackName, callSignature](const exception_ptr& ex) { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); auto env = JniUtils::attachCurrentThread(); if (env == nullptr) { MFCApiProviderJni::log.e() << "unable to get env" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jMFCProvider = (jobject) provider_p->opaque; if (jMFCProvider == nullptr) { MFCApiProviderJni::log.e() << "jMFCProvider == nullptr" << Logger::endl; return JniUtils::detachCurrentThread(); } auto jMFCProviderClass = env->GetObjectClass(jMFCProvider); if (jMFCProviderClass == nullptr) { MFCApiProviderJni::log.e() << "unable to env->GetObjectClass(jMFCProvider)" << Logger::endl; return JniUtils::detachCurrentThread(); } auto methodId = env->GetMethodID(jMFCProviderClass, callBackName.c_str(), callSignature.c_str()); if (methodId == nullptr) { MFCApiProviderJni::log.e() << "unable to find " << callBackName << " method" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jExceptionObj = JniUtils::createMFCOperationException(env, ex); env->CallVoidMethod(jMFCProvider, methodId, nullptr, jExceptionObj); return JniUtils::detachCurrentThread(); }); } catch (const Errors::InvalidState& ) { JniUtils::throwIllegalStateException(env, "invalid device state"); } catch (...) { MFCApiProviderJni::log.e() << "MFCApiProvider_native_1readBlock result in exception" << Logger::endl; JniUtils::throwIOException(env, "system error"); } } JNIEXPORT void JNICALL Java_com_jetbeep_nfc_mifare_1classic_MFCApiProvider_native_1writeBlock(JNIEnv* env, jobject object, jlong ptr, jobject blockData, jobject jKey){ std::lock_guard<recursive_mutex> lock(JniUtils::mutex); MifareClassicProvider * provider_p = nullptr; if (!getMifareClassicProviderPointer(env, ptr, &provider_p)) { JniUtils::throwRuntimeException(env, "Unable to getMifareClassicProviderPointer"); return; } string callBackName = "onWriteResult"; string callSignature = "(Ljava/lang/Exception;)V"; try { MifareBlockContent content = {}; content.blockNo = -1; MifareClassicKey key = {}; key.type = JetBeep::NFC::MifareClassic::MifareClassicKeyType::NONE; JniUtils::getMifareClassicKeyFromMFCKey(env, jKey, &key); JniUtils::getMifareBlockContentFromMFCBlockData(env, blockData, &content); provider_p->writeBlock(content, &key) .then([&, result = content, provider_p, callBackName, callSignature]() { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); auto env = JniUtils::attachCurrentThread(); if (env == nullptr) { MFCApiProviderJni::log.e() << "unable to get env" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jMFCProvider = (jobject) provider_p->opaque; if (jMFCProvider == nullptr) { MFCApiProviderJni::log.e() << "jMFCProvider == nullptr" << Logger::endl; return JniUtils::detachCurrentThread(); } auto jMFCProviderClass = env->GetObjectClass(jMFCProvider); if (jMFCProviderClass == nullptr) { MFCApiProviderJni::log.e() << "unable to env->GetObjectClass(jMFCProvider)" << Logger::endl; return JniUtils::detachCurrentThread(); } auto methodId = env->GetMethodID(jMFCProviderClass, callBackName.c_str(), callSignature.c_str()); if (methodId == nullptr) { MFCApiProviderJni::log.e() << "unable to find " << callBackName << " method" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jBlockContent = JniUtils::getMFCBlockDataFromMifareBlockContent(env, &result); env->CallVoidMethod(jMFCProvider, methodId, nullptr); return JniUtils::detachCurrentThread(); }) .catchError([&, provider_p, callBackName, callSignature](const exception_ptr& ex) { std::lock_guard<recursive_mutex> lock(JniUtils::mutex); auto env = JniUtils::attachCurrentThread(); if (env == nullptr) { MFCApiProviderJni::log.e() << "unable to get env" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jMFCProvider = (jobject) provider_p->opaque; if (jMFCProvider == nullptr) { MFCApiProviderJni::log.e() << "jMFCProvider == nullptr" << Logger::endl; return JniUtils::detachCurrentThread(); } auto jMFCProviderClass = env->GetObjectClass(jMFCProvider); if (jMFCProviderClass == nullptr) { MFCApiProviderJni::log.e() << "unable to env->GetObjectClass(jMFCProvider)" << Logger::endl; return JniUtils::detachCurrentThread(); } auto methodId = env->GetMethodID(jMFCProviderClass, callBackName.c_str(), callSignature.c_str()); if (methodId == nullptr) { MFCApiProviderJni::log.e() << "unable to find " << callBackName << " method" << Logger::endl; return JniUtils::detachCurrentThread();; } auto jExceptionObj = JniUtils::createMFCOperationException(env, ex); env->CallVoidMethod(jMFCProvider, methodId, jExceptionObj); return JniUtils::detachCurrentThread(); }); return; } catch (const Errors::InvalidState& ) { JniUtils::throwIllegalStateException(env, "invalid device state"); } catch (...) { MFCApiProviderJni::log.e() << "MFCApiProvider_native_1writeBlock result in exception" << Logger::endl; JniUtils::throwIOException(env, "system error"); } }
43.811404
167
0.680949
[ "object" ]
780852c57b29a0e04a4c190289938b68a619f011
1,913
cxx
C++
Plugins/PrismPlugins/Server/vtkSMPrismDoubleRangeDomain.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Plugins/PrismPlugins/Server/vtkSMPrismDoubleRangeDomain.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Plugins/PrismPlugins/Server/vtkSMPrismDoubleRangeDomain.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
#include "vtkSMPrismDoubleRangeDomain.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkObjectFactory.h" #include <vtkstd/vector> vtkStandardNewMacro(vtkSMPrismDoubleRangeDomain); vtkCxxRevisionMacro(vtkSMPrismDoubleRangeDomain, "$Revision$"); struct vtkSMPrismDoubleRangeDomainInternals { double Min; double Max; }; //--------------------------------------------------------------------------- vtkSMPrismDoubleRangeDomain::vtkSMPrismDoubleRangeDomain() { this->DRInternals = new vtkSMPrismDoubleRangeDomainInternals; } //--------------------------------------------------------------------------- vtkSMPrismDoubleRangeDomain::~vtkSMPrismDoubleRangeDomain() { delete this->DRInternals; } //--------------------------------------------------------------------------- void vtkSMPrismDoubleRangeDomain::Update(vtkSMProperty* prop) { vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast(prop); if (!dvp) { return; } if(dvp->GetNumberOfElements()>=2) { this->DRInternals->Min=dvp->GetElement(0); this->DRInternals->Max=dvp->GetElement(1); } } //--------------------------------------------------------------------------- int vtkSMPrismDoubleRangeDomain::SetDefaultValues(vtkSMProperty* prop) { vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast(prop); if (!dvp) { vtkErrorMacro( "vtkSMPrismDoubleRangeDomain only works with vtkSMDoubleVectorProperty."); return 0; } dvp->SetElements2(this->DRInternals->Min,this->DRInternals->Max); return 1; } //--------------------------------------------------------------------------- void vtkSMPrismDoubleRangeDomain::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
26.943662
86
0.549922
[ "vector" ]
7808ef4a98531cc2bffbae6aee4c1c311c4d7866
17,797
cpp
C++
src/Application/SceneWidgetComponents/EC_WidgetCanvas.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
src/Application/SceneWidgetComponents/EC_WidgetCanvas.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
src/Application/SceneWidgetComponents/EC_WidgetCanvas.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
// For conditions of distribution and use, see copyright notice in LICENSE #include "Math/MathNamespace.h" #include "DebugOperatorNew.h" #include "EC_WidgetCanvas.h" #include "Framework.h" #include "IRenderer.h" #include "Entity.h" #include "LoggingFunctions.h" #include "OgreMaterialUtils.h" #include "EC_Mesh.h" #include "EC_OgreCustomObject.h" #include <OgreTextureManager.h> #include <OgreMaterialManager.h> #include <OgreHardwarePixelBuffer.h> #include <OgreTechnique.h> #include <QTimer> #include <QWidget> #include <QPainter> #include <QDebug> #if defined(DIRECTX_ENABLED) && defined(WIN32) #ifdef SAFE_DELETE #undef SAFE_DELETE #endif #ifdef SAFE_DELETE_ARRAY #undef SAFE_DELETE_ARRAY #endif #include <d3d9.h> #include <OgreD3D9RenderSystem.h> #include <OgreD3D9HardwarePixelBuffer.h> #endif #include "MemoryLeakCheck.h" EC_WidgetCanvas::EC_WidgetCanvas(Scene *scene) : IComponent(scene), widget_(0), update_internals_(false), mesh_hooked_(false), refresh_timer_(0), update_interval_msec_(0), material_name_(""), texture_name_("") { connect(this, SIGNAL(ParentEntitySet()), SLOT(Initialize())); connect(this, SIGNAL(ParentEntitySet()), SLOT(OnParentEntitySet())); } EC_WidgetCanvas::~EC_WidgetCanvas() { submeshes_.clear(); widget_ = 0; if (refresh_timer_) refresh_timer_->stop(); SAFE_DELETE(refresh_timer_); if (!material_name_.empty()) { try { Ogre::MaterialManager::getSingleton().remove(material_name_); } catch (...) {} } if (!texture_name_.empty()) { try { Ogre::TextureManager::getSingleton().remove(texture_name_); } catch (...) {} } } void EC_WidgetCanvas::Start() { if (framework->IsHeadless()) return; update_internals_ = true; if (update_interval_msec_ != 0 && refresh_timer_) { if (refresh_timer_->isActive()) refresh_timer_->stop(); refresh_timer_->start(update_interval_msec_); } else Update(); if(!mesh_hooked_) { Entity* entity = ParentEntity(); EC_Mesh* ec_mesh = entity->GetComponent<EC_Mesh>().get(); if (ec_mesh) { connect(ec_mesh, SIGNAL(MaterialChanged(uint, const QString)), SLOT(MeshMaterialsUpdated(uint, const QString))); mesh_hooked_ = true; } } } void EC_WidgetCanvas::MeshMaterialsUpdated(uint index, const QString &material_name) { if (framework->IsHeadless()) return; if (material_name_.empty()) return; if(material_name.compare(QString(material_name_.c_str())) != 0 ) { bool has_index = false; for (int i=0; i<submeshes_.length(); i++) { if (index == submeshes_[i]) has_index = true; } if(has_index) UpdateSubmeshes(); } } void EC_WidgetCanvas::Stop() { if (framework->IsHeadless()) return; if (refresh_timer_) if (refresh_timer_->isActive()) refresh_timer_->stop(); } void EC_WidgetCanvas::Setup(QWidget *widget, const QList<uint> &submeshes, int refresh_per_second) { if (framework->IsHeadless()) return; SetWidget(widget); SetSubmeshes(submeshes); SetRefreshRate(refresh_per_second); } void EC_WidgetCanvas::SetWidget(QWidget *widget) { if (framework->IsHeadless()) return; if (widget_ != widget) { widget_ = widget; if (widget_) connect(widget_, SIGNAL(destroyed(QObject*)), SLOT(WidgetDestroyed(QObject *)), Qt::UniqueConnection); } } void EC_WidgetCanvas::SetRefreshRate(int refresh_per_second) { if (framework->IsHeadless()) return; if (refresh_per_second < 0) refresh_per_second = 0; bool was_running = false; if (refresh_timer_) was_running = refresh_timer_->isActive(); SAFE_DELETE(refresh_timer_); if (refresh_per_second != 0) { refresh_timer_ = new QTimer(this); connect(refresh_timer_, SIGNAL(timeout()), SLOT(Update()), Qt::UniqueConnection); int temp_msec = 1000 / refresh_per_second; if (update_interval_msec_ != temp_msec && was_running) refresh_timer_->start(temp_msec); update_interval_msec_ = temp_msec; } else update_interval_msec_ = 0; } void EC_WidgetCanvas::SetSubmesh(uint submesh) { if (framework->IsHeadless()) return; submeshes_.clear(); submeshes_.append(submesh); update_internals_ = true; UpdateSubmeshes(); } void EC_WidgetCanvas::SetSubmeshes(const QList<uint> &submeshes) { if (framework->IsHeadless()) return; submeshes_.clear(); submeshes_ = submeshes; update_internals_ = true; UpdateSubmeshes(); } void EC_WidgetCanvas::WidgetDestroyed(QObject *obj) { if (framework->IsHeadless()) return; widget_ = 0; Stop(); RestoreOriginalMeshMaterials(); SAFE_DELETE(refresh_timer_); } void EC_WidgetCanvas::Update(QImage buffer) { if (framework->IsHeadless()) return; if (buffer.width() <= 0 || buffer.height() <= 0) return; if (buffer.format() != QImage::Format_ARGB32 && buffer.format() != QImage::Format_ARGB32_Premultiplied) { LogWarning("EC_WidgetCanvas::Update(QImage buffer): Input format needs to be Format_ARGB32 or Format_ARGB32_Premultiplied, preforming auto conversion!"); buffer = buffer.convertToFormat(QImage::Format_ARGB32); if (buffer.isNull()) { LogError("-- Auto conversion failed, not updating!"); return; } } try { Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(texture_name_); if (texture.isNull()) return; // Set texture to material if need be if (update_internals_ && !material_name_.empty()) { Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(material_name_); if (material.isNull()) return; // Just for good measure, this is done once in the ctor already if everything went well. OgreRenderer::SetTextureUnitOnMaterial(material, texture_name_); UpdateSubmeshes(); update_internals_ = false; } if ((int)texture->getWidth() != buffer.width() || (int)texture->getHeight() != buffer.height()) { texture->freeInternalResources(); texture->setWidth(buffer.width()); texture->setHeight(buffer.height()); texture->createInternalResources(); } Blit(buffer, texture); } catch (Ogre::Exception &e) // inherits std::exception { LogError("Exception occurred while blitting texture data from memory: " + std::string(e.what())); } catch (...) { LogError("Unknown exception occurred while blitting texture data from memory."); } } void EC_WidgetCanvas::Update() { if (framework->IsHeadless()) return; if (!widget_.data() || texture_name_.empty()) return; if (widget_->width() <= 0 || widget_->height() <= 0) return; try { Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(texture_name_); if (texture.isNull()) return; if (buffer_.size() != widget_->size()) buffer_ = QImage(widget_->size(), QImage::Format_ARGB32_Premultiplied); if (buffer_.width() <= 0 || buffer_.height() <= 0) return; QPainter painter(&buffer_); widget_->render(&painter); // Set texture to material if (update_internals_ && !material_name_.empty()) { Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(material_name_); if (material.isNull()) return; // Just for good measure, this is done once in the ctor already if everything went well. OgreRenderer::SetTextureUnitOnMaterial(material, texture_name_); UpdateSubmeshes(); update_internals_ = false; } if ((int)texture->getWidth() != buffer_.width() || (int)texture->getHeight() != buffer_.height()) { texture->freeInternalResources(); texture->setWidth(buffer_.width()); texture->setHeight(buffer_.height()); texture->createInternalResources(); } Blit(buffer_, texture); } catch (Ogre::Exception &e) // inherits std::exception { LogError("Exception occurred while blitting texture data from memory: " + std::string(e.what())); } catch (...) { LogError("Unknown exception occurred while blitting texture data from memory."); } } void EC_WidgetCanvas::Initialize() { if (framework->IsHeadless()) return; if (framework->Renderer()) { // Create texture texture_name_ = framework->Renderer()->GetUniqueObjectName("EC_3DCanvas_tex"); Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( texture_name_, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); if (texture.isNull()) { LogError("EC_WidgetCanvas: Could not create texture for usage!"); return; } // Create material: Make sure we have one tech with one pass with one texture unit. // Don't use our lit textured templates here as emissive will not work there as it has vertex etc programs in it. material_name_ = framework->Renderer()->GetUniqueObjectName("EC_3DCanvas_mat"); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(material_name_, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (material->getNumTechniques() == 0) material->createTechnique(); if (material->getTechnique(0) && material->getTechnique(0)->getNumPasses() == 0) material->getTechnique(0)->createPass(); if (material->getTechnique(0)->getPass(0) && material->getTechnique(0)->getPass(0)->getNumTextureUnitStates() == 0) material->getTechnique(0)->getPass(0)->createTextureUnitState(texture_name_); } } bool EC_WidgetCanvas::Blit(const QImage &source, Ogre::TexturePtr destination) { #if defined(DIRECTX_ENABLED) && defined(WIN32) Ogre::HardwarePixelBufferSharedPtr pb = destination->getBuffer(); Ogre::D3D9HardwarePixelBuffer *pixelBuffer = dynamic_cast<Ogre::D3D9HardwarePixelBuffer*>(pb.get()); if (!pixelBuffer) return false; LPDIRECT3DSURFACE9 surface = pixelBuffer->getSurface(Ogre::D3D9RenderSystem::getActiveD3D9Device()); if (surface) { D3DSURFACE_DESC desc; HRESULT hr = surface->GetDesc(&desc); if (SUCCEEDED(hr)) { D3DLOCKED_RECT lock; HRESULT hr = surface->LockRect(&lock, 0, 0); if (SUCCEEDED(hr)) { const int bytesPerPixel = 4; ///\todo Count from Ogre::PixelFormat! const int sourceStride = bytesPerPixel * source.width(); if (lock.Pitch == sourceStride) memcpy(lock.pBits, source.bits(), sourceStride * source.height()); else for(int y = 0; y < source.height(); ++y) memcpy((u8*)lock.pBits + lock.Pitch * y, source.bits() + sourceStride * y, sourceStride); surface->UnlockRect(); } } } #else if (!destination->getBuffer().isNull()) { Ogre::Box update_box(0, 0, source.width(), source.height()); Ogre::PixelBox pixel_box(update_box, Ogre::PF_A8R8G8B8, (void*)source.bits()); destination->getBuffer()->blitFromMemory(pixel_box, update_box); } #endif return true; } void EC_WidgetCanvas::UpdateSubmeshes() { if (framework->IsHeadless()) return; Entity* entity = ParentEntity(); if (material_name_.empty() || !entity) return; uint submesh_count = 0; EC_Mesh* ec_mesh = entity->GetComponent<EC_Mesh>().get(); EC_OgreCustomObject* ec_custom_object = entity->GetComponent<EC_OgreCustomObject>().get(); if (ec_mesh) submesh_count = ec_mesh->GetNumMaterials(); else if (ec_custom_object) submesh_count = ec_custom_object->GetNumMaterials(); else { ///\todo Log out error - entity doesn't contain either a EC_Mesh or EC_OgreCustomObject! return; } // Iterate trough sub meshes for(uint index = 0; index < submesh_count; ++index) { // Store original materials std::string submesh_material_name; if (ec_mesh) submesh_material_name = ec_mesh->GetMaterialName(index); else submesh_material_name = ec_custom_object->GetMaterialName(index); if (submesh_material_name != material_name_) restore_materials_[index] = submesh_material_name; if (submeshes_.contains(index)) { if (ec_mesh) ec_mesh->SetMaterial(index, QString::fromStdString(material_name_)); else ec_custom_object->SetMaterial(index, material_name_); } else { // If submesh not contained, restore the original material if (ec_mesh) { if (ec_mesh->GetMaterialName(index) == material_name_) if (restore_materials_.contains(index)) ec_mesh->SetMaterial(index, QString::fromStdString(restore_materials_[index])); } else { if (ec_custom_object->GetMaterialName(index) == material_name_) if (restore_materials_.contains(index)) ec_custom_object->SetMaterial(index, restore_materials_[index]); } } } } void EC_WidgetCanvas::RestoreOriginalMeshMaterials() { if (framework->IsHeadless()) return; if (restore_materials_.empty()) { update_internals_ = true; return; } Entity* entity = ParentEntity(); if (material_name_.empty() || !entity) return; uint submesh_count = 0; EC_Mesh* ec_mesh = entity->GetComponent<EC_Mesh>().get(); EC_OgreCustomObject* ec_custom_object = entity->GetComponent<EC_OgreCustomObject>().get(); if (ec_mesh) submesh_count = ec_mesh->GetNumMaterials(); else if (ec_custom_object) submesh_count = ec_custom_object->GetNumMaterials(); else { ///\todo Log out error - entity doesn't contain either a EC_Mesh or EC_OgreCustomObject! return; } // Iterate trough sub meshes for(uint index = 0; index < submesh_count; ++index) { // If submesh not contained, restore the original material if (ec_mesh) { if (ec_mesh->GetMaterialName(index) == material_name_) if (restore_materials_.contains(index)) ec_mesh->SetMaterial(index, QString::fromStdString(restore_materials_[index])); } else { if (ec_custom_object->GetMaterialName(index) == material_name_) if (restore_materials_.contains(index)) ec_custom_object->SetMaterial(index, restore_materials_[index]); } } restore_materials_.clear(); update_internals_ = true; } void EC_WidgetCanvas::OnParentEntitySet() { if (framework->IsHeadless()) return; // Warn users if they are creating this component with sync enabled. /// \todo Maybe this component should not be a component anymore as components can no longer be non-serializable. Maybe these rendering operations should be moved to some util code inside SceneWidgetComponents. if (IsReplicated()) LogWarning("EC_WidgetCanvas: My network sync seems to be enabled, this is not advisable in most situations! I don't have any attributes and am intended for local rendering operations."); if (ParentEntity()) connect(ParentEntity(), SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(ComponentRemoved(IComponent*, AttributeChange::Type)), Qt::UniqueConnection); } void EC_WidgetCanvas::ComponentRemoved(IComponent *component, AttributeChange::Type change) { if (framework->IsHeadless()) return; if (component == this) { Stop(); RestoreOriginalMeshMaterials(); SetWidget(0); submeshes_.clear(); } } void EC_WidgetCanvas::SetSelfIllumination(bool illuminating) { if (material_name_.empty()) return; Ogre::ColourValue emissiveColor; if (illuminating) emissiveColor = Ogre::ColourValue(1.0f, 1.0f, 1.0f, 1.0f); else emissiveColor = Ogre::ColourValue(0.0f, 0.0f, 0.0f, 0.0f); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(material_name_); if (!material.isNull()) { Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator(); while(iter.hasMoreElements()) { Ogre::Technique *tech = iter.getNext(); if (!tech) continue; Ogre::Technique::PassIterator passIter = tech->getPassIterator(); while(passIter.hasMoreElements()) { Ogre::Pass *pass = passIter.getNext(); if (pass) pass->setSelfIllumination(emissiveColor); } } } }
30.474315
214
0.622464
[ "render" ]
780db85a5be789043e92ad50ae1dea982d84fe7c
5,233
hpp
C++
3party/boost/boost/geometry/extensions/gis/projections/impl/pj_ellps.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
2
2015-01-02T14:24:56.000Z
2015-01-02T14:25:17.000Z
3party/boost/boost/geometry/extensions/gis/projections/impl/pj_ellps.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
2
2019-01-13T23:45:51.000Z
2019-02-03T08:13:26.000Z
3party/boost/boost/geometry/extensions/gis/projections/impl/pj_ellps.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
2
2018-04-04T10:55:01.000Z
2020-04-23T18:52:06.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // This file is manually converted from PROJ4 // Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by Gerald Evenden (then of the USGS) // PROJ4 is maintained by Frank Warmerdam // PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam) // Original copyright notice: // 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 BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELLPS_HPP #define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELLPS_HPP #include <boost/geometry/extensions/gis/projections/impl/projects.hpp> namespace boost { namespace geometry { namespace projections { namespace detail { static const PJ_ELLPS pj_ellps[] = { { "MERIT", "a=6378137.0", "rf=298.257", "MERIT 1983" }, { "SGS85", "a=6378136.0", "rf=298.257", "Soviet Geodetic System 85" }, { "GRS80", "a=6378137.0", "rf=298.257222101", "GRS 1980(IUGG, 1980)" }, { "IAU76", "a=6378140.0", "rf=298.257", "IAU 1976" }, { "airy", "a=6377563.396", "b=6356256.910", "Airy 1830" }, { "APL4.9", "a=6378137.0.", "rf=298.25", "Appl. Physics. 1965" }, { "NWL9D", "a=6378145.0.", "rf=298.25", "Naval Weapons Lab., 1965" }, { "mod_airy", "a=6377340.189", "b=6356034.446", "Modified Airy" }, { "andrae", "a=6377104.43", "rf=300.0", "Andrae 1876 (Den., Iclnd.)" }, { "aust_SA", "a=6378160.0", "rf=298.25", "Australian Natl & S. Amer. 1969" }, { "GRS67", "a=6378160.0", "rf=298.2471674270", "GRS 67(IUGG 1967)" }, { "bessel", "a=6377397.155", "rf=299.1528128", "Bessel 1841" }, { "bess_nam", "a=6377483.865", "rf=299.1528128", "Bessel 1841 (Namibia)" }, { "clrk66", "a=6378206.4", "b=6356583.8", "Clarke 1866" }, { "clrk80", "a=6378249.145", "rf=293.4663", "Clarke 1880 mod." }, { "CPM", "a=6375738.7", "rf=334.29", "Comm. des Poids et Mesures 1799" }, { "delmbr", "a=6376428.", "rf=311.5", "Delambre 1810 (Belgium)" }, { "engelis", "a=6378136.05", "rf=298.2566", "Engelis 1985" }, { "evrst30", "a=6377276.345", "rf=300.8017", "Everest 1830" }, { "evrst48", "a=6377304.063", "rf=300.8017", "Everest 1948" }, { "evrst56", "a=6377301.243", "rf=300.8017", "Everest 1956" }, { "evrst69", "a=6377295.664", "rf=300.8017", "Everest 1969" }, { "evrstSS", "a=6377298.556", "rf=300.8017", "Everest (Sabah & Sarawak)" }, { "fschr60", "a=6378166.", "rf=298.3", "Fischer (Mercury Datum) 1960" }, { "fschr60m", "a=6378155.", "rf=298.3", "Modified Fischer 1960" }, { "fschr68", "a=6378150.", "rf=298.3", "Fischer 1968" }, { "helmert", "a=6378200.", "rf=298.3", "Helmert 1906" }, { "hough", "a=6378270.0", "rf=297.", "Hough" }, { "intl", "a=6378388.0", "rf=297.", "International 1909 (Hayford)" }, { "krass", "a=6378245.0", "rf=298.3", "Krassovsky, 1942" }, { "kaula", "a=6378163.", "rf=298.24", "Kaula 1961" }, { "lerch", "a=6378139.", "rf=298.257", "Lerch 1979" }, { "mprts", "a=6397300.", "rf=191.", "Maupertius 1738" }, { "new_intl", "a=6378157.5", "b=6356772.2","New International 1967" }, { "plessis", "a=6376523.", "b=6355863.", "Plessis 1817 (France)" }, { "SEasia", "a=6378155.0", "b=6356773.3205", "Southeast Asia" }, { "walbeck", "a=6376896.0", "b=6355834.8467", "Walbeck" }, { "WGS60", "a=6378165.0", "rf=298.3", "WGS 60" }, { "WGS66", "a=6378145.0", "rf=298.25", "WGS 66" }, { "WGS72", "a=6378135.0", "rf=298.26", "WGS 72" }, { "WGS84", "a=6378137.0", "rf=298.257223563", "WGS 84" }, { "sphere", "a=6370997.0", "b=6370997.0", "Normal Sphere (r=6370997)" } }; } // namespace detail }}} // namespace boost::geometry::projections #endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELLPS_HPP
55.670213
92
0.616855
[ "geometry" ]
78112ef07e006ac1d3b54f086670a2afbced4e08
7,115
cpp
C++
wxWidgets-3.1.0/src/osx/uiaction_osx.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
2
2016-10-15T05:12:16.000Z
2016-11-06T16:19:53.000Z
wxWidgets-3.1.0/src/osx/uiaction_osx.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
14
2016-09-21T21:24:46.000Z
2016-11-15T07:54:21.000Z
wxWidgets-3.1.0/src/osx/uiaction_osx.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/osx/uiaction_osx.cpp // Purpose: wxUIActionSimulator implementation // Author: Kevin Ollivier, Steven Lamerton, Vadim Zeitlin // Modified by: // Created: 2010-03-06 // Copyright: (c) Kevin Ollivier // (c) 2010 Steven Lamerton // (c) 2010 Vadim Zeitlin // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/object.h" #endif #if wxUSE_UIACTIONSIMULATOR #include "wx/uiaction.h" #include "wx/log.h" #include "wx/osx/private.h" #include "wx/osx/core/cfref.h" #include "wx/evtloop.h" namespace { CGEventTapLocation tap = kCGSessionEventTap; CGEventType CGEventTypeForMouseButton(int button, bool isDown) { switch ( button ) { case wxMOUSE_BTN_LEFT: return isDown ? kCGEventLeftMouseDown : kCGEventLeftMouseUp; case wxMOUSE_BTN_RIGHT: return isDown ? kCGEventRightMouseDown : kCGEventRightMouseUp; // All the other buttons use the constant OtherMouseDown but we still // want to check for invalid parameters so assert first default: wxFAIL_MSG("Unsupported button passed in."); wxFALLTHROUGH;// fall back to the only known remaining case case wxMOUSE_BTN_MIDDLE: return isDown ? kCGEventOtherMouseDown : kCGEventOtherMouseUp; } } CGEventType CGEventTypeForMouseDrag(int button) { switch ( button ) { case wxMOUSE_BTN_LEFT: return kCGEventLeftMouseDragged; break; case wxMOUSE_BTN_RIGHT: return kCGEventRightMouseDragged; break; // All the other buttons use the constant OtherMouseDown but we still // want to check for invalid parameters so assert first default: wxFAIL_MSG("Unsupported button passed in."); wxFALLTHROUGH;// fall back to the only known remaining case case wxMOUSE_BTN_MIDDLE: return kCGEventOtherMouseDragged; break; } } CGMouseButton CGButtonForMouseButton(int button) { switch ( button ) { case wxMOUSE_BTN_LEFT: return kCGMouseButtonLeft; case wxMOUSE_BTN_RIGHT: return kCGMouseButtonRight; // All the other buttons use the constant OtherMouseDown but we still // want to check for invalid parameters so assert first default: wxFAIL_MSG("Unsupported button passed in."); wxFALLTHROUGH;// fall back to the only known remaining case case wxMOUSE_BTN_MIDDLE: return kCGMouseButtonCenter; } } CGPoint GetMousePosition() { int x, y; wxGetMousePosition(&x, &y); CGPoint pos; pos.x = x; pos.y = y; return pos; } } // anonymous namespace bool wxUIActionSimulator::MouseDown(int button) { CGEventType type = CGEventTypeForMouseButton(button, true); wxCFRef<CGEventRef> event( CGEventCreateMouseEvent(NULL, type, GetMousePosition(), CGButtonForMouseButton(button))); if ( !event ) return false; CGEventSetType(event, type); CGEventPost(tap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } bool wxUIActionSimulator::MouseMove(long x, long y) { CGPoint pos; pos.x = x; pos.y = y; CGEventType type = kCGEventMouseMoved; wxCFRef<CGEventRef> event( CGEventCreateMouseEvent(NULL, type, pos, kCGMouseButtonLeft)); if ( !event ) return false; CGEventSetType(event, type); CGEventPost(tap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } bool wxUIActionSimulator::MouseUp(int button) { CGEventType type = CGEventTypeForMouseButton(button, false); wxCFRef<CGEventRef> event( CGEventCreateMouseEvent(NULL, type, GetMousePosition(), CGButtonForMouseButton(button))); if ( !event ) return false; CGEventSetType(event, type); CGEventPost(tap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } bool wxUIActionSimulator::MouseDblClick(int button) { CGEventType downtype = CGEventTypeForMouseButton(button, true); CGEventType uptype = CGEventTypeForMouseButton(button, false); wxCFRef<CGEventRef> event( CGEventCreateMouseEvent(NULL, downtype, GetMousePosition(), CGButtonForMouseButton(button))); if ( !event ) return false; CGEventSetType(event,downtype); CGEventPost(tap, event); CGEventSetType(event, uptype); CGEventPost(tap, event); CGEventSetIntegerValueField(event, kCGMouseEventClickState, 2); CGEventSetType(event, downtype); CGEventPost(tap, event); CGEventSetType(event, uptype); CGEventPost(tap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } bool wxUIActionSimulator::MouseDragDrop(long x1, long y1, long x2, long y2, int button) { CGPoint pos1,pos2; pos1.x = x1; pos1.y = y1; pos2.x = x2; pos2.y = y2; CGEventType downtype = CGEventTypeForMouseButton(button, true); CGEventType uptype = CGEventTypeForMouseButton(button, false); CGEventType dragtype = CGEventTypeForMouseDrag(button) ; wxCFRef<CGEventRef> event( CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, pos1, CGButtonForMouseButton(button))); if ( !event ) return false; CGEventSetType(event,kCGEventMouseMoved); CGEventPost(tap, event); CGEventSetType(event,downtype); CGEventPost(tap, event); CGEventSetType(event, dragtype); CGEventSetLocation(event,pos2); CGEventPost(tap, event); CGEventSetType(event, uptype); CGEventPost(tap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } bool wxUIActionSimulator::DoKey(int keycode, int WXUNUSED(modifiers), bool isDown) { CGKeyCode cgcode = wxCharCodeWXToOSX((wxKeyCode)keycode); wxCFRef<CGEventRef> event(CGEventCreateKeyboardEvent(NULL, cgcode, isDown)); if ( !event ) return false; CGEventPost(kCGHIDEventTap, event); wxCFEventLoop* loop = dynamic_cast<wxCFEventLoop*>(wxEventLoop::GetActive()); if (loop) loop->SetShouldWaitForEvent(true); return true; } #endif // wxUSE_UIACTIONSIMULATOR
27.053232
123
0.637948
[ "object" ]
781b3a3fe4f18a9c40a271d9d4c903a5e4aa4dbb
3,037
cpp
C++
third_party/WebKit/Source/core/paint/PaintInfoTest.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/paint/PaintInfoTest.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/paint/PaintInfoTest.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/paint/PaintInfo.h" #include "platform/graphics/paint/PaintController.h" #include "testing/gtest/include/gtest/gtest.h" #include <memory> namespace blink { class PaintInfoTest : public testing::Test { protected: PaintInfoTest() : m_paintController(PaintController::create()) , m_context(*m_paintController) { } std::unique_ptr<PaintController> m_paintController; GraphicsContext m_context; }; TEST_F(PaintInfoTest, intersectsCullRect) { PaintInfo paintInfo(m_context, IntRect(0, 0, 50, 50), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); EXPECT_TRUE(paintInfo.cullRect().intersectsCullRect(IntRect(0, 0, 1, 1))); EXPECT_FALSE(paintInfo.cullRect().intersectsCullRect(IntRect(51, 51, 1, 1))); } TEST_F(PaintInfoTest, intersectsCullRectWithLayoutRect) { PaintInfo paintInfo(m_context, IntRect(0, 0, 50, 50), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); EXPECT_TRUE(paintInfo.cullRect().intersectsCullRect(LayoutRect(0, 0, 1, 1))); EXPECT_TRUE(paintInfo.cullRect().intersectsCullRect(LayoutRect(LayoutUnit(0.1), LayoutUnit(0.1), LayoutUnit(0.1), LayoutUnit(0.1)))); } TEST_F(PaintInfoTest, intersectsCullRectWithTransform) { PaintInfo paintInfo(m_context, IntRect(0, 0, 50, 50), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); AffineTransform transform; transform.translate(-2, -2); EXPECT_TRUE(paintInfo.cullRect().intersectsCullRect(transform, IntRect(51, 51, 1, 1))); EXPECT_FALSE(paintInfo.cullRect().intersectsCullRect(IntRect(52, 52, 1, 1))); } TEST_F(PaintInfoTest, updateCullRect) { PaintInfo paintInfo(m_context, IntRect(1, 1, 50, 50), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); AffineTransform transform; transform.translate(1, 1); paintInfo.updateCullRect(transform); EXPECT_TRUE(paintInfo.cullRect().intersectsCullRect(IntRect(0, 0, 1, 1))); EXPECT_FALSE(paintInfo.cullRect().intersectsCullRect(IntRect(51, 51, 1, 1))); } TEST_F(PaintInfoTest, intersectsVerticalRange) { PaintInfo paintInfo(m_context, IntRect(0, 0, 50, 100), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); EXPECT_TRUE(paintInfo.cullRect().intersectsVerticalRange(LayoutUnit(), LayoutUnit(1))); EXPECT_FALSE(paintInfo.cullRect().intersectsVerticalRange(LayoutUnit(100), LayoutUnit(101))); } TEST_F(PaintInfoTest, intersectsHorizontalRange) { PaintInfo paintInfo(m_context, IntRect(0, 0, 50, 100), PaintPhaseSelfBlockBackgroundOnly, GlobalPaintNormalPhase, PaintLayerNoFlag); EXPECT_TRUE(paintInfo.cullRect().intersectsHorizontalRange(LayoutUnit(), LayoutUnit(1))); EXPECT_FALSE(paintInfo.cullRect().intersectsHorizontalRange(LayoutUnit(50), LayoutUnit(51))); } } // namespace blink
38.935897
137
0.76918
[ "transform" ]
781c7ed68d6566a305c954fc2cb061ec91a3589a
1,944
cpp
C++
solved-lightOj/1082.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2020-07-02T00:08:02.000Z
2020-07-02T00:08:02.000Z
solved-lightOj/1082.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-lightOj/1082.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @School : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<fstream> #include<string> #include<vector> #include<queue> #include<map> #include<algorithm> #include<set> #include<sstream> #include<stack> using namespace std; #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(),x.end() #define mem(a,b) memset(a,b,sizeof(a)) #define inf 1e9 #define eps 1e-9 #define NN 1050 int parent[100010]; int tree[300010]; void makeTree(int node,int low,int high) { if(low==high) { tree[node]=parent[low]; return; } int left=node*2; int right=left+1; int mid=(low+high)/2; makeTree(left,low,mid); makeTree(right,mid+1,high); tree[node]=min(tree[right],tree[left]); return; } int minValue(int node, int low,int high, int rlow, int rhigh) { if(low>=rlow && high<=rhigh) return tree[node]; int left=node*2; int right=left+1; int mid=(low+high)/2; if(rhigh<=mid) return minValue(left,low,mid,rlow,rhigh); else if(rlow>mid) return minValue(right,mid+1,high,rlow,rhigh); else { left=minValue(left,low,mid,rlow,rhigh); right=minValue(right,mid+1,high,rlow,rhigh); return min(left,right); } } main() { ios_base::sync_with_stdio(false); int tc,i,t; cin>>tc; for(t=1; t<=tc; t++) { int n,q; cin>>n>>q; for(int i=1; i<=n; i++) cin>>parent[i]; makeTree(1,1,n); printf("Case %d:\n",t); while(q--) { int i,j; cin>>i>>j; int k=minValue(1,1,n,i,j); printf("%d\n",k); } } return 0; }
19.836735
61
0.564815
[ "vector" ]
781e6c2d240b3375baa9616b82ef5f4c2bb6b9c7
3,030
cxx
C++
Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2015-06-19T07:18:36.000Z
2019-04-18T07:28:23.000Z
Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx
151706061/ITK
6c073453ff8bdae9b1392dd17f168fca231823e8
[ "Apache-2.0" ]
null
null
null
Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx
151706061/ITK
6c073453ff8bdae9b1392dd17f168fca231823e8
[ "Apache-2.0" ]
2
2017-05-02T07:18:49.000Z
2020-04-30T01:37:35.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkAzimuthElevationToCartesianTransform.h" typedef double CoordinateRepresentationType; typedef itk::Point<CoordinateRepresentationType,3> PointType; void PrintPoint( const PointType & p ) { for( unsigned int i=0; i<PointType::PointDimension; i++) { std::cout << p[i] << ", "; } std::cout << std::endl; } int itkAzimuthElevationToCartesianTransformTest(int, char *[]) { const CoordinateRepresentationType ACCEPTABLE_ERROR = 1E-10; typedef itk::AzimuthElevationToCartesianTransform< CoordinateRepresentationType > AzimuthElevationToCartesianTransformType; AzimuthElevationToCartesianTransformType::Pointer transform = AzimuthElevationToCartesianTransformType::New(); transform->SetAzimuthElevationToCartesianParameters(1.0,5.0,45,45); PointType p; p[0] = 3; p[1] = 3; p[2] = 25; std::cout<< "original values of (theta,phi,r) p = "<<std::endl; PrintPoint(p); transform->SetForwardAzimuthElevationToCartesian(); PointType answer = transform->TransformPoint(p); PrintPoint(answer); PointType answerBackwards = transform->BackTransformPoint(answer); PrintPoint(answerBackwards); transform->SetForwardCartesianToAzimuthElevation(); PointType reverseDirectionAnswer = transform->BackTransformPoint(answerBackwards); PrintPoint(reverseDirectionAnswer); PointType reverseDirectionAnswerBackwards = transform->TransformPoint(reverseDirectionAnswer); PrintPoint(reverseDirectionAnswerBackwards); transform->Print(std::cout); bool same=true; for (unsigned int i=0; i < p.PointDimension && same; i++) { same = ((vnl_math_abs(p[i] - answerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(p[i] - reverseDirectionAnswerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(answer[i] - reverseDirectionAnswer[i]) < ACCEPTABLE_ERROR)) ; } if (!same) { std::cout << "itkAzimuthElevationToCartesianTransformTest failed" <<std::endl; return EXIT_FAILURE; } std::cout << "itkAzimuthElevationToCartesianTransformTest passed" <<std::endl; return EXIT_SUCCESS; }
33.666667
98
0.665677
[ "transform" ]
7829ab1b7b0cf5f4e46ecf3e806e8f6170562c85
3,025
cc
C++
source/neuropod/tests/test_factories.cc
qiyanz/neuropod
13c2bc794b168583588b68269026ec4ed76163ed
[ "Apache-2.0" ]
887
2020-06-08T16:10:28.000Z
2022-03-27T21:55:43.000Z
source/neuropod/tests/test_factories.cc
qiyanz/neuropod
13c2bc794b168583588b68269026ec4ed76163ed
[ "Apache-2.0" ]
150
2020-06-09T10:43:15.000Z
2022-03-30T02:48:39.000Z
source/neuropod/tests/test_factories.cc
qiyanz/neuropod
13c2bc794b168583588b68269026ec4ed76163ed
[ "Apache-2.0" ]
70
2020-06-08T18:43:12.000Z
2022-03-18T20:37:51.000Z
/* Copyright (c) 2020 UATC, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gtest/gtest.h" #include "neuropod/core/generic_tensor.hh" namespace { template <typename T> bool is_full(neuropod::TypedNeuropodTensor<T> &tensor, T value, size_t num_items) { // Make sure our size is correct auto actual_numel = tensor.get_num_elements(); EXPECT_EQ(actual_numel, num_items); // Generate expected data T expected_data[num_items]; std::fill_n(expected_data, num_items, value); // Compare auto actual_data = tensor.get_raw_data_ptr(); return memcmp(actual_data, expected_data, num_items * sizeof(uint8_t)) == 0; } template <typename T> bool matches_expected(neuropod::TypedNeuropodTensor<T> &tensor, const std::vector<T> expected) { return tensor.get_data_as_vector() == expected; } } // namespace TEST(test_factories, test_factories) { auto allocator = neuropod::get_generic_tensor_allocator(); constexpr size_t num_items = 60; const std::vector<int64_t> dims = {3, 4, 5}; auto zeros = allocator->zeros<uint16_t>(dims); auto ones = allocator->ones<int32_t>(dims); auto full = allocator->full<double>(dims, 1.23); auto randn = allocator->randn<float>(dims); EXPECT_TRUE(is_full<uint16_t>(*zeros, 0, num_items)); EXPECT_TRUE(is_full<int32_t>(*ones, 1, num_items)); EXPECT_TRUE(is_full<double>(*full, 1.23, num_items)); // It's super unlikely for every element to be 0 EXPECT_FALSE(is_full<float>(*randn, 0, num_items)); auto range1 = allocator->arange<float>(5); auto range2 = allocator->arange<float>(2, 6); auto range3 = allocator->arange<float>(0, 10, 2); // Make sure they're 1D tensors EXPECT_EQ(range1->get_dims().size(), 1); EXPECT_EQ(range2->get_dims().size(), 1); EXPECT_EQ(range3->get_dims().size(), 1); // And that they match the expected data EXPECT_TRUE(matches_expected(*range1, {0, 1, 2, 3, 4})); EXPECT_TRUE(matches_expected(*range2, {2, 3, 4, 5})); EXPECT_TRUE(matches_expected(*range3, {0, 2, 4, 6, 8})); auto eye1 = allocator->eye<float>(4, 4); // clang-format off EXPECT_TRUE(matches_expected(*eye1, { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })); // clang-format on auto eye2 = allocator->eye<float>(3, 7); // clang-format off EXPECT_TRUE(matches_expected(*eye2, { 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 })); // clang-format on }
30.867347
94
0.666116
[ "vector" ]
782ee0a792c57f4df6354d2dd5382751844ede68
18,321
cc
C++
chrome/test/accessibility/accessibility_util.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
1
2016-05-08T15:35:17.000Z
2016-05-08T15:35:17.000Z
chrome/test/accessibility/accessibility_util.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
chrome/test/accessibility/accessibility_util.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/accessibility/accessibility_util.h" #include "base/win_util.h" #include "chrome/common/win_util.h" #include "chrome/common/l10n_util.h" #include "chrome/browser/views/old_frames/xp_frame.h" #include "chrome/browser/views/old_frames/vista_frame.h" #include "chrome/test/accessibility/constants.h" #include "chromium_strings.h" #include "generated_resources.h" VARIANT g_var_self = {VT_I4, CHILDID_SELF}; // TODO(beng): clean this up static const wchar_t* kBrowserWindowKey = L"__BROWSER_WINDOW__"; static BOOL CALLBACK WindowEnumProc(HWND hwnd, LPARAM data) { std::wstring class_name = win_util::GetClassName(hwnd); if (class_name == L"Chrome_ContainerWin_0") { HANDLE window_interface = GetProp(hwnd, kBrowserWindowKey); if (window_interface) { HWND* out = reinterpret_cast<HWND*>(data); *out = hwnd; return FALSE; } } return TRUE; } HWND GetChromeBrowserWnd(IAccessible** ppi_access) { HRESULT hr = S_OK; HWND hwnd = NULL; BSTR str_name; std::wstring str_role; const std::wstring product_name = l10n_util::GetString(IDS_PRODUCT_NAME); EnumWindows(WindowEnumProc, reinterpret_cast<LPARAM>(&hwnd)); if (!IsWindow(hwnd)) { // Didn't find the window handle by looking for the new frames, assume the // old frames are being used instead... if (win_util::ShouldUseVistaFrame()) { hwnd = FindWindow(VISTA_FRAME_CLASSNAME, NULL); } else { hwnd = FindWindow(XP_FRAME_CLASSNAME, NULL); } } if (NULL == hwnd) { if (ppi_access) *ppi_access = NULL; return hwnd; } // Get accessibility object for Chrome, only if requested. if (!ppi_access) { return hwnd; } *ppi_access = NULL; // Get accessibility object for Chrome Main Window. If failed to get it, // return only window handle. IAccessible *pi_acc_root_win = NULL; hr = AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**> (&pi_acc_root_win)); if ((S_OK != hr) || !pi_acc_root_win) { return hwnd; } // Confirm if it is Chrome window using it's accessibility object's // Name and Role property. If it's not the desired object, return only // window handle. hr = pi_acc_root_win->get_accName(g_var_self, &str_name); if ((S_OK != hr) || (!str_name) || (0 != _wcsicmp(str_name, product_name.c_str())) ) { CHK_RELEASE(pi_acc_root_win); return hwnd; } str_role = GetRole(pi_acc_root_win); if (0 != str_role.compare(BROWSER_WIN_ROLE)) { CHK_RELEASE(pi_acc_root_win); return hwnd; } // Get accessibility object for Chrome Window. If failed to get it, // return only window handle. INT64 child_cnt = GetChildCount(pi_acc_root_win); VARIANT *var_array_child = reinterpret_cast<VARIANT*>(calloc(size_t(child_cnt), sizeof(VARIANT))); if (!var_array_child) { CHK_RELEASE(pi_acc_root_win); return hwnd; } hr = GetChildrenArray(pi_acc_root_win, var_array_child); if (S_OK != hr) { CHK_RELEASE(pi_acc_root_win); return hwnd; } // Fetch desired child (Chrome window) of Chrome Main Window. IAccessible *pi_acc_app = NULL; GetChildObject(pi_acc_root_win, var_array_child[CHROME_APP_ACC_INDEX], &pi_acc_app); if (!pi_acc_app) { CHK_RELEASE(pi_acc_app); return hwnd; } // Confirm if it is Chrome application using it's accessibility object's // Name and Role property. If it's not the desired object, return only // window handle. hr = pi_acc_app->get_accName(g_var_self, &str_name); if ((S_OK != hr) || (!str_name) || (0 != _wcsicmp(str_name, product_name.c_str())) ) { CHK_RELEASE(pi_acc_app); CHK_RELEASE(pi_acc_root_win); return hwnd; } str_role = GetRole(pi_acc_app); if (0 != str_role.compare(BROWSER_APP_ROLE)) { CHK_RELEASE(pi_acc_app); CHK_RELEASE(pi_acc_root_win); return hwnd; } // Get accessibility object for Chrome Client. If failed, return only // window handle. hr = GetChildrenArray(pi_acc_app, var_array_child); if (S_OK != hr) { CHK_RELEASE(pi_acc_app); CHK_RELEASE(pi_acc_root_win); return hwnd; } // Chrome Window has only one child which is Chrome Client. GetChildObject(pi_acc_app, var_array_child[CHROME_CLIENT_ACC_INDEX], ppi_access); // Confirm if it is Chrome client using it's accessibility object's Name // and Role property. If it's not the desired object, return only window // handle. hr = (*ppi_access)->get_accName(g_var_self, &str_name); if ((S_OK != hr) || (!str_name) || (0 != _wcsicmp(str_name, product_name.c_str())) ) { CHK_RELEASE(*ppi_access); } str_role = GetRole(*ppi_access); if (0 != str_role.compare(BROWSER_CLIENT_ROLE)) { CHK_RELEASE(*ppi_access); } CHK_RELEASE(pi_acc_app); CHK_RELEASE(pi_acc_root_win); return hwnd; } HRESULT GetChildWndOf(std::wstring parent_name, unsigned int child_index, IAccessible** ppi_access, VARIANT* child_var_id) { HRESULT hr = S_OK; // Validate input and initialize. if (!ppi_access && !child_var_id) return E_INVALIDARG; if (ppi_access) *ppi_access = NULL; if (child_var_id) VariantInit(child_var_id); // Get accessibility object and window handle for Chrome parent. IAccessible *pi_parent = NULL; if (0 == parent_name.compare(BROWSER_STR)) GetChromeBrowserWnd(&pi_parent); if (0 == parent_name.compare(BROWSER_VIEW_STR)) GetBrowserViewWnd(&pi_parent); if (0 == parent_name.compare(TOOLBAR_STR)) GetToolbarWnd(&pi_parent); if (0 == parent_name.compare(TABSTRIP_STR)) GetTabStripWnd(&pi_parent); if (!pi_parent) return E_FAIL; // Validate child index. INT64 child_cnt = GetChildCount(pi_parent); if (child_index >= child_cnt) { CHK_RELEASE(pi_parent); VariantClear(child_var_id); return E_INVALIDARG; } // Get array of child items of parent object. VARIANT *var_array_child = reinterpret_cast<VARIANT*>(calloc(size_t(child_cnt), sizeof(VARIANT))); if (var_array_child) { hr = GetChildrenArray(pi_parent, var_array_child); if (S_OK == hr) { // Fetch Tabstrip which is child_index'th child of parent object. if (ppi_access) { hr = GetChildObject(pi_parent, var_array_child[child_index], ppi_access); } if (child_var_id) { VariantCopy(child_var_id, var_array_child+child_index); } } free(var_array_child); } CHK_RELEASE(pi_parent); return hr; } HRESULT GetTabStripWnd(IAccessible** ppi_access) { #ifdef NEW_FRAMES return GetChildWndOf(BROWSER_VIEW_STR, TABSTRIP_ACC_INDEX, ppi_access, NULL); #else return GetChildWndOf(BROWSER_STR, TABSTRIP_ACC_INDEX, ppi_access, NULL); #endif } HRESULT GetBrowserViewWnd(IAccessible** ppi_access) { return GetChildWndOf(BROWSER_STR, BROWSER_VIEW_ACC_INDEX, ppi_access, NULL); } HRESULT GetToolbarWnd(IAccessible** ppi_access) { return GetChildWndOf(BROWSER_VIEW_STR, TOOLBAR_ACC_INDEX, ppi_access, NULL); } HRESULT GetBrowserMinimizeButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(BROWSER_STR, CHROME_MIN_ACC_INDEX, ppi_access, child_var_id); } HRESULT GetBrowserMaximizeButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(BROWSER_STR, CHROME_MAX_ACC_INDEX, ppi_access, child_var_id); } HRESULT GetBrowserRestoreButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(BROWSER_STR, CHROME_RESTORE_ACC_INDEX, ppi_access, child_var_id); } HRESULT GetBrowserCloseButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(BROWSER_STR, CHROME_CLOSE_ACC_INDEX, ppi_access, child_var_id); } HRESULT GetStarButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(TOOLBAR_STR, STAR_BTN_INDEX, ppi_access, child_var_id); } HRESULT GetBackButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(TOOLBAR_STR, BACK_BTN_INDEX, ppi_access, child_var_id); } HRESULT GetForwardButton(IAccessible** ppi_access, VARIANT* child_var_id) { return GetChildWndOf(TOOLBAR_STR, FORWARD_BTN_INDEX, ppi_access, child_var_id); } HWND GetAddressBarWnd(IAccessible** ppi_access) { HWND hwnd = NULL; HWND hwnd_addr_bar = NULL; // // Initialize, if requested. if (ppi_access) { *ppi_access = NULL; } // Get window handle for Chrome Browser. hwnd = GetChromeBrowserWnd(NULL); if (NULL != hwnd) { // Get AddressBar/OmniBox (edit box) window handle. hwnd_addr_bar = FindWindowEx(hwnd, 0, CHROME_AUTOCOMPLETE_EDIT, NULL); // Get accessibility object for address bar, if requested. if (ppi_access && hwnd_addr_bar) { AccessibleObjectFromWindow(hwnd_addr_bar, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(ppi_access)); } } return hwnd_addr_bar; } HWND GetFindTextWnd(IAccessible** ppi_access) { HWND hwnd = NULL; HWND hwnd_find = NULL; // Initialize, if requested. if (ppi_access) { *ppi_access = NULL; } // Get window handle for Chrome Browser. hwnd = GetChromeBrowserWnd(NULL); if (NULL != hwnd) { // Get handle of a window, which is contains edit box for Find string. hwnd_find = FindWindowEx(hwnd, 0, CHROME_HWND_VIEW_CONTAINER, NULL); // Get accessibility object, if requested. if (ppi_access && hwnd_find) { AccessibleObjectFromWindow(hwnd_find, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(ppi_access)); } } return hwnd_find; } HWND GetAuthWnd(IAccessible** ppi_access) { HWND hwnd = NULL; HWND hwnd_tab = NULL; HWND hwnd_auth = NULL; // Initialize, if requested. if (ppi_access) { *ppi_access = NULL; } // Get window handle for Chrome Browser. hwnd = GetChromeBrowserWnd(NULL); if (NULL != hwnd) { // Get window handle for tab. hwnd_tab = FindWindowEx(hwnd, 0, CHROME_TAB_CONTENTS, NULL); if (!hwnd_tab) return hwnd_auth; // Get handle for Authentication window. hwnd_auth = FindWindowEx(hwnd_tab, 0, CHROME_HWND_VIEW_CONTAINER, AUTH_TITLE); // Get accessibility object, if requested. if (ppi_access && hwnd_auth) { AccessibleObjectFromWindow(hwnd_auth, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(ppi_access)); } } return hwnd_auth; } HRESULT GetChildObject(IAccessible* pi_access, VARIANT var_child, IAccessible** ppi_child_access) { HRESULT hr = S_OK; IDispatch *p_dispatch = NULL; // Validate input. if ( (pi_access == NULL) || (ppi_child_access == NULL) ) { return E_INVALIDARG; } // Check the child type and fetch object accordingly. if (var_child.vt == VT_DISPATCH) { var_child.pdispVal-> QueryInterface(IID_IAccessible, reinterpret_cast<void**>(ppi_child_access)); } else if (var_child.vt == VT_I4) { hr = pi_access->get_accChild(var_child, &p_dispatch); if ( (hr == S_OK) && (p_dispatch != NULL) ) { p_dispatch->QueryInterface(IID_IAccessible, reinterpret_cast<void**>(ppi_child_access)); CHK_RELEASE(p_dispatch); } } return hr; } HRESULT GetParentObject(IAccessible* pi_access, IAccessible** ppi_parent_access) { HRESULT hr = S_OK; IDispatch *p_dispatch = NULL; // Validate input. if ( (pi_access == NULL) || (ppi_parent_access == NULL) ) { return E_INVALIDARG; } // Fetch parent object. hr = pi_access->get_accParent(&p_dispatch); if ( (hr == S_OK) && (p_dispatch != NULL) ) { p_dispatch->QueryInterface(IID_IAccessible, reinterpret_cast<void**>(ppi_parent_access)); CHK_RELEASE(p_dispatch); } return hr; } INT64 GetChildCount(IAccessible* pi_access) { HRESULT hr = S_OK; long child_cnt = 0; // Validate input. Object can have 0 children. So return -1 on invalid input. if (pi_access == NULL) { return -1; } // Get child count. pi_access->get_accChildCount(&child_cnt); return child_cnt; } HRESULT GetChildrenArray(IAccessible* pi_access, VARIANT* var_array_child) { HRESULT hr = S_OK; INT64 child_start = 0; long child_obtained = 0; INT64 child_cnt = GetChildCount(pi_access); // Validate input. if ((pi_access == NULL) || (var_array_child == NULL)) { return E_INVALIDARG; } // Validate every item and initialize it. int i = 0; for (; (i < child_cnt) && (var_array_child+i); i++) { VariantInit(var_array_child+i); } // If all items in array are not initialized, return error. if (i != child_cnt) { return E_INVALIDARG; } // Get IDs of child items. AccessibleChildren(pi_access, LONG(child_start), LONG(child_cnt), var_array_child, &child_obtained); return hr; } HRESULT ActivateWnd(IAccessible *pi_access, HWND hwnd) { HRESULT hr = S_OK; // Select and focus the object, if accessibility object is specified. if (pi_access) { hr = pi_access->accSelect(SELFLAG_TAKEFOCUS | SELFLAG_TAKESELECTION, g_var_self); } // Send message to window, if window handle is specified. if (hwnd) { SetActiveWindow(hwnd); } return hr; } BSTR GetTabName(INT64 tab_index) { HRESULT hr = S_OK; BSTR str_name; // Validate tab index specified. if (tab_index < 1) return NULL; // Get accessibility object for Tabstrip. IAccessible *pi_acc_strip = NULL; GetTabStripWnd(&pi_acc_strip); // Get Tab from Tabstrip and return it's Name. if (pi_acc_strip) { INT64 child_cnt = GetChildCount(pi_acc_strip); VARIANT *var_array_child = reinterpret_cast<VARIANT*>(calloc(size_t(child_cnt), sizeof(VARIANT))); if (var_array_child) { // Get tab object. tab_index = index in child array, because first child // in tabstrip is '+' button. hr = GetChildrenArray(pi_acc_strip, var_array_child); if (S_OK == hr) { IAccessible *pi_access_temp = NULL; hr = GetChildObject(pi_acc_strip, var_array_child[tab_index], &pi_access_temp); if ((S_OK == hr) && (var_array_child[tab_index].vt == VT_DISPATCH) && (pi_access_temp) ) { hr = pi_access_temp->get_accName(g_var_self, &str_name); } else if (var_array_child[tab_index].vt == VT_I4) { hr = pi_acc_strip->get_accName(var_array_child[1], &str_name); } CHK_RELEASE(pi_acc_strip); return str_name; } } CHK_RELEASE(pi_acc_strip); } return NULL; } INT64 GetTabCnt() { // Get accessibility object for Tabstrip. IAccessible *pi_acc_strip = NULL; GetTabStripWnd(&pi_acc_strip); // If Tabstrip is invalid, return -1, to indicate error. if (!pi_acc_strip) { return -1; } // Get child count. INT64 child_cnt = 0; if (pi_acc_strip) { child_cnt = GetChildCount(pi_acc_strip); CHK_RELEASE(pi_acc_strip); } // Don't count 1st child as it is '+' button. return (child_cnt-1); } std::wstring GetName(IAccessible* pi_access, VARIANT child) { HRESULT hr = S_OK; // Validate input. if (NULL == pi_access) { return std::wstring(); } // Get Name. BSTR name; hr = pi_access->get_accName(child, &name); if (S_OK != hr) return std::wstring(); return std::wstring(name); } std::wstring GetRole(IAccessible* pi_access, VARIANT child) { HRESULT hr = S_OK; LPTSTR role_str = NULL; // Validate input. if (NULL == pi_access) { return std::wstring(); } // Get Role. VARIANT role; VariantInit(&role); hr = pi_access->get_accRole(child, &role); if (S_OK != hr || VT_I4 != role.vt) { VariantClear(&role); return std::wstring(); } // Get Role string. unsigned int role_length = GetRoleText(role.lVal, NULL, 0); role_str = (LPTSTR)calloc(role_length + 1, sizeof(TCHAR)); if (role_str) GetRoleText(role.lVal, role_str, role_length + 1); VariantClear(&role); return std::wstring(role_str); } std::wstring GetState(IAccessible* pi_access, VARIANT child) { HRESULT hr = S_OK; LPTSTR state_str = NULL; std::wstring complete_state; // Validate input. if (NULL == pi_access) { return std::wstring(); } // Get State. VARIANT state; VariantInit(&state); hr = pi_access->get_accState(child, &state); if (S_OK != hr || VT_I4 != state.vt) { VariantClear(&state); return std::wstring(); } // Treat the "normal" state separately. if (state.vt == 0) { unsigned int state_length = GetStateText(state.lVal, NULL, 0); state_str = (LPTSTR)calloc(state_length + 1, sizeof(TCHAR)); if (state_str) { GetStateText(state.lVal, state_str, state_length + 1); complete_state = std::wstring(state_str); } } else { // Number of bits. UINT bit_cnt = 32; // Convert state flags to comma separated list. for (DWORD dwStateBit = 0x80000000; bit_cnt; bit_cnt--, dwStateBit >>= 1) { if (state.lVal & dwStateBit) { unsigned int state_length = GetStateText(dwStateBit, NULL, 0); state_str = (LPTSTR)calloc(state_length + 1, sizeof(TCHAR)); if (state_str) { GetStateText(dwStateBit, state_str, state_length + 1); if (complete_state.length() > 0) complete_state.append(L", "); complete_state.append(state_str); free(state_str); } } } } VariantClear(&state); return complete_state; }
29.034865
79
0.656078
[ "object" ]
782fac540cd216476e0addce6f6dc1201844b32e
3,667
cpp
C++
game/StartScene.cpp
kaplaars/CppHerexamen
604bcb841238cca29604224f77fd5afae4e96f80
[ "MIT" ]
null
null
null
game/StartScene.cpp
kaplaars/CppHerexamen
604bcb841238cca29604224f77fd5afae4e96f80
[ "MIT" ]
null
null
null
game/StartScene.cpp
kaplaars/CppHerexamen
604bcb841238cca29604224f77fd5afae4e96f80
[ "MIT" ]
null
null
null
#include <libgba-sprite-engine/sprites/sprite_builder.h> #include <libgba-sprite-engine/background/text_stream.h> #include <libgba-sprite-engine/gba/tonc_memdef.h> #include <libgba-sprite-engine/gba_engine.h> #include "StartScene.h" #include "MiniGame1.h" #include "MiniGame2.h" #include "MiniGame3.h" #include "CollorPallet.h" #include "karakter.h" #include "sample_sound.h" #include "background.h" StartScene::StartScene(const std::shared_ptr<GBAEngine> &engine) : Scene(engine){} std::vector<Sprite *> StartScene::sprites() { return {animation.get()}; } std::vector<Background *> StartScene::backgrounds() { return { bg.get() }; } void StartScene::load() { backgroundPalette = std::unique_ptr<BackgroundPaletteManager>(new BackgroundPaletteManager(gbmapPal, sizeof(gbmapPal))); foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(new ForegroundPaletteManager(sharedPal, sizeof(sharedPal))); engine.get()->enableText(); bg = std::unique_ptr<Background>(new Background(0, gbmapTiles, sizeof(gbmapTiles), gbmapMap, sizeof(gbmapMap))); bg.get()->useMapScreenBlock(24); SpriteBuilder<Sprite> builder; animation = builder .withData(karakterTiles, sizeof(karakterTiles)) .withSize(SIZE_32_32) .withAnimated(3, 20) .withLocation(100, 100) .withinBounds() .buildPtr(); engine->getTimer()->start(); //TextStream::instance().setText("Score: " + std::to_string(totaalscore), 1, 3); engine->enqueueMusic(zelda_music_16K_mono, zelda_music_16K_mono_bytes); } void StartScene::tick(u16 keys) { //manneke bewegen if(keys & KEY_LEFT) { if((animation->getY()>10 && animation->getX()<70 && animation->getY()<83)||(animation->getY()<38 && animation->getX()==155)) { animation->setVelocity(0, 0); }else { animation->setVelocity(-1, 0); } } else if(keys & KEY_RIGHT) { if((animation->getY()<38 && animation->getX()==75)||(animation->getY()<75 && animation->getY()>10 && animation->getX()==160)) { animation->setVelocity(0, 0); }else{ animation->setVelocity(1,0); } } else if(keys & KEY_UP) { if((animation->getX()>75 && animation->getX()<155 && animation->getY() < 38)||(animation->getY()<83 && animation->getY()>10 && animation->getX()<70)||(animation->getY()<75 && animation->getY()>15 && animation->getX()>160)) { animation->setVelocity(0, 0); }else { animation->setVelocity(0, -1); } } else if(keys & KEY_DOWN) { if(animation->getY()>110||(animation->getY()<83 && animation->getY()>10 && animation->getX()<70)||(animation->getY()<70 && animation->getY()>10 && animation->getX()>160)) { animation->setVelocity(0, 0); }else { animation->setVelocity(0, 1); } } else{ animation->setVelocity(0, 0); } //naar een minigame gaan //minigame 1 if(animation->getY()>70 && animation->getY()<100 && animation->getX()>20 && animation->getX()<50) { if(keys & KEY_A) { engine->setScene(new MiniGame1(engine)); } } //minigame 2 if(animation->getY()>37 && animation->getY()<68 && animation->getX()>100 && animation->getX()<130) { if(keys & KEY_A) { engine->setScene(new MiniGame2(engine)); } } //minigame 3 if(animation->getY()>74 && animation->getY()<104 && animation->getX()>185 && animation->getX()<215) { if(keys & KEY_A) { engine->setScene(new MiniGame3(engine)); } } }
34.92381
232
0.6054
[ "vector" ]
783228583018d6899ccf59e4e8b7bcad9cd0b924
4,022
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-es/source/model/ElasticsearchClusterConfig.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-es/source/model/ElasticsearchClusterConfig.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-es/source/model/ElasticsearchClusterConfig.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/es/model/ElasticsearchClusterConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ElasticsearchService { namespace Model { ElasticsearchClusterConfig::ElasticsearchClusterConfig() : m_instanceTypeHasBeenSet(false), m_instanceCount(0), m_instanceCountHasBeenSet(false), m_dedicatedMasterEnabled(false), m_dedicatedMasterEnabledHasBeenSet(false), m_zoneAwarenessEnabled(false), m_zoneAwarenessEnabledHasBeenSet(false), m_dedicatedMasterTypeHasBeenSet(false), m_dedicatedMasterCount(0), m_dedicatedMasterCountHasBeenSet(false) { } ElasticsearchClusterConfig::ElasticsearchClusterConfig(const JsonValue& jsonValue) : m_instanceTypeHasBeenSet(false), m_instanceCount(0), m_instanceCountHasBeenSet(false), m_dedicatedMasterEnabled(false), m_dedicatedMasterEnabledHasBeenSet(false), m_zoneAwarenessEnabled(false), m_zoneAwarenessEnabledHasBeenSet(false), m_dedicatedMasterTypeHasBeenSet(false), m_dedicatedMasterCount(0), m_dedicatedMasterCountHasBeenSet(false) { *this = jsonValue; } ElasticsearchClusterConfig& ElasticsearchClusterConfig::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("InstanceType")) { m_instanceType = ESPartitionInstanceTypeMapper::GetESPartitionInstanceTypeForName(jsonValue.GetString("InstanceType")); m_instanceTypeHasBeenSet = true; } if(jsonValue.ValueExists("InstanceCount")) { m_instanceCount = jsonValue.GetInteger("InstanceCount"); m_instanceCountHasBeenSet = true; } if(jsonValue.ValueExists("DedicatedMasterEnabled")) { m_dedicatedMasterEnabled = jsonValue.GetBool("DedicatedMasterEnabled"); m_dedicatedMasterEnabledHasBeenSet = true; } if(jsonValue.ValueExists("ZoneAwarenessEnabled")) { m_zoneAwarenessEnabled = jsonValue.GetBool("ZoneAwarenessEnabled"); m_zoneAwarenessEnabledHasBeenSet = true; } if(jsonValue.ValueExists("DedicatedMasterType")) { m_dedicatedMasterType = ESPartitionInstanceTypeMapper::GetESPartitionInstanceTypeForName(jsonValue.GetString("DedicatedMasterType")); m_dedicatedMasterTypeHasBeenSet = true; } if(jsonValue.ValueExists("DedicatedMasterCount")) { m_dedicatedMasterCount = jsonValue.GetInteger("DedicatedMasterCount"); m_dedicatedMasterCountHasBeenSet = true; } return *this; } JsonValue ElasticsearchClusterConfig::Jsonize() const { JsonValue payload; if(m_instanceTypeHasBeenSet) { payload.WithString("InstanceType", ESPartitionInstanceTypeMapper::GetNameForESPartitionInstanceType(m_instanceType)); } if(m_instanceCountHasBeenSet) { payload.WithInteger("InstanceCount", m_instanceCount); } if(m_dedicatedMasterEnabledHasBeenSet) { payload.WithBool("DedicatedMasterEnabled", m_dedicatedMasterEnabled); } if(m_zoneAwarenessEnabledHasBeenSet) { payload.WithBool("ZoneAwarenessEnabled", m_zoneAwarenessEnabled); } if(m_dedicatedMasterTypeHasBeenSet) { payload.WithString("DedicatedMasterType", ESPartitionInstanceTypeMapper::GetNameForESPartitionInstanceType(m_dedicatedMasterType)); } if(m_dedicatedMasterCountHasBeenSet) { payload.WithInteger("DedicatedMasterCount", m_dedicatedMasterCount); } return payload; } } // namespace Model } // namespace ElasticsearchService } // namespace Aws
26.993289
137
0.77822
[ "model" ]
7832a72bd8c7aabf31cbc6d3f74d7e118ef89330
803
cpp
C++
systems/plants/massMatrixmex.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
null
null
null
systems/plants/massMatrixmex.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
null
null
null
systems/plants/massMatrixmex.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
1
2021-09-29T19:37:28.000Z
2021-09-29T19:37:28.000Z
#include <mex.h> #include <iostream> #include "drakeUtil.h" #include "RigidBodyManipulator.h" using namespace Eigen; using namespace std; void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { string usage = "Usage [M, dM] = massMatrixmex(model_ptr)"; if (nrhs != 1) { mexErrMsgIdAndTxt("Drake:geometricJacobianmex:WrongNumberOfInputs", usage.c_str()); } if (nlhs > 2) { mexErrMsgIdAndTxt("Drake:geometricJacobianmex:WrongNumberOfOutputs", usage.c_str()); } int gradient_order = nlhs - 1; RigidBodyManipulator *model = (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]); auto ret = model->massMatrix<double>(gradient_order); plhs[0] = eigenToMatlab(ret.value()); if (gradient_order > 0) plhs[1] = eigenToMatlab(ret.gradient().value()); }
25.903226
88
0.709838
[ "model" ]
78406467a6f4ded90dfa2d45fd2b6d6ad411d21d
2,003
hpp
C++
src/Controller/Yokai.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
1
2021-04-11T04:57:06.000Z
2021-04-11T04:57:06.000Z
src/Controller/Yokai.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
null
null
null
src/Controller/Yokai.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
null
null
null
#pragma once #include "Controller/TerrainManager.hpp" #include "View/Renderer/Renderer.hpp" #include "View/Window.hpp" #include "Model/SplashScreen.hpp" //workaround to allow vector of layer pointers class Layer; /** * @class Yokai * @brief A class which ties together all game engine components */ class Yokai { public: /** * @brief Returns an instance of the engine * @return Yokai& */ static Yokai & getInstance(); /** * @brief Initialises the engine */ void Init(); /** * @brief Runs the engine loop */ void Run(); ///renderer used by engine Renderer renderer = {}; ///window used by the engine Window window = {}; /** * @brief Set is Running * @param s */ void setIsRunning(bool s); /** * @brief Gets a layer Pointer * @return Layer* */ std::vector<std::shared_ptr<Layer>> getLayer(); /** * @brief Sets active lauer * @param a */ void setActiveLayer(int a); /** * Sets the paused state * @param p */ void setIsPaused(bool p); /** * Return true if engine paused * @return bool */ bool getIsPaused() const; void registerClass(); private: //Singleton pattern requires that all constructors,destructors and copy constructors be private /** * @brief Registers Engine close event with EMS */ void registerClose(); /** * @brief Privatised Default Constructor */ Yokai() = default; /** * @brief Privatised Default Destructor */ ~Yokai() = default; /** * @brief Deleted Copy Constructor */ Yokai(const Yokai &) = delete; /** * @brief Privatised assign operator */ Yokai &operator =(const Yokai &); ///Is engine Running bool isRunning = true; ///Vector of Scene layers std::vector<std::shared_ptr<Layer>> layers; ///is paused bool isPaused; ///active layer int activeLayer; };
21.537634
99
0.588617
[ "vector", "model" ]
784239e314630316f77ec8049558b1b462e8ca74
9,190
cpp
C++
src/archutils/Darwin/JoystickDevice.cpp
SharpnelXu/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
1
2022-02-22T01:24:02.000Z
2022-02-22T01:24:02.000Z
src/archutils/Darwin/JoystickDevice.cpp
john-marinelli/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
1
2019-05-04T02:30:57.000Z
2019-05-04T02:30:57.000Z
src/archutils/Darwin/JoystickDevice.cpp
john-marinelli/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
3
2019-05-02T01:50:23.000Z
2020-05-25T01:08:36.000Z
#include "Etterna/Globals/global.h" #include "JoystickDevice.h" #include "Etterna/Models/Misc/Foreach.h" #include "Core/Services/Locator.hpp" using __gnu_cxx::hash_map; Joystick::Joystick() : id(InputDevice_Invalid) , x_axis(0) , y_axis(0) , z_axis(0) , x_rot(0) , y_rot(0) , z_rot(0) , hat(0) , x_min(0) , x_max(0) , y_min(0) , y_max(0) , z_min(0) , z_max(0) , rx_min(0) , rx_max(0) , ry_min(0) , ry_max(0) , rz_min(0) , rz_max(0) , hat_min(0) , hat_max(0) { } bool JoystickDevice::AddLogicalDevice(int usagePage, int usage) { if (usagePage != kHIDPage_GenericDesktop) return false; switch (usage) { case kHIDUsage_GD_Joystick: case kHIDUsage_GD_GamePad: break; default: return false; } m_vSticks.push_back(Joystick()); return true; } void JoystickDevice::AddElement(int usagePage, int usage, IOHIDElementCookie cookie, const CFDictionaryRef properties) { if (usagePage >= kHIDPage_VendorDefinedStart) return; ASSERT(m_vSticks.size()); Joystick& js = m_vSticks.back(); switch (usagePage) { case kHIDPage_GenericDesktop: { int iMin = 0; int iMax = 0; IntValue( CFDictionaryGetValue(properties, CFSTR(kIOHIDElementMinKey)), iMin); IntValue( CFDictionaryGetValue(properties, CFSTR(kIOHIDElementMaxKey)), iMax); switch (usage) { case kHIDUsage_GD_X: js.x_axis = cookie; js.x_min = iMin; js.x_max = iMax; break; case kHIDUsage_GD_Y: js.y_axis = cookie; js.y_min = iMin; js.y_max = iMax; break; case kHIDUsage_GD_Z: js.z_axis = cookie; js.z_min = iMin; js.z_max = iMax; break; case kHIDUsage_GD_Rx: js.x_rot = cookie; js.rx_min = iMin; js.rx_max = iMax; break; case kHIDUsage_GD_Ry: js.y_rot = cookie; js.ry_min = iMin; js.ry_max = iMax; break; case kHIDUsage_GD_Rz: js.z_rot = cookie; js.rz_min = iMin; js.rz_max = iMax; break; case kHIDUsage_GD_DPadUp: js.mapping[cookie] = JOY_UP; break; case kHIDUsage_GD_DPadDown: js.mapping[cookie] = JOY_DOWN; break; case kHIDUsage_GD_DPadRight: js.mapping[cookie] = JOY_RIGHT; break; case kHIDUsage_GD_DPadLeft: js.mapping[cookie] = JOY_LEFT; break; case kHIDUsage_GD_Hatswitch: { if (iMax - iMin != 7 && iMax - iMin != 3) break; js.hat = cookie; js.hat_min = iMin; js.hat_max = iMax; break; } default: // LOG->Warn( "Unknown usagePage usage pair: // (kHIDPage_GenericDesktop, %d).", usage ); break; } break; } case kHIDPage_Button: { const DeviceButton buttonID = enum_add2(JOY_BUTTON_1, usage - kHIDUsage_Button_1); if (buttonID <= JOY_BUTTON_32) js.mapping[cookie] = buttonID; else Locator::getLogger()->warn("Button id too large: {}.", int(buttonID)); break; } default: // LOG->Warn( "Unknown usagePage usage pair: (%d, %d).", usagePage, // usage ); break; } // end switch (usagePage) } void JoystickDevice::Open() { // Add elements to the queue for each Joystick FOREACH_CONST(Joystick, m_vSticks, i) { const Joystick& js = *i; #define ADD(x) \ if (js.x) \ AddElementToQueue(js.x) ADD(x_axis); ADD(y_axis); ADD(z_axis); ADD(x_rot); ADD(y_rot); ADD(z_rot); ADD(hat); #undef ADD for (hash_map<IOHIDElementCookie, DeviceButton>::const_iterator j = js.mapping.begin(); j != js.mapping.end(); ++j) AddElementToQueue(j->first); } } bool JoystickDevice::InitDevice(int vid, int pid) { if (vid != 0x0507 || pid != 0x0011) return true; // It's a Para controller, so try to power it on. uint8_t powerOn = 1; IOReturn ret = SetReport(kIOHIDReportTypeFeature, 0, &powerOn, 1, 10); if (ret) Locator::getLogger()->warn("Failed to power on the Para controller: {:#x}", ret); return ret == kIOReturnSuccess; } void JoystickDevice::GetButtonPresses( std::vector<DeviceInput>& vPresses, IOHIDElementCookie cookie, int value, const std::chrono::time_point<std::chrono::steady_clock>& now) const { FOREACH_CONST(Joystick, m_vSticks, i) { const Joystick& js = *i; if (js.x_axis == cookie) { float level = SCALE(value, js.x_min, js.x_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_LEFT, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_RIGHT, fmax(level, 0.0f), now)); break; } else if (js.y_axis == cookie) { float level = SCALE(value, js.y_min, js.y_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_UP, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_DOWN, fmax(level, 0.0f), now)); break; } else if (js.z_axis == cookie) { float level = SCALE(value, js.z_min, js.z_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_Z_UP, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_Z_DOWN, fmax(level, 0.0f), now)); break; } else if (js.x_rot == cookie) { float level = SCALE(value, js.rx_min, js.rx_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_ROT_LEFT, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_ROT_RIGHT, fmax(level, 0.0f), now)); break; } else if (js.y_rot == cookie) { float level = SCALE(value, js.ry_min, js.ry_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_ROT_UP, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_ROT_DOWN, fmax(level, 0.0f), now)); break; } else if (js.z_rot == cookie) { float level = SCALE(value, js.rz_min, js.rz_max, -1.0f, 1.0f); vPresses.push_back( DeviceInput(js.id, JOY_ROT_Z_UP, fmax(-level, 0.0f), now)); vPresses.push_back( DeviceInput(js.id, JOY_ROT_Z_DOWN, fmax(level, 0.0f), now)); break; } else if (js.hat == cookie) { float levelUp = 0.f, levelRight = 0.f, levelDown = 0.f, levelLeft = 0.f; value -= js.hat_min; // Probably just subtracting 0. if (js.hat_max - js.hat_min == 3) value *= 2; switch (value) { case 0: levelUp = 1.f; break; // U case 1: levelUp = 1.f; levelRight = 1.f; break; // UR case 2: levelRight = 1.f; break; // R case 3: levelDown = 1.f; levelRight = 1.f; break; // DR case 4: levelDown = 1.f; break; // D case 5: levelDown = 1.f; levelLeft = 1.f; break; // DL case 6: levelLeft = 1.f; break; // L case 7: levelUp = 1.f; levelLeft = 1.f; break; // UL } vPresses.push_back(DeviceInput(js.id, JOY_HAT_UP, levelUp, now)); vPresses.push_back( DeviceInput(js.id, JOY_HAT_RIGHT, levelRight, now)); vPresses.push_back( DeviceInput(js.id, JOY_HAT_DOWN, levelDown, now)); vPresses.push_back( DeviceInput(js.id, JOY_HAT_LEFT, levelLeft, now)); break; } else { // hash_map<T,U>::operator[] is not const hash_map<IOHIDElementCookie, DeviceButton>::const_iterator iter; iter = js.mapping.find(cookie); if (iter != js.mapping.end()) { vPresses.push_back( DeviceInput(js.id, iter->second, value, now)); break; } } } } int JoystickDevice::AssignIDs(InputDevice startID) { if (!IsJoystick(startID)) return -1; FOREACH(Joystick, m_vSticks, i) { if (!IsJoystick(startID)) { m_vSticks.erase(i, m_vSticks.end()); break; } i->id = startID; enum_add(startID, 1); } return m_vSticks.size(); } void JoystickDevice::GetDevicesAndDescriptions( std::vector<InputDeviceInfo>& vDevices) const { FOREACH_CONST(Joystick, m_vSticks, i) vDevices.push_back(InputDeviceInfo(i->id, GetDescription())); } /* * (c) 2005-2007 Steve Checkoway * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
25.814607
83
0.641458
[ "vector" ]
78431470a5900bb381c75e9607b5f19697f5f246
17,214
hpp
C++
src/graphlab/core.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-08-01T06:32:58.000Z
2018-08-01T06:32:58.000Z
src/graphlab/core.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/core.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_CORE_HPP #define GRAPHLAB_CORE_HPP #include <graphlab/engine/iengine.hpp> #include <graphlab/engine/engine_options.hpp> #include <graphlab/engine/engine_factory.hpp> #include <graphlab/util/command_line_options.hpp> #include <graphlab/schedulers/ischeduler.hpp> #include <graphlab/scope/iscope.hpp> #include <graphlab/graph/graph.hpp> #include <graphlab/core_base.hpp> #include <graphlab/metrics/metrics.hpp> #include <graphlab/metrics/reporters/null_reporter.hpp> #include <graphlab/metrics/reporters/basic_reporter.hpp> #include <graphlab/metrics/reporters/file_reporter.hpp> #include <graphlab/metrics/reporters/html_reporter.hpp> #include <graphlab/macros_def.hpp> namespace graphlab { // Predecleration template<typename Graph> struct types; /** \brief A GraphLab core is the base (or core) data structure in GraphLab. Because many GraphLab programs will consists of a graph and an engine we have created a single data-structure, called a core, which manages all the pieces of GraphLab including engine and scheduler construction parameters. The core is templatized over the VertexType and EdgeType however by using the ref types typedef, one can simply create a core by doing the following: \code gl::core glcore; \endcode The core contains the \li Data Graph: which represents the structured data dependencies. \li Engine: The computational structure which contains the scheduling and execution statistics for the GraphLab program. The core provides pass-through calls for many engine functions. The core also manages the engine and scheduler construction parameters. The core will invisibly recreate the engine each time engine options are modified. This will mean that this internal behavior of the core should be pretty much "transparent" for the typical use case where engine options and scheduler options are defined before tasks are added to the scheduler. Otherwise, modifications to the engine options will result in the clearing of all scheduler tasks. */ template <typename VertexType, typename EdgeType> class core : public core_base { public: typedef graphlab::types<graphlab::graph<VertexType, EdgeType> > types; typedef typename types::vertex_id vertex_id_type; typedef typename types::edge_id edge_id_type; typedef typename types::edge_list edge_list_type; public: /// default constructor does nothing core() : mengine(NULL), engine_has_been_modified(false), coremetrics("core"), reporter(new null_reporter) { } private: //! Core is not copyable core(const core& other); //! Core is not copyable core& operator=(const core& other); public: ~core() { if (meopts.get_metrics_type() != "none") { // Write options to metrics fill_metrics(); report_metrics(); } destroy_engine(); delete reporter; } /// \brief Get a modifiable reference to the graph associated with this core typename types::graph& graph() { return mgraph; } /// \brief Get a constant reference to the graph associated with this core const typename types::graph& graph() const { return mgraph; } /** * \brief Set the type of scheduler. * * This will destroy the current engine and any tasks currently * associated with the scheduler. See \ref Schedulers for the * list of supported schedulers. */ void set_scheduler_type(const std::string& scheduler_type) { check_engine_modification(); bool success = meopts.set_scheduler_type(scheduler_type); ASSERT_TRUE(success); destroy_engine(); } /** * \brief Set the scope consistency model used in this engine. * * This will destroy the current engine and any tasks associated * with the current scheduler. The available scopes are: * * \li \b "full" This ensures full data consistency within the scope * \li \b "edge" This ensures data consistency with just the * vertex and edges * \li \b "vertex" This ensures that a vertex cannot be updated * by two processors simultaneously * \li \b "none" This eliminates all locking * * See \ref Scopes for details */ void set_scope_type(const std::string& scope_type) { check_engine_modification(); bool success = meopts.set_scope_type(scope_type); ASSERT_TRUE(success); destroy_engine(); } /** * \brief Set the engine type. * * This will destroy the current engine and any tasks associated * with the current scheduler. * * \li \b "async" This is the regular multithreaded engine * \li \b "async_sim" This is a single threaded engine. But it can be * be started with multiple "simulated threads". * The simulation is low-fidelity however, and should * be used with caution. */ void set_engine_type(const std::string& engine_type) { check_engine_modification(); bool success = meopts.set_engine_type(engine_type); ASSERT_TRUE(success); destroy_engine(); } /** * \brief Sets the output format of any recorded metrics * \li \b "none" No reporting * \li \b "basic" Outputs to screen * \li \b "file" Outputs to a text file graphlab_metrics.txt * \li \b "html" Outputs to a html file graphlab_metrics.html */ void set_metrics_type(const std::string& metrics_type) { bool metrics_set_success = meopts.set_metrics_type(metrics_type); ASSERT_TRUE(metrics_set_success); delete reporter; if (meopts.get_metrics_type() == "file") { reporter = new file_reporter("graphlab_metrics.txt"); } else if (meopts.get_metrics_type() == "html") { reporter = new html_reporter("graphlab_metrics.html"); } else if (meopts.get_metrics_type() == "basic") { reporter = new basic_reporter; } else { reporter = new null_reporter; } } /** \brief Destroys a created engine (if any). */ void reset() { engine_has_been_modified = false; destroy_engine(); } /** * \brief Set the number of cpus that the engine will use. * * This will destroy the current engine and any tasks associated * with the current scheduler. * */ void set_ncpus(size_t ncpus) { check_engine_modification(); meopts.set_ncpus(ncpus); destroy_engine(); } /** * Get a reference to the active engine. If no engine exists one is * created. */ typename types::iengine& engine() { bool engine_build_success = auto_build_engine(); ASSERT_TRUE(engine_build_success); return *mengine; } /** * \brief Destroys and reconstructs the current engine, * reprocessing the engine arguments. */ bool rebuild_engine() { destroy_engine(); ASSERT_EQ(mengine, NULL); return auto_build_engine(); } /** * \brief Set the engine options by passing in an engine options object. */ void set_engine_options(const engine_options& opts) { check_engine_modification(); meopts = opts; delete reporter; if (meopts.get_metrics_type() == "file") { reporter = new file_reporter("graphlab_metrics.txt"); } else if (meopts.get_metrics_type() == "html") { reporter = new html_reporter("graphlab_metrics.html"); } else if (meopts.get_metrics_type() == "basic") { reporter = new basic_reporter; } else { reporter = new null_reporter; } } imetrics_reporter& get_reporter() { return *reporter; } /** * \brief Returns the engine options */ const engine_options& get_engine_options() const { return meopts; } /** * \brief Returns a modifiable reference to the scheduler options */ scheduler_options& sched_options() { return meopts.get_scheduler_options(); } /** * \brief Returns a constant reference to the scheduler options */ const scheduler_options& sched_options() const{ return meopts.get_scheduler_options(); } /** * \brief Set the engine options by simply parsing the command line * arguments. */ bool parse_engine_options(int argc, char **argv) { check_engine_modification(); command_line_options clopts; bool success = clopts.parse(argc, argv); if (!success) return false; set_engine_options(clopts); return true; } /** * \brief Run the engine until a termination condition is reached or * there are no more tasks remaining to execute. */ double start() { bool success = auto_build_engine(); ASSERT_TRUE(success); ASSERT_NE(mengine, NULL); // merge in options from command line and other manually set options mengine->set_scheduler_options( meopts.get_scheduler_options() ); graphlab::timer ti; ti.start(); mengine->start(); return ti.current_time(); } /** * \brief Add a single update function to a single vertex. */ void add_task(vertex_id_type vertex, typename types::update_function func, double priority) { engine_has_been_modified = true; typename types::update_task task(vertex, func); add_task(task, priority); } /** * \brief Add a single task with a fixed priority. */ void add_task(typename types::update_task task, double priority) { engine_has_been_modified = true; engine().add_task(task, priority); } /** * \brief Add the update function to all the veritces in the provided * vector with the given priority. */ void add_tasks(const std::vector<vertex_id_type>& vertices, typename types::update_function func, double priority) { engine_has_been_modified = true; engine().add_tasks(vertices, func, priority); } /** * \brief Add the given function to all vertices using the given priority */ void add_task_to_all(typename types::update_function func, double priority) { engine_has_been_modified = true; engine().add_task_to_all(func, priority); } /** * \brief Get the number of updates executed by the engine */ size_t last_update_count() { if(mengine == NULL) return 0; else return mengine->last_update_count(); } void fill_metrics() { coremetrics.set("ncpus", meopts.get_ncpus()); coremetrics.set("engine", meopts.get_engine_type()); coremetrics.set("scope", meopts.get_scope_type()); coremetrics.set("scheduler", meopts.get_scheduler_type()); coremetrics.set("affinities", meopts.get_cpu_affinities() ? "true" : "false"); coremetrics.set("schedyield", meopts.get_sched_yield() ? "true" : "false"); coremetrics.set("compile_flags", meopts.get_compile_flags()); } void reset_metrics() { coremetrics.clear(); engine().reset_metrics(); } /** \brief Outputs the recorded metrics */ void report_metrics() { coremetrics.report(get_reporter()); engine().report_metrics(get_reporter()); } /** * \brief Registers a sync with the engine. * * Registers a sync with the engine. * The sync will be performed approximately every "interval" updates, * and will perform a reduction over all vertices from rangelow * to rangehigh inclusive. * The merge function may be NULL, in which it will not be used. * However, it is highly recommended to provide a merge function since * this allow the sync operation to be parallelized. * * The sync operation is guaranteed to be strictly sequentially consistent * with all other execution. * * \param shared The shared variable to synchronize * \param sync The reduction function * \param apply The final apply function which writes to the shared value * \param zero The initial zero value passed to the reduction * \param sync_interval Frequency at which the sync is initiated. * Corresponds approximately to the number of * update function calls before the sync is reevaluated. * If 0, the sync will only be evaluated once * at engine start, and will never be evaluated again. * Defaults to 0. * \param merge Combined intermediate reduction value. defaults to NULL. * in which case, it will not be used. * \param rangelow he lower range of vertex id to start syncing. * The range is inclusive. i.e. vertex with id 'rangelow' * and vertex with id 'rangehigh' will be included. * Defaults to 0. * \param rangehigh The upper range of vertex id to stop syncing. * The range is inclusive. i.e. vertex with id 'rangelow' * and vertex with id 'rangehigh' will be included. * Defaults to infinity. */ void set_sync(glshared_base& shared, typename types::iengine::sync_function_type sync, glshared_base::apply_function_type apply, const any& zero, size_t sync_interval = 0, typename types::iengine::merge_function_type merge = NULL, vertex_id_type rangelow = 0, vertex_id_type rangehigh = -1) { engine_has_been_modified = true; engine().set_sync(shared, sync, apply, zero, sync_interval, merge, rangelow, rangehigh); } /** * Performs a sync immediately. This function requires that the shared * variable already be registered with the engine. */ void sync_now(glshared_base& shared) { engine().sync_now(shared); }; private: /** * Build the engine if it has not already been built. */ bool auto_build_engine() { if(mengine == NULL) { // create the engine mengine = engine_factory::new_engine(meopts, mgraph); if(mengine == NULL) return false; mengine->set_engine_options(meopts.get_engine_options()); } // scheduler options is one parameter that is allowed // to change without rebuilding the engine return true; } /** * Destroy the engine if one exists. */ void destroy_engine() { if(mengine != NULL) { delete mengine; mengine = NULL; } } /** Save the core to a file */ void save(const std::string& filename) const { std::ofstream fout(filename.c_str()); ASSERT_TRUE(fout.good()); oarchive oarc(fout); oarc << *this; fout.close(); } // end of save /** Save the core to an archive */ void save(oarchive& arc) const { arc << mgraph << meopts; } // end of save /** Load the core from a file. */ void load(const std::string& filename) { std::ifstream fin(filename.c_str()); ASSERT_TRUE(fin.good()); iarchive iarc(fin); iarc >> *this; fin.close(); } // end of load /** Load the core from an archive. */ void load(iarchive& arc) { arc >> mgraph >> meopts; } // end of load void check_engine_modification() { ASSERT_MSG(engine_has_been_modified == false, "Modifications to the engine/scheduler parameters are not" "allowed once tasks have been inserted into the engine."); } // graph and data objects typename types::graph mgraph; engine_options meopts; typename types::iengine *mengine; /** For error tracking. Once engine has been modified, any scheduler/ * engine parameter modifications will reset the modifications */ bool engine_has_been_modified; metrics coremetrics; imetrics_reporter* reporter; }; } #include <graphlab/macros_undef.hpp> #endif
31.760148
84
0.636691
[ "object", "vector", "model" ]
784866f6580f40704d3411717a47f3d48f9ad73c
5,484
hpp
C++
src/StringTemplate.hpp
sam-roth/autobind
df230f43335f2636fe32b370c359650391ed1ee1
[ "BSD-3-Clause" ]
1
2017-05-20T19:38:28.000Z
2017-05-20T19:38:28.000Z
src/StringTemplate.hpp
sam-roth/autobind
df230f43335f2636fe32b370c359650391ed1ee1
[ "BSD-3-Clause" ]
null
null
null
src/StringTemplate.hpp
sam-roth/autobind
df230f43335f2636fe32b370c359650391ed1ee1
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014, Samuel A. Roth. All rights reserved. // // Use of this source code is governed by a BSD-style license that can // be found in the COPYING file. #pragma once #include <string> #include <ostream> #include <sstream> #include <unordered_map> #include <memory> #include <vector> #include <typeinfo> #include <llvm/Support/raw_os_ostream.h> #include "RawIndentOstream.hpp" #include "streamindent.hpp" #include "util.hpp" #include "regex.hpp" namespace autobind { struct IStreamable { virtual void write(std::ostream &os) const = 0; virtual ~IStreamable() { } }; struct RawStreamable: public IStreamable { virtual void write(llvm::raw_ostream &os) const = 0; virtual void write(std::ostream &os) const override { llvm::raw_os_ostream ros(os); write(ros); } }; template <typename T> class StreamableWrapper: public IStreamable { T _object; public: template <class U> StreamableWrapper(U &&object) : _object(std::forward<U>(object)) { } void write(std::ostream &os) const final override { os << _object; } }; template <typename T> struct ArrayDecay { typedef typename std::remove_reference<T>::type U; typedef typename std::conditional< std::is_array<typename std::remove_cv<U>::type>::value, const typename std::remove_extent<U>::type *, U >::type type; }; template <typename T> struct RefArrayDecay { typedef typename std::remove_reference<T>::type U; typedef typename std::conditional< std::is_array<typename std::remove_cv<U>::type>::value, const typename std::remove_extent<U>::type *, const U & >::type type; }; template <typename T> std::unique_ptr<IStreamable> makeStreamable(const T &object) { return std::unique_ptr<IStreamable>(new StreamableWrapper<typename ArrayDecay<T>::type>(object)); } template <typename F> std::unique_ptr<IStreamable> functionStreamable(F function) { class FunctionStreamable: public IStreamable { F _func; public: FunctionStreamable(F func): _func(std::move(func)) {} void write(std::ostream &os) const final override { _func(os); } }; return std::unique_ptr<IStreamable>(new FunctionStreamable(std::move(function))); } class StringTemplate; struct ITemplateNamespace { virtual const IStreamable &get(const std::string &key) const = 0; virtual ~ITemplateNamespace() { } }; namespace { regex::regex templateRegex("\\{\\{(.*?)\\}\\}", regex::regex::ECMAScript); } /// @deprecated This class is unsafe to use because you must manually ensure that objects passed /// to set() outlive the namespace. /// Use StringTemplate::into() instead, which returns a template namespace with only /// private constructors, thus forcing template expansion to occur in the same statement /// as adding the values to the namespace. This means that the objects will be in scope for /// template instantiation. class SimpleTemplateNamespace: public ITemplateNamespace { std::unordered_map<std::string, std::unique_ptr<IStreamable>> _data; public: const IStreamable &get(const std::string &key) const final override { try { return *_data.at(key); } catch(std::out_of_range &) { throw std::runtime_error("No such key: " + key); } } template <typename T> SimpleTemplateNamespace &set(const std::string &key, const T &value) { _data[key] = makeStreamable(value); return *this; } template <typename F> SimpleTemplateNamespace &setFunc(const std::string &key, F func) { _data[key] = functionStreamable(std::move(func)); return *this; } }; class SafeTemplateNamespace: public SimpleTemplateNamespace { friend class StringTemplate; const StringTemplate &t; std::ostream &out; SafeTemplateNamespace(const StringTemplate &t, std::ostream &out) : t(t), out(out) { } SafeTemplateNamespace(SafeTemplateNamespace &&other) = default; public: template <typename T> SafeTemplateNamespace &set(const std::string &key, const T &value) { SimpleTemplateNamespace::set(key, value); return *this; } template <typename F> SafeTemplateNamespace &setFunc(const std::string &key, F func) { SimpleTemplateNamespace::setFunc(key, std::move(func)); return *this; } void expand() const; }; class StringTemplate { std::string _fmt; public: StringTemplate(const char *format) : _fmt(dedent(format)) { } StringTemplate(const std::string &format) : _fmt(dedent(format)) { } SafeTemplateNamespace into(std::ostream &os) const { return SafeTemplateNamespace(*this, os); } void expand(std::ostream &os, const ITemplateNamespace &ns) const { auto replacer = [&](const regex::smatch &m) { bool needsIndent = true; int index = m.position() - 1; for(; index >= 0; --index) { if(_fmt[index] == '\n') { break; } else if(!std::isspace(_fmt[index])) { needsIndent = false; break; } } ++index; std::stringstream ss; if(needsIndent && index != m.position()) { IndentingOStreambuf indenter(ss, std::string(_fmt.begin() + index, _fmt.begin() + m.position()), false); ns.get(m[1]).write(ss); } else { ns.get(m[1]).write(ss); } return ss.str(); }; auto s = regex_replace(_fmt, templateRegex, replacer); os << s; } }; inline void SafeTemplateNamespace::expand() const { t.expand(out, *this); } } // autobind
21.255814
108
0.670314
[ "object", "vector" ]
785044cd9fbe14e24432601b878c4ce2ad4ebbc8
4,301
cpp
C++
src/PriceCalculator/PriceCalculatorCross.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
17
2018-01-08T13:38:28.000Z
2022-01-21T05:39:26.000Z
src/PriceCalculator/PriceCalculatorCross.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
null
null
null
src/PriceCalculator/PriceCalculatorCross.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
1
2018-01-08T13:39:00.000Z
2018-01-08T13:39:00.000Z
/* Copyright 2017 - BSD-3-Clause * * Copyright Holder (alphabetical): * * Beikirch, Maximilian * Cramer, Simon * Frank, Martin * Otte, Philipp * Pabich, Emma * Trimborn, Torsten * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * @author Beikirch, Cramer, Pabich * @date 08 Nov 2017 * @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM */ #include <cmath> #include <cassert> #include "PriceCalculatorCross.h" /** Standardconstructor for the PriceCalculatorCross. */ PriceCalculatorCross::PriceCalculatorCross(CalculationMethod method): PriceCalculatorCross(nullptr, nullptr, nullptr, nullptr, method){ } /** Constructor for the pure-virtual PriceCalculatorCross. * Requires an ExcessDemandCalculator for the object to work properly. * \param newExcessDemandCalculator Pointer to an ExcessDemandCalculator object * \param newPrice Pointer to the Price container * \param newExcessDemand Pointer to the ExcessDemand container */ PriceCalculatorCross::PriceCalculatorCross(ExcessDemandCalculator* newExcessDemandCalculator, Price* newPrice, ExcessDemand* newExcessDemand, RandomGenerator *newRandomGenerator, CalculationMethod method): PriceCalculator(newExcessDemandCalculator, newPrice, newExcessDemand), randomGenerator(newRandomGenerator), method(method){ /// @todo Setter für theta eliminieren und stattdessen im Konstruktor setzen. theta = 2; prevExcessDemand = 0; /// @todo ACHTUNG: Wie muss der prevExcessDemand gesetzt werden? RandomInit zwischen [-1,1] ? TODO // randomGenerator->getUniformRandomDouble(-1,1,&prevExcessDemand); } /** Virtual destructor of the PriceCalculatorCross. */ PriceCalculatorCross::~PriceCalculatorCross() = default; void PriceCalculatorCross::stepCalculate(){ assert(excessDemandCalculator != nullptr); assert(excessDemand != nullptr); assert(price != nullptr); assert(randomGenerator != nullptr); double tempPrice = 0; double eta = 0; double deltaED = 0; excessDemandCalculator->stepCalculate(); randomGenerator->getNormalRandomDouble(0, sqrt(deltaT->getDeltaT()), &eta); // sqrt(deltaT) * eta aus N(0,1) deltaED = excessDemand->getExcessDemand() - prevExcessDemand; prevExcessDemand = excessDemand->getExcessDemand(); switch(method) { case ORIGINAL: tempPrice = price->getPrice() * exp( (1+theta*fabs(excessDemand->getExcessDemand()) ) * ( eta ) + marketDepth * deltaED); break; case MARTINGALE: tempPrice = price->getPrice() * exp( (1+theta*fabs(excessDemand->getExcessDemand()) ) * ( eta ) - deltaT->getDeltaT()/2 + marketDepth * deltaED); } price->setPrice(tempPrice); } void PriceCalculatorCross::preStepCalculate(){ } void PriceCalculatorCross::postStepCalculate(){ } void PriceCalculatorCross::setTheta(double theta) { this->theta = theta; }
39.1
205
0.755871
[ "object" ]
78511273b65aa75e2668613dc71e9820f07ba1d1
20,174
cpp
C++
Engine/source/sfx/sfxSound.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/sfx/sfxSound.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/sfx/sfxSound.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "sfx/sfxSound.h" #include "sfx/sfxDevice.h" #include "sfx/sfxVoice.h" #include "sfx/sfxSystem.h" #include "sfx/sfxBuffer.h" #include "sfx/sfxStream.h" #include "sfx/sfxDescription.h" #include "core/util/safeDelete.h" #include "console/engineAPI.h" //#define DEBUG_SPEW IMPLEMENT_CONOBJECT( SFXSound ); ConsoleDocClass( SFXSound, "@brief A sound controller that directly plays a single sound file.\n\n" "When playing individual audio files, SFXSounds are implicitly created by the sound system.\n\n" "Each sound source has an associated play cursor that can be queried and explicitly positioned " "by the user. The cursor is a floating-point value measured in seconds.\n\n" "For streamed sources, playback may not be continuous in case the streaming queue is interrupted.\n\n" "@note This class cannot be instantiated directly by the user but rather is implicitly created by the sound " "system when sfxCreateSource() or sfxPlayOnce() is called on a SFXProfile instance.\n\n" "@section SFXSound_virtualization Sounds and Voices\n\n" "To actually emit an audible signal, a sound must allocate a resource on the sound device through " "which the sound data is being played back. This resource is called 'voice'.\n\n" "As with other types of resources, the availability of these resources may be restricted, i.e. a given " "sound device will usually only support a fixed number of voices that are playing at the same time. Since, " "however, there may be arbitrary many SFXSounds instantiated and playing at the same time, this needs to be " "solved. \n\n" "@see SFXDescription::priority\n" "@ingroup SFX" ); //----------------------------------------------------------------------------- SFXSound::SFXSound() : mVoice( NULL ) { // NOTE: This should never be used directly // and is only here to satisfy satisfy the // construction needs of IMPLEMENT_CONOBJECT. } //----------------------------------------------------------------------------- SFXSound::SFXSound( SFXProfile *profile, SFXDescription* desc ) : Parent( profile, desc ), mVoice( NULL ) { } //----------------------------------------------------------------------------- SFXSound* SFXSound::_create( SFXDevice *device, SFXProfile *profile ) { AssertFatal( profile, "SFXSound::_create() - Got a null profile!" ); SFXDescription* desc = profile->getDescription(); if ( !desc ) { Con::errorf( "SFXSound::_create() - Profile has null description!" ); return NULL; } // Create the sound and register it. SFXSound* sound = new SFXSound( profile, desc ); sound->registerObject(); // Initialize the buffer. SFXBuffer* buffer = profile->getBuffer(); if( !buffer ) { sound->deleteObject(); Con::errorf( "SFXSound::_create() - Could not create device buffer!" ); return NULL; } sound->_setBuffer( buffer ); // The sound is a console object... register it. #ifdef DEBUG_SPEW Platform::outputDebugString( "[SFXSound] new sound '%i' with profile '%i' (\"%s\")", sound->getId(), profile->getId(), profile->getName() ); #endif // Hook up reloading. profile->getChangedSignal().notify( sound, &SFXSound::_onProfileChanged ); return sound; } //----------------------------------------------------------------------------- SFXSound* SFXSound::_create( SFXDevice* device, const ThreadSafeRef< SFXStream >& stream, SFXDescription* description ) { AssertFatal( stream.ptr() != NULL, "SFXSound::_create() - Got a null stream!" ); AssertFatal( description, "SFXSound::_create() - Got a null description!" ); // Create the source and register it. SFXSound* source = new SFXSound( NULL, description ); source->registerObject(); // Create the buffer. SFXBuffer* buffer = SFX->_createBuffer( stream, description ); if( !buffer ) { source->deleteObject(); Con::errorf( "SFXSound::_create() - Could not create device buffer!" ); return NULL; } source->_setBuffer( buffer ); #ifdef DEBUG_SPEW Platform::outputDebugString( "[SFXSound] new source '%i' for stream", source->getId() ); #endif return source; } //----------------------------------------------------------------------------- void SFXSound::_reloadBuffer() { SFXProfile* profile = getProfile(); if( profile != NULL && _releaseVoice() ) { SFXBuffer* buffer = profile->getBuffer(); if( !buffer ) { Con::errorf( "SFXSound::_reloadBuffer() - Could not create device buffer!" ); return; } _setBuffer( buffer ); if( getLastStatus() == SFXStatusPlaying ) SFX->_assignVoice( this ); } } //----------------------------------------------------------------------------- void SFXSound::_setBuffer( SFXBuffer* buffer ) { mBuffer = buffer; // There is no telling when the device will be // destroyed and the buffers deleted. // // By caching the duration now we can allow sources // to continue virtual playback until the device // is restored. mDuration = mBuffer->getDuration(); } //----------------------------------------------------------------------------- bool SFXSound::_allocVoice( SFXDevice* device ) { // We shouldn't have any existing voice! AssertFatal( !mVoice, "SFXSound::_allocVoice() - Already had a voice!" ); // Must not assign voice to source that isn't playing. AssertFatal( getLastStatus() == SFXStatusPlaying, "SFXSound::_allocVoice() - Source is not playing!" ); // The buffer can be lost when the device is reset // or changed, so initialize it if we have to. If // that fails then we cannot create the voice. if( mBuffer.isNull() ) { SFXProfile* profile = getProfile(); if( profile != NULL ) { SFXBuffer* buffer = profile->getBuffer(); if( buffer ) _setBuffer( buffer ); } if( mBuffer.isNull() ) return false; } // Ask the device for a voice based on this buffer. mVoice = device->createVoice( is3d(), mBuffer ); if( !mVoice ) return false; // Set initial properties. mVoice->setVolume( mPreAttenuatedVolume ); mVoice->setPitch( mEffectivePitch ); mVoice->setPriority( mEffectivePriority ); if( mDescription->mRolloffFactor != -1.f ) mVoice->setRolloffFactor( mDescription->mRolloffFactor ); // Set 3D parameters. if( is3d() ) { // Scatter the position, if requested. Do this only once so // we don't change position when resuming from virtualized // playback. if( !mTransformScattered ) _scatterTransform(); // Set the 3D attributes. setTransform( mTransform ); setVelocity( mVelocity ); _setMinMaxDistance( mMinDistance, mMaxDistance ); _setCone( mConeInsideAngle, mConeOutsideAngle, mConeOutsideVolume ); } // Set reverb, if enabled. if( mDescription->mUseReverb ) mVoice->setReverb( mDescription->mReverb ); // Update the duration... it shouldn't have changed, but // its probably better that we're accurate if it did. mDuration = mBuffer->getDuration(); // If virtualized playback has been started, we transfer its position to the // voice and stop virtualization. const U32 playTime = mPlayTimer.getPosition(); if( playTime > 0 ) { const U32 pos = mBuffer->getFormat().getSampleCount( playTime ); mVoice->setPosition( pos); } mVoice->play( isLooping() ); #ifdef DEBUG_SPEW Platform::outputDebugString( "[SFXSound] allocated voice for source '%i' (pos=%i, 3d=%i, vol=%f)", getId(), playTime, is3d(), mPreAttenuatedVolume ); #endif return true; } //----------------------------------------------------------------------------- void SFXSound::_onParameterEvent( SFXParameter* parameter, SFXParameterEvent event ) { Parent::_onParameterEvent( parameter, event ); switch( event ) { case SFXParameterEvent_ValueChanged: switch( parameter->getChannel() ) { case SFXChannelCursor: setPosition( parameter->getValue() * 1000.f ); break; default: break; } break; default: break; } } //----------------------------------------------------------------------------- void SFXSound::onRemove() { SFXProfile* profile = getProfile(); if( profile != NULL ) profile->getChangedSignal().remove( this, &SFXSound::_onProfileChanged ); Parent::onRemove(); } //----------------------------------------------------------------------------- void SFXSound::onDeleteNotify( SimObject* object ) { if( object == mDescription ) { deleteObject(); return; } Parent::onDeleteNotify( object ); } //----------------------------------------------------------------------------- bool SFXSound::_releaseVoice() { if( !mVoice ) return true; // Refuse to release a voice for a streaming buffer that // is not coming from a profile. For streaming buffers, we will // have to release the buffer, too, and without a profile we don't // know how to recreate the stream. if( isStreaming() && !mTrack ) return false; // If we're currently playing, transfer our playback position // to the playtimer so we can virtualize playback while not // having a voice. SFXStatus status = getLastStatus(); if( status == SFXStatusPlaying || status == SFXStatusBlocked ) { // Sync up the play timer with the voice's current position to make // sure we handle any lag that's cropped up. mPlayTimer.setPosition( mVoice->getPosition() ); if( status == SFXStatusBlocked ) status = SFXStatusPlaying; } mVoice = NULL; // If this is a streaming source, release our buffer, too. // Otherwise the voice will stick around as it is uniquely assigned to // the buffer. When we get reassigned a voice, we will have to do // a full stream seek anyway, so it's no real loss here. if( isStreaming() ) mBuffer = NULL; #ifdef DEBUG_SPEW Platform::outputDebugString( "[SFXSound] release voice for source '%i' (status: %s)", getId(), SFXStatusToString( status ) ); #endif return true; } //----------------------------------------------------------------------------- void SFXSound::_play() { Parent::_play(); if( mVoice ) mVoice->play( isLooping() ); else { // To ensure the fastest possible reaction // to this playback let the system reassign // voices immediately. SFX->_assignVoice( this ); // If we did not get assigned a voice, we'll be // running virtualized. #ifdef DEBUG_SPEW if( !mVoice ) Platform::outputDebugString( "[SFXSound] virtualizing playback of source '%i'", getId() ); #endif } } //----------------------------------------------------------------------------- void SFXSound::_stop() { Parent::_stop(); if( mVoice ) mVoice->stop(); } //----------------------------------------------------------------------------- void SFXSound::_pause() { Parent::_pause(); if( mVoice ) mVoice->pause(); } //----------------------------------------------------------------------------- void SFXSound::_updateStatus() { // If we have a voice, use its status. if( mVoice ) { SFXStatus voiceStatus = mVoice->getStatus(); // Filter out SFXStatusBlocked. if( voiceStatus == SFXStatusBlocked ) _setStatus( SFXStatusPlaying ); else _setStatus( voiceStatus ); return; } // If we're not in a playing state or we're a looping // sound then we don't need to calculate the status. if( isLooping() || mStatus != SFXStatusPlaying ) return; // If we're playing and don't have a voice we // need to decide if the sound is done playing // to ensure proper virtualization of the sound. if( mPlayTimer.getPosition() > mDuration ) { _stop(); _setStatus( SFXStatusStopped ); } } //----------------------------------------------------------------------------- void SFXSound::_updateVolume( const MatrixF& listener ) { F32 oldPreAttenuatedVolume = mPreAttenuatedVolume; Parent::_updateVolume( listener ); // If we have a voice and the pre-attenuated volume has // changed, pass it on to the voice. Attenuation itself will // happen on the device. if( mVoice != NULL && oldPreAttenuatedVolume != mPreAttenuatedVolume ) mVoice->setVolume( mPreAttenuatedVolume ); } //----------------------------------------------------------------------------- void SFXSound::_updatePitch() { F32 oldEffectivePitch = mEffectivePitch; Parent::_updatePitch(); if( mVoice != NULL && oldEffectivePitch != mEffectivePitch ) mVoice->setPitch( mEffectivePitch ); } //----------------------------------------------------------------------------- void SFXSound::_updatePriority() { F32 oldEffectivePriority = mEffectivePriority; Parent::_updatePriority(); if( mVoice != NULL && oldEffectivePriority != mEffectivePriority ) mVoice->setPriority( mEffectivePriority ); } //----------------------------------------------------------------------------- U32 SFXSound::getPosition() const { if( mVoice ) return mVoice->getFormat().getDuration( mVoice->getPosition() ); else return ( mPlayTimer.getPosition() % mDuration ); // Clamp for looped sounds. } //----------------------------------------------------------------------------- void SFXSound::setPosition( U32 ms ) { AssertFatal( ms < getDuration(), "SFXSound::setPosition() - position out of range" ); if( mVoice ) mVoice->setPosition( mVoice->getFormat().getSampleCount( ms ) ); else mPlayTimer.setPosition( ms ); } //----------------------------------------------------------------------------- void SFXSound::setVelocity( const VectorF& velocity ) { Parent::setVelocity( velocity ); if( mVoice && is3d() ) mVoice->setVelocity( velocity ); } //----------------------------------------------------------------------------- void SFXSound::setTransform( const MatrixF& transform ) { Parent::setTransform( transform ); if( mVoice && is3d() ) mVoice->setTransform( mTransform ); } //----------------------------------------------------------------------------- void SFXSound::_setMinMaxDistance( F32 min, F32 max ) { Parent::_setMinMaxDistance( min, max ); if( mVoice && is3d() ) mVoice->setMinMaxDistance( mMinDistance, mMaxDistance ); } //----------------------------------------------------------------------------- void SFXSound::_setCone( F32 innerAngle, F32 outerAngle, F32 outerVolume ) { Parent::_setCone( innerAngle, outerAngle, outerVolume ); if( mVoice && is3d() ) mVoice->setCone( mConeInsideAngle, mConeOutsideAngle, mConeOutsideVolume ); } //----------------------------------------------------------------------------- bool SFXSound::isReady() const { return ( mBuffer != NULL && mBuffer->isReady() ); } //----------------------------------------------------------------------------- bool SFXSound::isVirtualized() const { return ( ( mVoice == NULL && isPlaying() ) || ( mVoice != NULL && mVoice->isVirtual() ) ); } //----------------------------------------------------------------------------- SFXProfile* SFXSound::getProfile() const { return dynamic_cast< SFXProfile* >( mTrack.getPointer() ); } //----------------------------------------------------------------------------- F32 SFXSound::getElapsedPlayTimeCurrentCycle() const { return F32( getPosition() ) / 1000.f; } //----------------------------------------------------------------------------- F32 SFXSound::getTotalPlayTime() const { return F32( mDuration ) / 1000.f; } //----------------------------------------------------------------------------- // Let the user define a priority value for each channel // in script. We assign it in the system init and use // it when doleing out hardware handles. S32 QSORT_CALLBACK SFXSound::qsortCompare( const void* item1, const void* item2 ) { const SFXSound* source1 = *( ( SFXSound** ) item1 ); const SFXSound* source2 = *( ( SFXSound** ) item2 ); // Sounds that are playing are always sorted // closer than non-playing sounds. const bool source1IsPlaying = source1->isPlaying(); const bool source2IsPlaying = source2->isPlaying(); if( !source1IsPlaying && !source2IsPlaying ) return 0; else if( !source1IsPlaying && source2IsPlaying ) return 1; else if( source1IsPlaying && !source2IsPlaying ) return -1; // Louder attenuated volumes take precedence but adjust them // by priority so that less audible sounds with higher priority // become more important. F32 volume1 = source1->getAttenuatedVolume(); F32 volume2 = source2->getAttenuatedVolume(); volume1 += volume1 * source1->mEffectivePriority; volume2 += volume2 * source2->mEffectivePriority; if( volume1 < volume2 ) return 1; if( volume1 > volume2 ) return -1; // If we got this far then the source that was // played last has the higher priority. if( source1->mPlayStartTick > source2->mPlayStartTick ) return -1; if( source1->mPlayStartTick < source2->mPlayStartTick ) return 1; // These are sorted the same! return 0; } //============================================================================= // Console Methods. //============================================================================= // MARK: ---- Console Methods ---- //----------------------------------------------------------------------------- DefineEngineMethod( SFXSound, isReady, bool, (),, "Test whether the sound data associated with the sound has been fully loaded and is ready for playback.\n" "For streamed sounds, this will be false during playback when the stream queue for the sound is starved and " "waiting for data. For buffered sounds, only an initial loading phase will potentially cause isReady to " "return false.\n\n" "@return True if the sound is ready for playback." ) { return object->isReady(); } //----------------------------------------------------------------------------- DefineEngineMethod( SFXSound, getPosition, F32, (),, "Get the current playback position in seconds.\n" "@return The current play cursor offset." ) { return F32( object->getPosition() ) * 0.001f; } //----------------------------------------------------------------------------- DefineEngineMethod( SFXSound, setPosition, void, ( F32 position ),, "Set the current playback position in seconds.\n" "If the source is currently playing, playback will jump to the new position. If playback is stopped or paused, " "playback will resume at the given position when play() is called.\n\n" "@param position The new position of the play cursor (in seconds).\n" ) { if( position >= 0 && position <= object->getDuration() ) object->setPosition( position * 1000.0f ); } //----------------------------------------------------------------------------- DefineEngineMethod( SFXSound, getDuration, F32, (),, "Get the total play time (in seconds) of the sound data attached to the sound.\n" "@return \n\n" "@note Be aware that for looped sounds, this will not return the total playback time of the sound.\n" ) { return F32( object->getDuration() ) * 0.001f; }
29.237681
116
0.55403
[ "object", "transform", "3d" ]
78538dc7df0985310943aeb67e8a9f766c253946
136,068
hpp
C++
externals/kokkos/core/src/Kokkos_CopyViews.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
externals/kokkos/core/src/Kokkos_CopyViews.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
externals/kokkos/core/src/Kokkos_CopyViews.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef KOKKOS_COPYVIEWS_HPP_ #define KOKKOS_COPYVIEWS_HPP_ #include <string> #include <Kokkos_Parallel.hpp> #include <KokkosExp_MDRangePolicy.hpp> //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { template <class Layout> struct ViewFillLayoutSelector {}; template <> struct ViewFillLayoutSelector<Kokkos::LayoutLeft> { static const Kokkos::Iterate iterate = Kokkos::Iterate::Left; }; template <> struct ViewFillLayoutSelector<Kokkos::LayoutRight> { static const Kokkos::Iterate iterate = Kokkos::Iterate::Right; }; } // namespace Impl } // namespace Kokkos namespace Kokkos { namespace Impl { template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 0, iType> { using ST = typename ViewType::non_const_value_type; ViewFill(const ViewType& a, const ST& val, const ExecSpace& space) { Kokkos::Impl::DeepCopy<typename ViewType::memory_space, Kokkos::HostSpace, ExecSpace>(space, a.data(), &val, sizeof(ST)); } }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 1, iType> { ViewType a; typename ViewType::const_value_type val; using policy_type = Kokkos::RangePolicy<ExecSpace, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-1D", policy_type(space, 0, a.extent(0)), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i) const { a(i) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 2, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<2, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-2D", policy_type(space, {0, 0}, {a.extent(0), a.extent(1)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1) const { a(i0, i1) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 3, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<3, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for( "Kokkos::ViewFill-3D", policy_type(space, {0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2) const { a(i0, i1, i2) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 4, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<4, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for( "Kokkos::ViewFill-4D", policy_type(space, {0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3) const { a(i0, i1, i2, i3) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 5, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<5, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-5D", policy_type(space, {0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3), a.extent(4)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3, const iType& i4) const { a(i0, i1, i2, i3, i4) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 6, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<6, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-6D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3), a.extent(4), a.extent(5)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3, const iType& i4, const iType& i5) const { a(i0, i1, i2, i3, i4, i5) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 7, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<6, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-7D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3), a.extent(5), a.extent(6)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i3, const iType& i4, const iType& i5, const iType& i6) const { for (iType i2 = 0; i2 < iType(a.extent(2)); i2++) a(i0, i1, i2, i3, i4, i5, i6) = val; }; }; template <class ViewType, class Layout, class ExecSpace, typename iType> struct ViewFill<ViewType, Layout, ExecSpace, 8, iType> { ViewType a; typename ViewType::const_value_type val; using iterate_type = Kokkos::Rank<6, ViewFillLayoutSelector<Layout>::iterate, ViewFillLayoutSelector<Layout>::iterate>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewFill(const ViewType& a_, typename ViewType::const_value_type& val_, const ExecSpace& space) : a(a_), val(val_) { Kokkos::parallel_for("Kokkos::ViewFill-8D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(3), a.extent(5), a.extent(6), a.extent(7)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i3, const iType& i5, const iType& i6, const iType& i7) const { for (iType i2 = 0; i2 < iType(a.extent(2)); i2++) for (iType i4 = 0; i4 < iType(a.extent(4)); i4++) a(i0, i1, i2, i3, i4, i5, i6, i7) = val; }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 1, iType> { ViewTypeA a; ViewTypeB b; using policy_type = Kokkos::RangePolicy<ExecSpace, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-1D", policy_type(space, 0, a.extent(0)), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0) const { a(i0) = b(i0); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 2, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<2, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-2D", policy_type(space, {0, 0}, {a.extent(0), a.extent(1)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1) const { a(i0, i1) = b(i0, i1); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 3, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<3, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for( "Kokkos::ViewCopy-3D", policy_type(space, {0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2) const { a(i0, i1, i2) = b(i0, i1, i2); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 4, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<4, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for( "Kokkos::ViewCopy-4D", policy_type(space, {0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3) const { a(i0, i1, i2, i3) = b(i0, i1, i2, i3); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 5, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<5, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-5D", policy_type(space, {0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3), a.extent(4)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3, const iType& i4) const { a(i0, i1, i2, i3, i4) = b(i0, i1, i2, i3, i4); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 6, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<6, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-6D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(2), a.extent(3), a.extent(4), a.extent(5)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i2, const iType& i3, const iType& i4, const iType& i5) const { a(i0, i1, i2, i3, i4, i5) = b(i0, i1, i2, i3, i4, i5); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 7, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<6, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-7D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(3), a.extent(4), a.extent(5), a.extent(6)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i3, const iType& i4, const iType& i5, const iType& i6) const { for (iType i2 = 0; i2 < iType(a.extent(2)); i2++) a(i0, i1, i2, i3, i4, i5, i6) = b(i0, i1, i2, i3, i4, i5, i6); }; }; template <class ViewTypeA, class ViewTypeB, class Layout, class ExecSpace, typename iType> struct ViewCopy<ViewTypeA, ViewTypeB, Layout, ExecSpace, 8, iType> { ViewTypeA a; ViewTypeB b; static const Kokkos::Iterate outer_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::outer_iteration_pattern; static const Kokkos::Iterate inner_iteration_pattern = Kokkos::layout_iterate_type_selector<Layout>::inner_iteration_pattern; using iterate_type = Kokkos::Rank<6, outer_iteration_pattern, inner_iteration_pattern>; using policy_type = Kokkos::MDRangePolicy<ExecSpace, iterate_type, Kokkos::IndexType<iType>>; ViewCopy(const ViewTypeA& a_, const ViewTypeB& b_, const ExecSpace space = ExecSpace()) : a(a_), b(b_) { Kokkos::parallel_for("Kokkos::ViewCopy-8D", policy_type(space, {0, 0, 0, 0, 0, 0}, {a.extent(0), a.extent(1), a.extent(3), a.extent(5), a.extent(6), a.extent(7)}), *this); } KOKKOS_INLINE_FUNCTION void operator()(const iType& i0, const iType& i1, const iType& i3, const iType& i5, const iType& i6, const iType& i7) const { for (iType i2 = 0; i2 < iType(a.extent(2)); i2++) for (iType i4 = 0; i4 < iType(a.extent(4)); i4++) a(i0, i1, i2, i3, i4, i5, i6, i7) = b(i0, i1, i2, i3, i4, i5, i6, i7); }; }; } // namespace Impl } // namespace Kokkos namespace Kokkos { namespace Impl { template <class ExecutionSpace, class DstType, class SrcType> void view_copy(const ExecutionSpace& space, const DstType& dst, const SrcType& src) { using dst_memory_space = typename DstType::memory_space; using src_memory_space = typename SrcType::memory_space; enum { ExecCanAccessSrc = Kokkos::Impl::SpaceAccessibility<ExecutionSpace, src_memory_space>::accessible }; enum { ExecCanAccessDst = Kokkos::Impl::SpaceAccessibility<ExecutionSpace, dst_memory_space>::accessible }; if (!(ExecCanAccessSrc && ExecCanAccessDst)) { Kokkos::Impl::throw_runtime_exception( "Kokkos::Impl::view_copy called with invalid execution space"); } else { // Figure out iteration order in case we need it int64_t strides[DstType::Rank + 1]; dst.stride(strides); Kokkos::Iterate iterate; if (Kokkos::is_layouttiled<typename DstType::array_layout>::value) { iterate = Kokkos::layout_iterate_type_selector< typename DstType::array_layout>::outer_iteration_pattern; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutRight>::value) { iterate = Kokkos::Iterate::Right; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutLeft>::value) { iterate = Kokkos::Iterate::Left; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutStride>::value) { if (strides[0] > strides[DstType::Rank - 1]) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } else { if (std::is_same<typename DstType::execution_space::array_layout, Kokkos::LayoutRight>::value) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } if ((dst.span() >= size_t(std::numeric_limits<int>::max())) || (src.span() >= size_t(std::numeric_limits<int>::max()))) { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, ExecutionSpace, DstType::Rank, int64_t>( dst, src, space); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, ExecutionSpace, DstType::Rank, int64_t>( dst, src, space); } else { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, ExecutionSpace, DstType::Rank, int>(dst, src, space); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, ExecutionSpace, DstType::Rank, int>(dst, src, space); } } } template <class DstType, class SrcType> void view_copy(const DstType& dst, const SrcType& src) { using dst_execution_space = typename DstType::execution_space; using src_execution_space = typename SrcType::execution_space; using dst_memory_space = typename DstType::memory_space; using src_memory_space = typename SrcType::memory_space; enum { DstExecCanAccessSrc = Kokkos::Impl::SpaceAccessibility<dst_execution_space, src_memory_space>::accessible }; enum { SrcExecCanAccessDst = Kokkos::Impl::SpaceAccessibility<src_execution_space, dst_memory_space>::accessible }; if (!DstExecCanAccessSrc && !SrcExecCanAccessDst) { std::string message( "Error: Kokkos::deep_copy with no available copy mechanism: "); message += src.label(); message += " to "; message += dst.label(); Kokkos::Impl::throw_runtime_exception(message); } // Figure out iteration order in case we need it int64_t strides[DstType::Rank + 1]; dst.stride(strides); Kokkos::Iterate iterate; if (Kokkos::is_layouttiled<typename DstType::array_layout>::value) { iterate = Kokkos::layout_iterate_type_selector< typename DstType::array_layout>::outer_iteration_pattern; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutRight>::value) { iterate = Kokkos::Iterate::Right; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutLeft>::value) { iterate = Kokkos::Iterate::Left; } else if (std::is_same<typename DstType::array_layout, Kokkos::LayoutStride>::value) { if (strides[0] > strides[DstType::Rank - 1]) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } else { if (std::is_same<typename DstType::execution_space::array_layout, Kokkos::LayoutRight>::value) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } if ((dst.span() >= size_t(std::numeric_limits<int>::max())) || (src.span() >= size_t(std::numeric_limits<int>::max()))) { if (DstExecCanAccessSrc) { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, dst_execution_space, DstType::Rank, int64_t>( dst, src); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, dst_execution_space, DstType::Rank, int64_t>( dst, src); } else { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, src_execution_space, DstType::Rank, int64_t>( dst, src); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, src_execution_space, DstType::Rank, int64_t>( dst, src); } } else { if (DstExecCanAccessSrc) { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, dst_execution_space, DstType::Rank, int>(dst, src); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, dst_execution_space, DstType::Rank, int>(dst, src); } else { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutRight, src_execution_space, DstType::Rank, int>(dst, src); else Kokkos::Impl::ViewCopy< typename DstType::uniform_runtime_nomemspace_type, typename SrcType::uniform_runtime_const_nomemspace_type, Kokkos::LayoutLeft, src_execution_space, DstType::Rank, int>(dst, src); } } } template <class DstType, class SrcType, int Rank, class... Args> struct CommonSubview; template <class DstType, class SrcType, class Arg0, class... Args> struct CommonSubview<DstType, SrcType, 1, Arg0, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, Args...) : dst_sub(dst, arg0), src_sub(src, arg0) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class... Args> struct CommonSubview<DstType, SrcType, 2, Arg0, Arg1, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, Args...) : dst_sub(dst, arg0, arg1), src_sub(src, arg0, arg1) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class... Args> struct CommonSubview<DstType, SrcType, 3, Arg0, Arg1, Arg2, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, Args...) : dst_sub(dst, arg0, arg1, arg2), src_sub(src, arg0, arg1, arg2) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class Arg3, class... Args> struct CommonSubview<DstType, SrcType, 4, Arg0, Arg1, Arg2, Arg3, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2, Arg3>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2, Arg3>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Args...) : dst_sub(dst, arg0, arg1, arg2, arg3), src_sub(src, arg0, arg1, arg2, arg3) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class Arg3, class Arg4, class... Args> struct CommonSubview<DstType, SrcType, 5, Arg0, Arg1, Arg2, Arg3, Arg4, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2, Arg3, Arg4>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2, Arg3, Arg4>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Args...) : dst_sub(dst, arg0, arg1, arg2, arg3, arg4), src_sub(src, arg0, arg1, arg2, arg3, arg4) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class... Args> struct CommonSubview<DstType, SrcType, 6, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Args...) : dst_sub(dst, arg0, arg1, arg2, arg3, arg4, arg5), src_sub(src, arg0, arg1, arg2, arg3, arg4, arg5) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class... Args> struct CommonSubview<DstType, SrcType, 7, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Args...> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, Args...) : dst_sub(dst, arg0, arg1, arg2, arg3, arg4, arg5, arg6), src_sub(src, arg0, arg1, arg2, arg3, arg4, arg5, arg6) {} }; template <class DstType, class SrcType, class Arg0, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7> struct CommonSubview<DstType, SrcType, 8, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7> { using dst_subview_type = typename Kokkos::Subview<DstType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>; using src_subview_type = typename Kokkos::Subview<SrcType, Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>; dst_subview_type dst_sub; src_subview_type src_sub; CommonSubview(const DstType& dst, const SrcType& src, const Arg0& arg0, const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7) : dst_sub(dst, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7), src_sub(src, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {} }; template <class DstType, class SrcType, class ExecSpace = typename DstType::execution_space, int Rank = DstType::Rank> struct ViewRemap; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 1> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { view_copy(dst, src); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); using sv_adapter_type = CommonSubview<DstType, SrcType, 1, p_type>; sv_adapter_type common_subview(dst, src, ext0); view_copy(common_subview.dst_sub, common_subview.src_sub); } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 2> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(1) == src.extent(1)) { view_copy(dst, src); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); using sv_adapter_type = CommonSubview<DstType, SrcType, 2, Kokkos::Impl::ALL_t, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(1) == src.extent(1)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); using sv_adapter_type = CommonSubview<DstType, SrcType, 2, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); using sv_adapter_type = CommonSubview<DstType, SrcType, 2, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 3> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(2) == src.extent(2)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); using sv_adapter_type = CommonSubview<DstType, SrcType, 3, Kokkos::Impl::ALL_t, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); using sv_adapter_type = CommonSubview<DstType, SrcType, 3, Kokkos::Impl::ALL_t, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(2) == src.extent(2)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); using sv_adapter_type = CommonSubview<DstType, SrcType, 3, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); using sv_adapter_type = CommonSubview<DstType, SrcType, 3, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 4> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(3) == src.extent(3)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); using sv_adapter_type = CommonSubview<DstType, SrcType, 4, Kokkos::Impl::ALL_t, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); using sv_adapter_type = CommonSubview<DstType, SrcType, 4, Kokkos::Impl::ALL_t, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(7) == src.extent(7)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); using sv_adapter_type = CommonSubview<DstType, SrcType, 4, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); using sv_adapter_type = CommonSubview<DstType, SrcType, 4, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 5> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(4) == src.extent(4)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); using sv_adapter_type = CommonSubview<DstType, SrcType, 5, Kokkos::Impl::ALL_t, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); using sv_adapter_type = CommonSubview<DstType, SrcType, 5, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(4) == src.extent(4)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); using sv_adapter_type = CommonSubview<DstType, SrcType, 5, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); using sv_adapter_type = CommonSubview<DstType, SrcType, 5, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 6> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(5) == src.extent(5)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); using sv_adapter_type = CommonSubview<DstType, SrcType, 6, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); using sv_adapter_type = CommonSubview<DstType, SrcType, 6, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, ext5); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(5) == src.extent(5)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); using sv_adapter_type = CommonSubview<DstType, SrcType, 6, p_type, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); using sv_adapter_type = CommonSubview<DstType, SrcType, 6, p_type, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, ext5); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 7> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(6) == src.extent(6)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); using sv_adapter_type = CommonSubview<DstType, SrcType, 7, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, ext5, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); using sv_adapter_type = CommonSubview<DstType, SrcType, 7, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, ext5, ext6); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(6) == src.extent(6)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); using sv_adapter_type = CommonSubview<DstType, SrcType, 7, p_type, p_type, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, ext5, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); using sv_adapter_type = CommonSubview<DstType, SrcType, 7, p_type, p_type, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, ext5, ext6); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; template <class DstType, class SrcType, class ExecSpace> struct ViewRemap<DstType, SrcType, ExecSpace, 8> { using p_type = Kokkos::pair<int64_t, int64_t>; ViewRemap(const DstType& dst, const SrcType& src) { if (dst.extent(0) == src.extent(0)) { if (dst.extent(7) == src.extent(7)) { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); using sv_adapter_type = CommonSubview<DstType, SrcType, 8, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, ext5, ext6, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); p_type ext7(0, std::min(dst.extent(7), src.extent(7))); using sv_adapter_type = CommonSubview<DstType, SrcType, 8, Kokkos::Impl::ALL_t, p_type, p_type, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, Kokkos::ALL, ext1, ext2, ext3, ext4, ext5, ext6, ext7); view_copy(common_subview.dst_sub, common_subview.src_sub); } } else { if (dst.extent(7) == src.extent(7)) { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); using sv_adapter_type = CommonSubview<DstType, SrcType, 8, p_type, p_type, p_type, p_type, p_type, p_type, p_type, Kokkos::Impl::ALL_t>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, ext5, ext6, Kokkos::ALL); view_copy(common_subview.dst_sub, common_subview.src_sub); } else { p_type ext0(0, std::min(dst.extent(0), src.extent(0))); p_type ext1(0, std::min(dst.extent(1), src.extent(1))); p_type ext2(0, std::min(dst.extent(2), src.extent(2))); p_type ext3(0, std::min(dst.extent(3), src.extent(3))); p_type ext4(0, std::min(dst.extent(4), src.extent(4))); p_type ext5(0, std::min(dst.extent(5), src.extent(5))); p_type ext6(0, std::min(dst.extent(6), src.extent(6))); p_type ext7(0, std::min(dst.extent(7), src.extent(7))); using sv_adapter_type = CommonSubview<DstType, SrcType, 8, p_type, p_type, p_type, p_type, p_type, p_type, p_type, p_type>; sv_adapter_type common_subview(dst, src, ext0, ext1, ext2, ext3, ext4, ext5, ext6, ext7); view_copy(common_subview.dst_sub, common_subview.src_sub); } } } }; } // namespace Impl /** \brief Deep copy a value from Host memory into a view. */ template <class DT, class... DP> inline void deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<std::is_same< typename ViewTraits<DT, DP...>::specialize, void>::value>::type* = nullptr) { using ViewType = View<DT, DP...>; using exec_space_type = typename ViewType::execution_space; if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(ViewType::memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(Kokkos::HostSpace::name()), "Scalar", &value, dst.span() * sizeof(typename ViewType::value_type)); } if (dst.data() == nullptr) { Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } Kokkos::fence(); static_assert(std::is_same<typename ViewType::non_const_value_type, typename ViewType::value_type>::value, "deep_copy requires non-const type"); // If contiguous we can simply do a 1D flat loop if (dst.span_is_contiguous()) { using ViewTypeFlat = Kokkos::View< typename ViewType::value_type*, Kokkos::LayoutRight, Kokkos::Device<typename ViewType::execution_space, typename std::conditional< ViewType::Rank == 0, typename ViewType::memory_space, Kokkos::AnonymousSpace>::type>, Kokkos::MemoryTraits<0>>; ViewTypeFlat dst_flat(dst.data(), dst.size()); if (dst.span() < static_cast<size_t>(std::numeric_limits<int>::max())) { Kokkos::Impl::ViewFill<ViewTypeFlat, Kokkos::LayoutRight, exec_space_type, ViewTypeFlat::Rank, int>(dst_flat, value, exec_space_type()); } else Kokkos::Impl::ViewFill<ViewTypeFlat, Kokkos::LayoutRight, exec_space_type, ViewTypeFlat::Rank, int64_t>(dst_flat, value, exec_space_type()); Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } // Figure out iteration order to do the ViewFill int64_t strides[ViewType::Rank + 1]; dst.stride(strides); Kokkos::Iterate iterate; if (std::is_same<typename ViewType::array_layout, Kokkos::LayoutRight>::value) { iterate = Kokkos::Iterate::Right; } else if (std::is_same<typename ViewType::array_layout, Kokkos::LayoutLeft>::value) { iterate = Kokkos::Iterate::Left; } else if (std::is_same<typename ViewType::array_layout, Kokkos::LayoutStride>::value) { if (strides[0] > strides[ViewType::Rank > 0 ? ViewType::Rank - 1 : 0]) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } else { if (std::is_same<typename ViewType::execution_space::array_layout, Kokkos::LayoutRight>::value) iterate = Kokkos::Iterate::Right; else iterate = Kokkos::Iterate::Left; } // Lets call the right ViewFill functor based on integer space needed and // iteration type using ViewTypeUniform = typename std::conditional< ViewType::Rank == 0, typename ViewType::uniform_runtime_type, typename ViewType::uniform_runtime_nomemspace_type>::type; if (dst.span() > static_cast<size_t>(std::numeric_limits<int>::max())) { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewFill<ViewTypeUniform, Kokkos::LayoutRight, exec_space_type, ViewType::Rank, int64_t>( dst, value, exec_space_type()); else Kokkos::Impl::ViewFill<ViewTypeUniform, Kokkos::LayoutLeft, exec_space_type, ViewType::Rank, int64_t>( dst, value, exec_space_type()); } else { if (iterate == Kokkos::Iterate::Right) Kokkos::Impl::ViewFill<ViewTypeUniform, Kokkos::LayoutRight, exec_space_type, ViewType::Rank, int>( dst, value, exec_space_type()); else Kokkos::Impl::ViewFill<ViewTypeUniform, Kokkos::LayoutLeft, exec_space_type, ViewType::Rank, int>( dst, value, exec_space_type()); } Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } /** \brief Deep copy into a value in Host memory from a view. */ template <class ST, class... SP> inline void deep_copy( typename ViewTraits<ST, SP...>::non_const_value_type& dst, const View<ST, SP...>& src, typename std::enable_if<std::is_same< typename ViewTraits<ST, SP...>::specialize, void>::value>::type* = nullptr) { using src_traits = ViewTraits<ST, SP...>; using src_memory_space = typename src_traits::memory_space; static_assert(src_traits::rank == 0, "ERROR: Non-rank-zero view in deep_copy( value , View )"); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(Kokkos::HostSpace::name()), "Scalar", &dst, Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), src.span() * sizeof(typename src_traits::value_type)); } if (src.data() == nullptr) { Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } Kokkos::Impl::DeepCopy<HostSpace, src_memory_space>(&dst, src.data(), sizeof(ST)); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } //---------------------------------------------------------------------------- /** \brief A deep copy between views of compatible type, and rank zero. */ template <class DT, class... DP, class ST, class... SP> inline void deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<( std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && std::is_same<typename ViewTraits<ST, SP...>::specialize, void>::value && (unsigned(ViewTraits<DT, DP...>::rank) == unsigned(0) && unsigned(ViewTraits<ST, SP...>::rank) == unsigned(0)))>::type* = nullptr) { using dst_type = View<DT, DP...>; using src_type = View<ST, SP...>; using value_type = typename dst_type::value_type; using dst_memory_space = typename dst_type::memory_space; using src_memory_space = typename src_type::memory_space; static_assert(std::is_same<typename dst_type::value_type, typename src_type::non_const_value_type>::value, "deep_copy requires matching non-const destination type"); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), src.span() * sizeof(typename dst_type::value_type)); } if (dst.data() == nullptr && src.data() == nullptr) { Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } Kokkos::fence(); if (dst.data() != src.data()) { Kokkos::Impl::DeepCopy<dst_memory_space, src_memory_space>( dst.data(), src.data(), sizeof(value_type)); Kokkos::fence(); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } //---------------------------------------------------------------------------- /** \brief A deep copy between views of the default specialization, compatible * type, same non-zero rank, same contiguous layout. */ template <class DT, class... DP, class ST, class... SP> inline void deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<( std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && std::is_same<typename ViewTraits<ST, SP...>::specialize, void>::value && (unsigned(ViewTraits<DT, DP...>::rank) != 0 || unsigned(ViewTraits<ST, SP...>::rank) != 0))>::type* = nullptr) { using dst_type = View<DT, DP...>; using src_type = View<ST, SP...>; using dst_execution_space = typename dst_type::execution_space; using src_execution_space = typename src_type::execution_space; using dst_memory_space = typename dst_type::memory_space; using src_memory_space = typename src_type::memory_space; using dst_value_type = typename dst_type::value_type; using src_value_type = typename src_type::value_type; static_assert(std::is_same<typename dst_type::value_type, typename dst_type::non_const_value_type>::value, "deep_copy requires non-const destination type"); static_assert((unsigned(dst_type::rank) == unsigned(src_type::rank)), "deep_copy requires Views of equal rank"); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), src.span() * sizeof(typename dst_type::value_type)); } if (dst.data() == nullptr || src.data() == nullptr) { // throw if dimension mismatch if ((src.extent(0) != dst.extent(0)) || (src.extent(1) != dst.extent(1)) || (src.extent(2) != dst.extent(2)) || (src.extent(3) != dst.extent(3)) || (src.extent(4) != dst.extent(4)) || (src.extent(5) != dst.extent(5)) || (src.extent(6) != dst.extent(6)) || (src.extent(7) != dst.extent(7))) { std::string message( "Deprecation Error: Kokkos::deep_copy extents of views don't " "match: "); message += dst.label(); message += "("; for (int r = 0; r < dst_type::Rank - 1; r++) { message += std::to_string(dst.extent(r)); message += ","; } message += std::to_string(dst.extent(dst_type::Rank - 1)); message += ") "; message += src.label(); message += "("; for (int r = 0; r < src_type::Rank - 1; r++) { message += std::to_string(src.extent(r)); message += ","; } message += std::to_string(src.extent(src_type::Rank - 1)); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } enum { DstExecCanAccessSrc = Kokkos::Impl::SpaceAccessibility<dst_execution_space, src_memory_space>::accessible }; enum { SrcExecCanAccessDst = Kokkos::Impl::SpaceAccessibility<src_execution_space, dst_memory_space>::accessible }; // Checking for Overlapping Views. dst_value_type* dst_start = dst.data(); dst_value_type* dst_end = dst.data() + dst.span(); src_value_type* src_start = src.data(); src_value_type* src_end = src.data() + src.span(); if (((std::ptrdiff_t)dst_start == (std::ptrdiff_t)src_start) && ((std::ptrdiff_t)dst_end == (std::ptrdiff_t)src_end) && (dst.span_is_contiguous() && src.span_is_contiguous())) { Kokkos::fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } if ((((std::ptrdiff_t)dst_start < (std::ptrdiff_t)src_end) && ((std::ptrdiff_t)dst_end > (std::ptrdiff_t)src_start)) && ((dst.span_is_contiguous() && src.span_is_contiguous()))) { std::string message("Error: Kokkos::deep_copy of overlapping views: "); message += dst.label(); message += "("; message += std::to_string((std::ptrdiff_t)dst_start); message += ","; message += std::to_string((std::ptrdiff_t)dst_end); message += ") "; message += src.label(); message += "("; message += std::to_string((std::ptrdiff_t)src_start); message += ","; message += std::to_string((std::ptrdiff_t)src_end); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } // Check for same extents if ((src.extent(0) != dst.extent(0)) || (src.extent(1) != dst.extent(1)) || (src.extent(2) != dst.extent(2)) || (src.extent(3) != dst.extent(3)) || (src.extent(4) != dst.extent(4)) || (src.extent(5) != dst.extent(5)) || (src.extent(6) != dst.extent(6)) || (src.extent(7) != dst.extent(7))) { std::string message( "Deprecation Error: Kokkos::deep_copy extents of views don't match: "); message += dst.label(); message += "("; for (int r = 0; r < dst_type::Rank - 1; r++) { message += std::to_string(dst.extent(r)); message += ","; } message += std::to_string(dst.extent(dst_type::Rank - 1)); message += ") "; message += src.label(); message += "("; for (int r = 0; r < src_type::Rank - 1; r++) { message += std::to_string(src.extent(r)); message += ","; } message += std::to_string(src.extent(src_type::Rank - 1)); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } // If same type, equal layout, equal dimensions, equal span, and contiguous // memory then can byte-wise copy if (std::is_same<typename dst_type::value_type, typename src_type::non_const_value_type>::value && (std::is_same<typename dst_type::array_layout, typename src_type::array_layout>::value || (dst_type::rank == 1 && src_type::rank == 1)) && dst.span_is_contiguous() && src.span_is_contiguous() && ((dst_type::rank < 1) || (dst.stride_0() == src.stride_0())) && ((dst_type::rank < 2) || (dst.stride_1() == src.stride_1())) && ((dst_type::rank < 3) || (dst.stride_2() == src.stride_2())) && ((dst_type::rank < 4) || (dst.stride_3() == src.stride_3())) && ((dst_type::rank < 5) || (dst.stride_4() == src.stride_4())) && ((dst_type::rank < 6) || (dst.stride_5() == src.stride_5())) && ((dst_type::rank < 7) || (dst.stride_6() == src.stride_6())) && ((dst_type::rank < 8) || (dst.stride_7() == src.stride_7()))) { const size_t nbytes = sizeof(typename dst_type::value_type) * dst.span(); Kokkos::fence(); if ((void*)dst.data() != (void*)src.data()) { Kokkos::Impl::DeepCopy<dst_memory_space, src_memory_space>( dst.data(), src.data(), nbytes); Kokkos::fence(); } } else { Kokkos::fence(); Impl::view_copy(dst, src); Kokkos::fence(); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Experimental { /** \brief A local deep copy between views of the default specialization, * compatible type, same non-zero rank. */ template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy_contiguous(const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src) { Kokkos::parallel_for(Kokkos::TeamThreadRange(team, src.span()), [&](const int& i) { dst.data()[i] = src.data()[i]; }); } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy_contiguous( const View<DT, DP...>& dst, const View<ST, SP...>& src) { for (size_t i = 0; i < src.span(); ++i) { dst.data()[i] = src.data()[i]; } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 1 && unsigned(ViewTraits<ST, SP...>::rank) == 1)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0); team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { dst(i) = src(i); }); team.team_barrier(); } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 2 && unsigned(ViewTraits<ST, SP...>::rank) == 2)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int i1 = i / dst.extent(0); dst(i0, i1) = src(i0, i1); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 3 && unsigned(ViewTraits<ST, SP...>::rank) == 3)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); int i2 = itmp / dst.extent(1); dst(i0, i1, i2) = src(i0, i1, i2); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 4 && unsigned(ViewTraits<ST, SP...>::rank) == 4)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); int i3 = itmp / dst.extent(2); dst(i0, i1, i2, i3) = src(i0, i1, i2, i3); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 5 && unsigned(ViewTraits<ST, SP...>::rank) == 5)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); int i4 = itmp / dst.extent(3); dst(i0, i1, i2, i3, i4) = src(i0, i1, i2, i3, i4); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 6 && unsigned(ViewTraits<ST, SP...>::rank) == 6)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4) * dst.extent(5); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); itmp = itmp / dst.extent(3); int i4 = itmp % dst.extent(4); int i5 = itmp / dst.extent(4); dst(i0, i1, i2, i3, i4, i5) = src(i0, i1, i2, i3, i4, i5); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 7 && unsigned(ViewTraits<ST, SP...>::rank) == 7)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4) * dst.extent(5) * dst.extent(6); if (dst.span_is_contiguous() && src.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, src); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); itmp = itmp / dst.extent(3); int i4 = itmp % dst.extent(4); itmp = itmp / dst.extent(4); int i5 = itmp % dst.extent(5); int i6 = itmp / dst.extent(5); dst(i0, i1, i2, i3, i4, i5, i6) = src(i0, i1, i2, i3, i4, i5, i6); }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 1 && unsigned(ViewTraits<ST, SP...>::rank) == 1)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0); for (size_t i = 0; i < N; ++i) { dst(i) = src(i); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 2 && unsigned(ViewTraits<ST, SP...>::rank) == 2)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) dst(i0, i1) = src(i0, i1); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 3 && unsigned(ViewTraits<ST, SP...>::rank) == 3)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) dst(i0, i1, i2) = src(i0, i1, i2); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 4 && unsigned(ViewTraits<ST, SP...>::rank) == 4)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) dst(i0, i1, i2, i3) = src(i0, i1, i2, i3); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 5 && unsigned(ViewTraits<ST, SP...>::rank) == 5)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) dst(i0, i1, i2, i3, i4) = src(i0, i1, i2, i3, i4); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 6 && unsigned(ViewTraits<ST, SP...>::rank) == 6)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) for (size_t i5 = 0; i5 < dst.extent(5); ++i5) dst(i0, i1, i2, i3, i4, i5) = src(i0, i1, i2, i3, i4, i5); } } //---------------------------------------------------------------------------- template <class DT, class... DP, class ST, class... SP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 7 && unsigned(ViewTraits<ST, SP...>::rank) == 7)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous() && src.span_is_contiguous()) { local_deep_copy_contiguous(dst, src); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) for (size_t i5 = 0; i5 < dst.extent(5); ++i5) for (size_t i6 = 0; i6 < dst.extent(6); ++i6) dst(i0, i1, i2, i3, i4, i5, i6) = src(i0, i1, i2, i3, i4, i5, i6); } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- /** \brief Deep copy a value into a view. */ template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy_contiguous( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value) { Kokkos::parallel_for(Kokkos::TeamThreadRange(team, dst.span()), [&](const int& i) { dst.data()[i] = value; }); } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy_contiguous( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value) { for (size_t i = 0; i < dst.span(); ++i) { dst.data()[i] = value; } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 1)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0); team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { dst(i) = value; }); team.team_barrier(); } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 2)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int i1 = i / dst.extent(0); dst(i0, i1) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 3)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); int i2 = itmp / dst.extent(1); dst(i0, i1, i2) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 4)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); int i3 = itmp / dst.extent(2); dst(i0, i1, i2, i3) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 5)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); int i4 = itmp / dst.extent(3); dst(i0, i1, i2, i3, i4) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 6)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4) * dst.extent(5); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); itmp = itmp / dst.extent(3); int i4 = itmp % dst.extent(4); int i5 = itmp / dst.extent(4); dst(i0, i1, i2, i3, i4, i5) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class TeamType, class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const TeamType& team, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 7)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0) * dst.extent(1) * dst.extent(2) * dst.extent(3) * dst.extent(4) * dst.extent(5) * dst.extent(6); if (dst.span_is_contiguous()) { team.team_barrier(); local_deep_copy_contiguous(team, dst, value); team.team_barrier(); } else { team.team_barrier(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team, N), [&](const int& i) { int i0 = i % dst.extent(0); int itmp = i / dst.extent(0); int i1 = itmp % dst.extent(1); itmp = itmp / dst.extent(1); int i2 = itmp % dst.extent(2); itmp = itmp / dst.extent(2); int i3 = itmp % dst.extent(3); itmp = itmp / dst.extent(3); int i4 = itmp % dst.extent(4); itmp = itmp / dst.extent(4); int i5 = itmp % dst.extent(5); int i6 = itmp / dst.extent(5); dst(i0, i1, i2, i3, i4, i5, i6) = value; }); team.team_barrier(); } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 1)>::type* = nullptr) { if (dst.data() == nullptr) { return; } const size_t N = dst.extent(0); for (size_t i = 0; i < N; ++i) { dst(i) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 2)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) dst(i0, i1) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 3)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) dst(i0, i1, i2) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 4)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) dst(i0, i1, i2, i3) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 5)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) dst(i0, i1, i2, i3, i4) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 6)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) for (size_t i5 = 0; i5 < dst.extent(5); ++i5) dst(i0, i1, i2, i3, i4, i5) = value; } } //---------------------------------------------------------------------------- template <class DT, class... DP> void KOKKOS_INLINE_FUNCTION local_deep_copy( const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if<(unsigned(ViewTraits<DT, DP...>::rank) == 7)>::type* = nullptr) { if (dst.data() == nullptr) { return; } if (dst.span_is_contiguous()) { local_deep_copy_contiguous(dst, value); } else { for (size_t i0 = 0; i0 < dst.extent(0); ++i0) for (size_t i1 = 0; i1 < dst.extent(1); ++i1) for (size_t i2 = 0; i2 < dst.extent(2); ++i2) for (size_t i3 = 0; i3 < dst.extent(3); ++i3) for (size_t i4 = 0; i4 < dst.extent(4); ++i4) for (size_t i5 = 0; i5 < dst.extent(5); ++i5) for (size_t i6 = 0; i6 < dst.extent(6); ++i6) dst(i0, i1, i2, i3, i4, i5, i6) = value; } } } /* namespace Experimental */ } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { /** \brief Deep copy a value from Host memory into a view. ExecSpace can access * dst */ template <class ExecSpace, class DT, class... DP> inline void deep_copy( const ExecSpace& space, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if< Kokkos::Impl::is_execution_space<ExecSpace>::value && std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && Kokkos::Impl::SpaceAccessibility< ExecSpace, typename ViewTraits<DT, DP...>::memory_space>::accessible>::type* = nullptr) { using dst_traits = ViewTraits<DT, DP...>; static_assert(std::is_same<typename dst_traits::non_const_value_type, typename dst_traits::value_type>::value, "deep_copy requires non-const type"); using dst_memory_space = typename dst_traits::memory_space; if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(Kokkos::HostSpace::name()), "(none)", &value, dst.span() * sizeof(typename dst_traits::value_type)); } if (dst.data() == nullptr) { space.fence(); } else { using ViewTypeUniform = typename std::conditional< View<DT, DP...>::Rank == 0, typename View<DT, DP...>::uniform_runtime_type, typename View<DT, DP...>::uniform_runtime_nomemspace_type>::type; Kokkos::Impl::ViewFill<ViewTypeUniform, typename dst_traits::array_layout, ExecSpace>(dst, value, space); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } /** \brief Deep copy a value from Host memory into a view. ExecSpace can not * access dst */ template <class ExecSpace, class DT, class... DP> inline void deep_copy( const ExecSpace& space, const View<DT, DP...>& dst, typename ViewTraits<DT, DP...>::const_value_type& value, typename std::enable_if< Kokkos::Impl::is_execution_space<ExecSpace>::value && std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && !Kokkos::Impl::SpaceAccessibility< ExecSpace, typename ViewTraits<DT, DP...>::memory_space>::accessible>::type* = nullptr) { using dst_traits = ViewTraits<DT, DP...>; static_assert(std::is_same<typename dst_traits::non_const_value_type, typename dst_traits::value_type>::value, "deep_copy requires non-const type"); using dst_memory_space = typename dst_traits::memory_space; if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(Kokkos::HostSpace::name()), "(none)", &value, dst.span() * sizeof(typename dst_traits::value_type)); } if (dst.data() == nullptr) { space.fence(); } else { space.fence(); using ViewTypeUniform = typename std::conditional< View<DT, DP...>::Rank == 0, typename View<DT, DP...>::uniform_runtime_type, typename View<DT, DP...>::uniform_runtime_nomemspace_type>::type; using fill_exec_space = typename dst_traits::memory_space::execution_space; Kokkos::Impl::ViewFill<ViewTypeUniform, typename dst_traits::array_layout, fill_exec_space>(dst, value, fill_exec_space()); fill_exec_space().fence(); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } /** \brief Deep copy into a value in Host memory from a view. */ template <class ExecSpace, class ST, class... SP> inline void deep_copy( const ExecSpace& exec_space, typename ViewTraits<ST, SP...>::non_const_value_type& dst, const View<ST, SP...>& src, typename std::enable_if< Kokkos::Impl::is_execution_space<ExecSpace>::value && std::is_same<typename ViewTraits<ST, SP...>::specialize, void>::value>::type* = 0) { using src_traits = ViewTraits<ST, SP...>; using src_memory_space = typename src_traits::memory_space; static_assert(src_traits::rank == 0, "ERROR: Non-rank-zero view in deep_copy( value , View )"); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(Kokkos::HostSpace::name()), "(none)", &dst, Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), sizeof(ST)); } if (src.data() == nullptr) { exec_space.fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } Kokkos::Impl::DeepCopy<HostSpace, src_memory_space, ExecSpace>( exec_space, &dst, src.data(), sizeof(ST)); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } //---------------------------------------------------------------------------- /** \brief A deep copy between views of compatible type, and rank zero. */ template <class ExecSpace, class DT, class... DP, class ST, class... SP> inline void deep_copy( const ExecSpace& exec_space, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<( Kokkos::Impl::is_execution_space<ExecSpace>::value && std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && std::is_same<typename ViewTraits<ST, SP...>::specialize, void>::value && (unsigned(ViewTraits<DT, DP...>::rank) == unsigned(0) && unsigned(ViewTraits<ST, SP...>::rank) == unsigned(0)))>::type* = nullptr) { using src_traits = ViewTraits<ST, SP...>; using dst_traits = ViewTraits<DT, DP...>; using src_memory_space = typename src_traits::memory_space; using dst_memory_space = typename dst_traits::memory_space; static_assert(std::is_same<typename dst_traits::value_type, typename src_traits::non_const_value_type>::value, "deep_copy requires matching non-const destination type"); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), sizeof(DT)); } if (dst.data() == nullptr && src.data() == nullptr) { exec_space.fence(); if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } if (dst.data() != src.data()) { Kokkos::Impl::DeepCopy<dst_memory_space, src_memory_space, ExecSpace>( exec_space, dst.data(), src.data(), sizeof(typename dst_traits::value_type)); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } //---------------------------------------------------------------------------- /** \brief A deep copy between views of the default specialization, compatible * type, same non-zero rank */ template <class ExecSpace, class DT, class... DP, class ST, class... SP> inline void deep_copy( const ExecSpace& exec_space, const View<DT, DP...>& dst, const View<ST, SP...>& src, typename std::enable_if<( Kokkos::Impl::is_execution_space<ExecSpace>::value && std::is_same<typename ViewTraits<DT, DP...>::specialize, void>::value && std::is_same<typename ViewTraits<ST, SP...>::specialize, void>::value && (unsigned(ViewTraits<DT, DP...>::rank) != 0 || unsigned(ViewTraits<ST, SP...>::rank) != 0))>::type* = nullptr) { using dst_type = View<DT, DP...>; using src_type = View<ST, SP...>; static_assert(std::is_same<typename dst_type::value_type, typename dst_type::non_const_value_type>::value, "deep_copy requires non-const destination type"); static_assert((unsigned(dst_type::rank) == unsigned(src_type::rank)), "deep_copy requires Views of equal rank"); using dst_execution_space = typename dst_type::execution_space; using src_execution_space = typename src_type::execution_space; using dst_memory_space = typename dst_type::memory_space; using src_memory_space = typename src_type::memory_space; using dst_value_type = typename dst_type::value_type; using src_value_type = typename src_type::value_type; if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::beginDeepCopy( Kokkos::Profiling::make_space_handle(dst_memory_space::name()), dst.label(), dst.data(), Kokkos::Profiling::make_space_handle(src_memory_space::name()), src.label(), src.data(), dst.span() * sizeof(dst_value_type)); } dst_value_type* dst_start = dst.data(); dst_value_type* dst_end = dst.data() + dst.span(); src_value_type* src_start = src.data(); src_value_type* src_end = src.data() + src.span(); // Early dropout if identical range if ((dst_start == nullptr || src_start == nullptr) || ((std::ptrdiff_t(dst_start) == std::ptrdiff_t(src_start)) && (std::ptrdiff_t(dst_end) == std::ptrdiff_t(src_end)))) { // throw if dimension mismatch if ((src.extent(0) != dst.extent(0)) || (src.extent(1) != dst.extent(1)) || (src.extent(2) != dst.extent(2)) || (src.extent(3) != dst.extent(3)) || (src.extent(4) != dst.extent(4)) || (src.extent(5) != dst.extent(5)) || (src.extent(6) != dst.extent(6)) || (src.extent(7) != dst.extent(7))) { std::string message( "Deprecation Error: Kokkos::deep_copy extents of views don't " "match: "); message += dst.label(); message += "("; for (int r = 0; r < dst_type::Rank - 1; r++) { message += std::to_string(dst.extent(r)); message += ","; } message += std::to_string(dst.extent(dst_type::Rank - 1)); message += ") "; message += src.label(); message += "("; for (int r = 0; r < src_type::Rank - 1; r++) { message += std::to_string(src.extent(r)); message += ","; } message += std::to_string(src.extent(src_type::Rank - 1)); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } return; } enum { ExecCanAccessSrcDst = Kokkos::Impl::SpaceAccessibility<ExecSpace, dst_memory_space>::accessible && Kokkos::Impl::SpaceAccessibility<ExecSpace, src_memory_space>::accessible }; enum { DstExecCanAccessSrc = Kokkos::Impl::SpaceAccessibility<dst_execution_space, src_memory_space>::accessible }; enum { SrcExecCanAccessDst = Kokkos::Impl::SpaceAccessibility<src_execution_space, dst_memory_space>::accessible }; // Error out for non-identical overlapping views. if ((((std::ptrdiff_t)dst_start < (std::ptrdiff_t)src_end) && ((std::ptrdiff_t)dst_end > (std::ptrdiff_t)src_start)) && ((dst.span_is_contiguous() && src.span_is_contiguous()))) { std::string message("Error: Kokkos::deep_copy of overlapping views: "); message += dst.label(); message += "("; message += std::to_string((std::ptrdiff_t)dst_start); message += ","; message += std::to_string((std::ptrdiff_t)dst_end); message += ") "; message += src.label(); message += "("; message += std::to_string((std::ptrdiff_t)src_start); message += ","; message += std::to_string((std::ptrdiff_t)src_end); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } // Check for same extents if ((src.extent(0) != dst.extent(0)) || (src.extent(1) != dst.extent(1)) || (src.extent(2) != dst.extent(2)) || (src.extent(3) != dst.extent(3)) || (src.extent(4) != dst.extent(4)) || (src.extent(5) != dst.extent(5)) || (src.extent(6) != dst.extent(6)) || (src.extent(7) != dst.extent(7))) { std::string message( "Deprecation Error: Kokkos::deep_copy extents of views don't match: "); message += dst.label(); message += "("; for (int r = 0; r < dst_type::Rank - 1; r++) { message += std::to_string(dst.extent(r)); message += ","; } message += std::to_string(dst.extent(dst_type::Rank - 1)); message += ") "; message += src.label(); message += "("; for (int r = 0; r < src_type::Rank - 1; r++) { message += std::to_string(src.extent(r)); message += ","; } message += std::to_string(src.extent(src_type::Rank - 1)); message += ") "; Kokkos::Impl::throw_runtime_exception(message); } // If same type, equal layout, equal dimensions, equal span, and contiguous // memory then can byte-wise copy if (std::is_same<typename dst_type::value_type, typename src_type::non_const_value_type>::value && (std::is_same<typename dst_type::array_layout, typename src_type::array_layout>::value || (dst_type::rank == 1 && src_type::rank == 1)) && dst.span_is_contiguous() && src.span_is_contiguous() && ((dst_type::rank < 1) || (dst.stride_0() == src.stride_0())) && ((dst_type::rank < 2) || (dst.stride_1() == src.stride_1())) && ((dst_type::rank < 3) || (dst.stride_2() == src.stride_2())) && ((dst_type::rank < 4) || (dst.stride_3() == src.stride_3())) && ((dst_type::rank < 5) || (dst.stride_4() == src.stride_4())) && ((dst_type::rank < 6) || (dst.stride_5() == src.stride_5())) && ((dst_type::rank < 7) || (dst.stride_6() == src.stride_6())) && ((dst_type::rank < 8) || (dst.stride_7() == src.stride_7()))) { const size_t nbytes = sizeof(typename dst_type::value_type) * dst.span(); if ((void*)dst.data() != (void*)src.data()) { Kokkos::Impl::DeepCopy<dst_memory_space, src_memory_space, ExecSpace>( exec_space, dst.data(), src.data(), nbytes); } } else { // Copying data between views in accessible memory spaces and either // non-contiguous or incompatible shape. if (ExecCanAccessSrcDst) { Impl::view_copy(exec_space, dst, src); } else if (DstExecCanAccessSrc || SrcExecCanAccessDst) { using cpy_exec_space = typename std::conditional<DstExecCanAccessSrc, dst_execution_space, src_execution_space>::type; exec_space.fence(); Impl::view_copy(cpy_exec_space(), dst, src); cpy_exec_space().fence(); } else { Kokkos::Impl::throw_runtime_exception( "deep_copy given views that would require a temporary allocation"); } } if (Kokkos::Profiling::profileLibraryLoaded()) { Kokkos::Profiling::endDeepCopy(); } } } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { /** \brief Resize a view with copying old data to new data at the corresponding * indices. */ template <class T, class... P> inline typename std::enable_if< std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutLeft>::value || std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutRight>::value>::type resize(Kokkos::View<T, P...>& v, const size_t n0 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n1 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n2 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n3 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n4 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n5 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n6 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n7 = KOKKOS_IMPL_CTOR_DEFAULT_ARG) { using view_type = Kokkos::View<T, P...>; static_assert(Kokkos::ViewTraits<T, P...>::is_managed, "Can only resize managed views"); // Fix #904 by checking dimensions before actually resizing. // // Rank is known at compile time, so hopefully the compiler will // remove branches that are compile-time false. The upcoming "if // constexpr" language feature would make this certain. if (view_type::Rank == 1 && n0 == static_cast<size_t>(v.extent(0))) { return; } if (view_type::Rank == 2 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1))) { return; } if (view_type::Rank == 3 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2))) { return; } if (view_type::Rank == 4 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3))) { return; } if (view_type::Rank == 5 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4))) { return; } if (view_type::Rank == 6 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5))) { return; } if (view_type::Rank == 7 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5)) && n6 == static_cast<size_t>(v.extent(6))) { return; } if (view_type::Rank == 8 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5)) && n6 == static_cast<size_t>(v.extent(6)) && n7 == static_cast<size_t>(v.extent(7))) { return; } // If Kokkos ever supports Views of rank > 8, the above code won't // be incorrect, because avoiding reallocation in resize() is just // an optimization. // TODO (mfh 27 Jun 2017) If the old View has enough space but just // different dimensions (e.g., if the product of the dimensions, // including extra space for alignment, will not change), then // consider just reusing storage. For now, Kokkos always // reallocates if any of the dimensions change, even if the old View // has enough space. view_type v_resized(v.label(), n0, n1, n2, n3, n4, n5, n6, n7); Kokkos::Impl::ViewRemap<view_type, view_type>(v_resized, v); v = v_resized; } /** \brief Resize a view with copying old data to new data at the corresponding * indices. */ template <class I, class T, class... P> inline typename std::enable_if< std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutLeft>::value || std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutRight>::value>::type resize(const I& arg_prop, Kokkos::View<T, P...>& v, const size_t n0 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n1 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n2 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n3 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n4 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n5 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n6 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n7 = KOKKOS_IMPL_CTOR_DEFAULT_ARG) { using view_type = Kokkos::View<T, P...>; static_assert(Kokkos::ViewTraits<T, P...>::is_managed, "Can only resize managed views"); // Fix #904 by checking dimensions before actually resizing. // // Rank is known at compile time, so hopefully the compiler will // remove branches that are compile-time false. The upcoming "if // constexpr" language feature would make this certain. if (view_type::Rank == 1 && n0 == static_cast<size_t>(v.extent(0))) { return; } if (view_type::Rank == 2 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1))) { return; } if (view_type::Rank == 3 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2))) { return; } if (view_type::Rank == 4 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3))) { return; } if (view_type::Rank == 5 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4))) { return; } if (view_type::Rank == 6 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5))) { return; } if (view_type::Rank == 7 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5)) && n6 == static_cast<size_t>(v.extent(6))) { return; } if (view_type::Rank == 8 && n0 == static_cast<size_t>(v.extent(0)) && n1 == static_cast<size_t>(v.extent(1)) && n2 == static_cast<size_t>(v.extent(2)) && n3 == static_cast<size_t>(v.extent(3)) && n4 == static_cast<size_t>(v.extent(4)) && n5 == static_cast<size_t>(v.extent(5)) && n6 == static_cast<size_t>(v.extent(6)) && n7 == static_cast<size_t>(v.extent(7))) { return; } // If Kokkos ever supports Views of rank > 8, the above code won't // be incorrect, because avoiding reallocation in resize() is just // an optimization. // TODO (mfh 27 Jun 2017) If the old View has enough space but just // different dimensions (e.g., if the product of the dimensions, // including extra space for alignment, will not change), then // consider just reusing storage. For now, Kokkos always // reallocates if any of the dimensions change, even if the old View // has enough space. view_type v_resized(view_alloc(v.label(), std::forward<const I>(arg_prop)), n0, n1, n2, n3, n4, n5, n6, n7); Kokkos::Impl::ViewRemap<view_type, view_type>(v_resized, v); v = v_resized; } /** \brief Resize a view with copying old data to new data at the corresponding * indices. */ template <class T, class... P> inline void resize(Kokkos::View<T, P...>& v, const typename Kokkos::View<T, P...>::array_layout& layout) { using view_type = Kokkos::View<T, P...>; static_assert(Kokkos::ViewTraits<T, P...>::is_managed, "Can only resize managed views"); view_type v_resized(v.label(), layout); Kokkos::Impl::ViewRemap<view_type, view_type>(v_resized, v); v = v_resized; } /** \brief Resize a view with discarding old data. */ template <class T, class... P> inline typename std::enable_if< std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutLeft>::value || std::is_same<typename Kokkos::View<T, P...>::array_layout, Kokkos::LayoutRight>::value>::type realloc(Kokkos::View<T, P...>& v, const size_t n0 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n1 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n2 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n3 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n4 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n5 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n6 = KOKKOS_IMPL_CTOR_DEFAULT_ARG, const size_t n7 = KOKKOS_IMPL_CTOR_DEFAULT_ARG) { using view_type = Kokkos::View<T, P...>; static_assert(Kokkos::ViewTraits<T, P...>::is_managed, "Can only realloc managed views"); const std::string label = v.label(); v = view_type(); // Deallocate first, if the only view to allocation v = view_type(label, n0, n1, n2, n3, n4, n5, n6, n7); } /** \brief Resize a view with discarding old data. */ template <class T, class... P> inline void realloc( Kokkos::View<T, P...>& v, const typename Kokkos::View<T, P...>::array_layout& layout) { using view_type = Kokkos::View<T, P...>; static_assert(Kokkos::ViewTraits<T, P...>::is_managed, "Can only realloc managed views"); const std::string label = v.label(); v = view_type(); // Deallocate first, if the only view to allocation v = view_type(label, layout); } } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { // Deduce Mirror Types template <class Space, class T, class... P> struct MirrorViewType { // The incoming view_type using src_view_type = typename Kokkos::View<T, P...>; // The memory space for the mirror view using memory_space = typename Space::memory_space; // Check whether it is the same memory space enum { is_same_memspace = std::is_same<memory_space, typename src_view_type::memory_space>::value }; // The array_layout using array_layout = typename src_view_type::array_layout; // The data type (we probably want it non-const since otherwise we can't even // deep_copy to it. using data_type = typename src_view_type::non_const_data_type; // The destination view type if it is not the same memory space using dest_view_type = Kokkos::View<data_type, array_layout, Space>; // If it is the same memory_space return the existsing view_type // This will also keep the unmanaged trait if necessary using view_type = typename std::conditional<is_same_memspace, src_view_type, dest_view_type>::type; }; template <class Space, class T, class... P> struct MirrorType { // The incoming view_type using src_view_type = typename Kokkos::View<T, P...>; // The memory space for the mirror view using memory_space = typename Space::memory_space; // Check whether it is the same memory space enum { is_same_memspace = std::is_same<memory_space, typename src_view_type::memory_space>::value }; // The array_layout using array_layout = typename src_view_type::array_layout; // The data type (we probably want it non-const since otherwise we can't even // deep_copy to it. using data_type = typename src_view_type::non_const_data_type; // The destination view type if it is not the same memory space using view_type = Kokkos::View<data_type, array_layout, Space>; }; } // namespace Impl template <class T, class... P> inline typename Kokkos::View<T, P...>::HostMirror create_mirror( const Kokkos::View<T, P...>& src, typename std::enable_if< std::is_same<typename ViewTraits<T, P...>::specialize, void>::value && !std::is_same<typename Kokkos::ViewTraits<T, P...>::array_layout, Kokkos::LayoutStride>::value>::type* = nullptr) { using src_type = View<T, P...>; using dst_type = typename src_type::HostMirror; return dst_type( std::string(src.label()).append("_mirror"), src.rank_dynamic > 0 ? src.extent(0) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 1 ? src.extent(1) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 2 ? src.extent(2) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 3 ? src.extent(3) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 4 ? src.extent(4) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 5 ? src.extent(5) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 6 ? src.extent(6) : KOKKOS_IMPL_CTOR_DEFAULT_ARG, src.rank_dynamic > 7 ? src.extent(7) : KOKKOS_IMPL_CTOR_DEFAULT_ARG); } template <class T, class... P> inline typename Kokkos::View<T, P...>::HostMirror create_mirror( const Kokkos::View<T, P...>& src, typename std::enable_if< std::is_same<typename ViewTraits<T, P...>::specialize, void>::value && std::is_same<typename Kokkos::ViewTraits<T, P...>::array_layout, Kokkos::LayoutStride>::value>::type* = nullptr) { using src_type = View<T, P...>; using dst_type = typename src_type::HostMirror; Kokkos::LayoutStride layout; layout.dimension[0] = src.extent(0); layout.dimension[1] = src.extent(1); layout.dimension[2] = src.extent(2); layout.dimension[3] = src.extent(3); layout.dimension[4] = src.extent(4); layout.dimension[5] = src.extent(5); layout.dimension[6] = src.extent(6); layout.dimension[7] = src.extent(7); layout.stride[0] = src.stride_0(); layout.stride[1] = src.stride_1(); layout.stride[2] = src.stride_2(); layout.stride[3] = src.stride_3(); layout.stride[4] = src.stride_4(); layout.stride[5] = src.stride_5(); layout.stride[6] = src.stride_6(); layout.stride[7] = src.stride_7(); return dst_type(std::string(src.label()).append("_mirror"), layout); } // Create a mirror in a new space (specialization for different space) template <class Space, class T, class... P> typename Impl::MirrorType<Space, T, P...>::view_type create_mirror( const Space&, const Kokkos::View<T, P...>& src, typename std::enable_if<std::is_same< typename ViewTraits<T, P...>::specialize, void>::value>::type* = nullptr) { return typename Impl::MirrorType<Space, T, P...>::view_type(src.label(), src.layout()); } template <class T, class... P> inline typename Kokkos::View<T, P...>::HostMirror create_mirror_view( const Kokkos::View<T, P...>& src, typename std::enable_if< (std::is_same< typename Kokkos::View<T, P...>::memory_space, typename Kokkos::View<T, P...>::HostMirror::memory_space>::value && std::is_same<typename Kokkos::View<T, P...>::data_type, typename Kokkos::View<T, P...>::HostMirror::data_type>:: value)>::type* = nullptr) { return src; } template <class T, class... P> inline typename Kokkos::View<T, P...>::HostMirror create_mirror_view( const Kokkos::View<T, P...>& src, typename std::enable_if<!( std::is_same< typename Kokkos::View<T, P...>::memory_space, typename Kokkos::View<T, P...>::HostMirror::memory_space>::value && std::is_same<typename Kokkos::View<T, P...>::data_type, typename Kokkos::View<T, P...>::HostMirror::data_type>:: value)>::type* = nullptr) { return Kokkos::create_mirror(src); } // Create a mirror view in a new space (specialization for same space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view( const Space&, const Kokkos::View<T, P...>& src, typename std::enable_if< Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { return src; } // Create a mirror view in a new space (specialization for different space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view( const Space&, const Kokkos::View<T, P...>& src, typename std::enable_if< !Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { return typename Impl::MirrorViewType<Space, T, P...>::view_type(src.label(), src.layout()); } // Create a mirror view and deep_copy in a new space (specialization for same // space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view_and_copy( const Space&, const Kokkos::View<T, P...>& src, std::string const& name = "", typename std::enable_if< Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { (void)name; fence(); // same behavior as deep_copy(src, src) return src; } // Create a mirror view and deep_copy in a new space (specialization for // different space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view_and_copy( const Space&, const Kokkos::View<T, P...>& src, std::string const& name = "", typename std::enable_if< !Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { using Mirror = typename Impl::MirrorViewType<Space, T, P...>::view_type; std::string label = name.empty() ? src.label() : name; auto mirror = typename Mirror::non_const_type{ ViewAllocateWithoutInitializing(label), src.layout()}; deep_copy(mirror, src); return mirror; } // Create a mirror view in a new space without initializing (specialization for // same space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view( const Space&, const Kokkos::View<T, P...>& src, Kokkos::Impl::WithoutInitializing_t, typename std::enable_if< Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { return src; } // Create a mirror view in a new space without initializing (specialization for // different space) template <class Space, class T, class... P> typename Impl::MirrorViewType<Space, T, P...>::view_type create_mirror_view( const Space&, const Kokkos::View<T, P...>& src, Kokkos::Impl::WithoutInitializing_t, typename std::enable_if< !Impl::MirrorViewType<Space, T, P...>::is_same_memspace>::type* = nullptr) { using Mirror = typename Impl::MirrorViewType<Space, T, P...>::view_type; return Mirror(Kokkos::ViewAllocateWithoutInitializing(src.label()), src.layout()); } } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- #endif
41.725851
80
0.583451
[ "shape", "3d" ]
7854597880246f4275fa30071141acd76f0f6d46
3,333
hpp
C++
src/server/ServerModules.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
6
2015-02-27T19:15:11.000Z
2018-10-25T14:22:31.000Z
src/server/ServerModules.hpp
yoursunny/DataSeries
b5b9db8e40a79a3e546a59cd72a80be89412d7b2
[ "BSD-2-Clause" ]
7
2015-08-17T15:18:50.000Z
2017-08-16T00:16:19.000Z
src/server/ServerModules.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
8
2015-07-13T23:02:28.000Z
2020-09-28T19:06:26.000Z
#ifndef DATASERIES_SERVERMODULES_HPP #define DATASERIES_SERVERMODULES_HPP #include <DataSeries/DataSeriesModule.hpp> #include "ThrowError.hpp" #include "OutputSeriesModule.hpp" #include "RenameCopier.hpp" #include "gen-cpp/DataSeriesServer.h" // TODO: consider re-doing a lot of the other modules in this form, most of them don't benefit // from inheritence. namespace dataseries { struct SortColumnImpl { SortColumnImpl(GeneralField::Ptr field, bool sort_less, NullMode null_mode) : field(field), sort_less(sort_less), null_mode(null_mode) { TINVARIANT(null_mode == NM_First || null_mode == NM_Last); } GeneralField::Ptr field; bool sort_less; // a < b ==> sort_less NullMode null_mode; }; struct UM_UnionTable : dataseries::UnionTable { UM_UnionTable() : UnionTable(), source(), series(), copier(), order_fields() { } UM_UnionTable(const dataseries::UnionTable &ut, DataSeriesModule::Ptr source) : UnionTable(ut), source(source), series(), copier(), order_fields() { } ~UM_UnionTable() throw () {} DataSeriesModule::Ptr source; ExtentSeries series; RenameCopier::Ptr copier; std::vector<SortColumnImpl> order_fields; }; DataSeriesModule::Ptr makeTeeModule(DataSeriesModule &source_module, const std::string &output_path); DataSeriesModule::Ptr makeTableDataModule(DataSeriesModule &source_module, TableData &into, uint32_t max_rows); OutputSeriesModule::OSMPtr makeHashJoinModule (DataSeriesModule &a_input, int32_t max_a_rows, DataSeriesModule &b_input, const std::map<std::string, std::string> &eq_columns, const std::map<std::string, std::string> &keep_columns, const std::string &output_table_name); OutputSeriesModule::OSMPtr makeStarJoinModule (DataSeriesModule &fact_input, const std::vector<Dimension> &dimensions, const std::string &output_table_name, const std::map<std::string, std::string> &fact_columns, const std::vector<DimensionFactJoin> &dimension_fact_join_in, const HashMap< std::string, boost::shared_ptr<DataSeriesModule> > &dimension_modules); DataSeriesModule::Ptr makeSelectModule(DataSeriesModule &source, const std::string &where_expr_str); OutputSeriesModule::OSMPtr makeProjectModule(DataSeriesModule &source, const std::vector<std::string> &keep_columns); DataSeriesModule::Ptr makeSortedUpdateModule (DataSeriesModule &base_input, DataSeriesModule &update_input, const std::string &update_column, const std::vector<std::string> &primary_key); OutputSeriesModule::OSMPtr makeUnionModule (const std::vector<dataseries::UM_UnionTable> &in_sources, const std::vector<SortColumn> &order_columns, const std::string &output_table_name); OutputSeriesModule::OSMPtr makeSortModule (DataSeriesModule &source, const std::vector<SortColumn> &sort_by); OutputSeriesModule::OSMPtr makeExprTransformModule (DataSeriesModule &source, const std::vector<ExprColumn> &expr_columns, const std::string &output_table_name); } #endif
42.189873
95
0.684968
[ "vector" ]
78558c3d15d35ec8cf86ad2ab463de67d4803d9b
2,690
cc
C++
hoomd/filter/export_filters.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
hoomd/filter/export_filters.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
hoomd/filter/export_filters.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
#include "export_filters.h" #include "ParticleFilter.h" #include "ParticleFilterAll.h" #include "ParticleFilterNull.h" #include "ParticleFilterIntersection.h" #include "ParticleFilterSetDifference.h" #include "ParticleFilterTags.h" #include "ParticleFilterType.h" #include "ParticleFilterUnion.h" #include "ParticleFilterCustom.h" #include <pybind11/pybind11.h> void export_ParticleFilters(pybind11::module& m) { pybind11::class_<ParticleFilter, std::shared_ptr<ParticleFilter> >(m,"ParticleFilter") .def(pybind11::init< >()) .def("_get_selected_tags", &ParticleFilter::getSelectedTags); pybind11::class_<ParticleFilterSetDifference, ParticleFilter, std::shared_ptr<ParticleFilterSetDifference> >(m, "ParticleFilterSetDifference") .def(pybind11::init<std::shared_ptr<ParticleFilter>, std::shared_ptr<ParticleFilter> >()); pybind11::class_<ParticleFilterUnion, ParticleFilter, std::shared_ptr<ParticleFilterUnion> >(m, "ParticleFilterUnion") .def(pybind11::init<std::shared_ptr<ParticleFilter>, std::shared_ptr<ParticleFilter> >()); pybind11::class_<ParticleFilterType, ParticleFilter, std::shared_ptr<ParticleFilterType> >(m,"ParticleFilterType") .def(pybind11::init<std::unordered_set<std::string>>()); pybind11::class_<ParticleFilterAll, ParticleFilter, std::shared_ptr<ParticleFilterAll> >(m,"ParticleFilterAll") .def(pybind11::init< >()); pybind11::class_<ParticleFilterNull, ParticleFilter, std::shared_ptr<ParticleFilterNull> >(m,"ParticleFilterNull") .def(pybind11::init< >()); pybind11::class_<ParticleFilterIntersection, ParticleFilter, std::shared_ptr<ParticleFilterIntersection> >(m, "ParticleFilterIntersection") .def(pybind11::init<std::shared_ptr<ParticleFilter>, std::shared_ptr<ParticleFilter> >()); pybind11::class_<ParticleFilterTags, ParticleFilter, std::shared_ptr<ParticleFilterTags> >(m,"ParticleFilterTags") .def(pybind11::init<pybind11::array_t<unsigned int, pybind11::array::c_style> >()); pybind11::class_<ParticleFilterCustom, ParticleFilter, std::shared_ptr<ParticleFilterCustom> >(m, "ParticleFilterCustom") .def(pybind11::init<pybind11::object, pybind11::object>()); };
42.698413
81
0.62342
[ "object" ]
7856c899e3df986cb9fe87f6eb2f3a2c72d242b6
26,110
cpp
C++
cynosdb/src/v20190107/model/CreateClustersRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cynosdb/src/v20190107/model/CreateClustersRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cynosdb/src/v20190107/model/CreateClustersRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cynosdb/v20190107/model/CreateClustersRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Cynosdb::V20190107::Model; using namespace std; CreateClustersRequest::CreateClustersRequest() : m_zoneHasBeenSet(false), m_vpcIdHasBeenSet(false), m_subnetIdHasBeenSet(false), m_dbTypeHasBeenSet(false), m_dbVersionHasBeenSet(false), m_projectIdHasBeenSet(false), m_cpuHasBeenSet(false), m_memoryHasBeenSet(false), m_storageHasBeenSet(false), m_clusterNameHasBeenSet(false), m_adminPasswordHasBeenSet(false), m_portHasBeenSet(false), m_payModeHasBeenSet(false), m_countHasBeenSet(false), m_rollbackStrategyHasBeenSet(false), m_rollbackIdHasBeenSet(false), m_originalClusterIdHasBeenSet(false), m_expectTimeHasBeenSet(false), m_expectTimeThreshHasBeenSet(false), m_storageLimitHasBeenSet(false), m_instanceCountHasBeenSet(false), m_timeSpanHasBeenSet(false), m_timeUnitHasBeenSet(false), m_autoRenewFlagHasBeenSet(false), m_autoVoucherHasBeenSet(false), m_haCountHasBeenSet(false), m_orderSourceHasBeenSet(false), m_resourceTagsHasBeenSet(false), m_dbModeHasBeenSet(false), m_minCpuHasBeenSet(false), m_maxCpuHasBeenSet(false), m_autoPauseHasBeenSet(false), m_autoPauseDelayHasBeenSet(false), m_storagePayModeHasBeenSet(false), m_securityGroupIdsHasBeenSet(false), m_alarmPolicyIdsHasBeenSet(false), m_clusterParamsHasBeenSet(false), m_dealModeHasBeenSet(false), m_paramTemplateIdHasBeenSet(false) { } string CreateClustersRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_zoneHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Zone"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_zone.c_str(), allocator).Move(), allocator); } if (m_vpcIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VpcId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_vpcId.c_str(), allocator).Move(), allocator); } if (m_subnetIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SubnetId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_subnetId.c_str(), allocator).Move(), allocator); } if (m_dbTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DbType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_dbType.c_str(), allocator).Move(), allocator); } if (m_dbVersionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DbVersion"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_dbVersion.c_str(), allocator).Move(), allocator); } if (m_projectIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProjectId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_projectId, allocator); } if (m_cpuHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Cpu"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_cpu, allocator); } if (m_memoryHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Memory"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_memory, allocator); } if (m_storageHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Storage"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_storage, allocator); } if (m_clusterNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ClusterName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_clusterName.c_str(), allocator).Move(), allocator); } if (m_adminPasswordHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AdminPassword"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_adminPassword.c_str(), allocator).Move(), allocator); } if (m_portHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Port"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_port, allocator); } if (m_payModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PayMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_payMode, allocator); } if (m_countHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Count"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_count, allocator); } if (m_rollbackStrategyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RollbackStrategy"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_rollbackStrategy.c_str(), allocator).Move(), allocator); } if (m_rollbackIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RollbackId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_rollbackId, allocator); } if (m_originalClusterIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OriginalClusterId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_originalClusterId.c_str(), allocator).Move(), allocator); } if (m_expectTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpectTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_expectTime.c_str(), allocator).Move(), allocator); } if (m_expectTimeThreshHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpectTimeThresh"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_expectTimeThresh, allocator); } if (m_storageLimitHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StorageLimit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_storageLimit, allocator); } if (m_instanceCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceCount"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_instanceCount, allocator); } if (m_timeSpanHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TimeSpan"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_timeSpan, allocator); } if (m_timeUnitHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TimeUnit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_timeUnit.c_str(), allocator).Move(), allocator); } if (m_autoRenewFlagHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoRenewFlag"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_autoRenewFlag, allocator); } if (m_autoVoucherHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoVoucher"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_autoVoucher, allocator); } if (m_haCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HaCount"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_haCount, allocator); } if (m_orderSourceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OrderSource"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_orderSource.c_str(), allocator).Move(), allocator); } if (m_resourceTagsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ResourceTags"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_resourceTags.begin(); itr != m_resourceTags.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_dbModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DbMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_dbMode.c_str(), allocator).Move(), allocator); } if (m_minCpuHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MinCpu"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_minCpu, allocator); } if (m_maxCpuHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MaxCpu"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_maxCpu, allocator); } if (m_autoPauseHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoPause"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_autoPause.c_str(), allocator).Move(), allocator); } if (m_autoPauseDelayHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoPauseDelay"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_autoPauseDelay, allocator); } if (m_storagePayModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StoragePayMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_storagePayMode, allocator); } if (m_securityGroupIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SecurityGroupIds"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_securityGroupIds.begin(); itr != m_securityGroupIds.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_alarmPolicyIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AlarmPolicyIds"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_alarmPolicyIds.begin(); itr != m_alarmPolicyIds.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_clusterParamsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ClusterParams"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_clusterParams.begin(); itr != m_clusterParams.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_dealModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DealMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_dealMode, allocator); } if (m_paramTemplateIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ParamTemplateId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_paramTemplateId, allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateClustersRequest::GetZone() const { return m_zone; } void CreateClustersRequest::SetZone(const string& _zone) { m_zone = _zone; m_zoneHasBeenSet = true; } bool CreateClustersRequest::ZoneHasBeenSet() const { return m_zoneHasBeenSet; } string CreateClustersRequest::GetVpcId() const { return m_vpcId; } void CreateClustersRequest::SetVpcId(const string& _vpcId) { m_vpcId = _vpcId; m_vpcIdHasBeenSet = true; } bool CreateClustersRequest::VpcIdHasBeenSet() const { return m_vpcIdHasBeenSet; } string CreateClustersRequest::GetSubnetId() const { return m_subnetId; } void CreateClustersRequest::SetSubnetId(const string& _subnetId) { m_subnetId = _subnetId; m_subnetIdHasBeenSet = true; } bool CreateClustersRequest::SubnetIdHasBeenSet() const { return m_subnetIdHasBeenSet; } string CreateClustersRequest::GetDbType() const { return m_dbType; } void CreateClustersRequest::SetDbType(const string& _dbType) { m_dbType = _dbType; m_dbTypeHasBeenSet = true; } bool CreateClustersRequest::DbTypeHasBeenSet() const { return m_dbTypeHasBeenSet; } string CreateClustersRequest::GetDbVersion() const { return m_dbVersion; } void CreateClustersRequest::SetDbVersion(const string& _dbVersion) { m_dbVersion = _dbVersion; m_dbVersionHasBeenSet = true; } bool CreateClustersRequest::DbVersionHasBeenSet() const { return m_dbVersionHasBeenSet; } int64_t CreateClustersRequest::GetProjectId() const { return m_projectId; } void CreateClustersRequest::SetProjectId(const int64_t& _projectId) { m_projectId = _projectId; m_projectIdHasBeenSet = true; } bool CreateClustersRequest::ProjectIdHasBeenSet() const { return m_projectIdHasBeenSet; } int64_t CreateClustersRequest::GetCpu() const { return m_cpu; } void CreateClustersRequest::SetCpu(const int64_t& _cpu) { m_cpu = _cpu; m_cpuHasBeenSet = true; } bool CreateClustersRequest::CpuHasBeenSet() const { return m_cpuHasBeenSet; } int64_t CreateClustersRequest::GetMemory() const { return m_memory; } void CreateClustersRequest::SetMemory(const int64_t& _memory) { m_memory = _memory; m_memoryHasBeenSet = true; } bool CreateClustersRequest::MemoryHasBeenSet() const { return m_memoryHasBeenSet; } int64_t CreateClustersRequest::GetStorage() const { return m_storage; } void CreateClustersRequest::SetStorage(const int64_t& _storage) { m_storage = _storage; m_storageHasBeenSet = true; } bool CreateClustersRequest::StorageHasBeenSet() const { return m_storageHasBeenSet; } string CreateClustersRequest::GetClusterName() const { return m_clusterName; } void CreateClustersRequest::SetClusterName(const string& _clusterName) { m_clusterName = _clusterName; m_clusterNameHasBeenSet = true; } bool CreateClustersRequest::ClusterNameHasBeenSet() const { return m_clusterNameHasBeenSet; } string CreateClustersRequest::GetAdminPassword() const { return m_adminPassword; } void CreateClustersRequest::SetAdminPassword(const string& _adminPassword) { m_adminPassword = _adminPassword; m_adminPasswordHasBeenSet = true; } bool CreateClustersRequest::AdminPasswordHasBeenSet() const { return m_adminPasswordHasBeenSet; } int64_t CreateClustersRequest::GetPort() const { return m_port; } void CreateClustersRequest::SetPort(const int64_t& _port) { m_port = _port; m_portHasBeenSet = true; } bool CreateClustersRequest::PortHasBeenSet() const { return m_portHasBeenSet; } int64_t CreateClustersRequest::GetPayMode() const { return m_payMode; } void CreateClustersRequest::SetPayMode(const int64_t& _payMode) { m_payMode = _payMode; m_payModeHasBeenSet = true; } bool CreateClustersRequest::PayModeHasBeenSet() const { return m_payModeHasBeenSet; } int64_t CreateClustersRequest::GetCount() const { return m_count; } void CreateClustersRequest::SetCount(const int64_t& _count) { m_count = _count; m_countHasBeenSet = true; } bool CreateClustersRequest::CountHasBeenSet() const { return m_countHasBeenSet; } string CreateClustersRequest::GetRollbackStrategy() const { return m_rollbackStrategy; } void CreateClustersRequest::SetRollbackStrategy(const string& _rollbackStrategy) { m_rollbackStrategy = _rollbackStrategy; m_rollbackStrategyHasBeenSet = true; } bool CreateClustersRequest::RollbackStrategyHasBeenSet() const { return m_rollbackStrategyHasBeenSet; } uint64_t CreateClustersRequest::GetRollbackId() const { return m_rollbackId; } void CreateClustersRequest::SetRollbackId(const uint64_t& _rollbackId) { m_rollbackId = _rollbackId; m_rollbackIdHasBeenSet = true; } bool CreateClustersRequest::RollbackIdHasBeenSet() const { return m_rollbackIdHasBeenSet; } string CreateClustersRequest::GetOriginalClusterId() const { return m_originalClusterId; } void CreateClustersRequest::SetOriginalClusterId(const string& _originalClusterId) { m_originalClusterId = _originalClusterId; m_originalClusterIdHasBeenSet = true; } bool CreateClustersRequest::OriginalClusterIdHasBeenSet() const { return m_originalClusterIdHasBeenSet; } string CreateClustersRequest::GetExpectTime() const { return m_expectTime; } void CreateClustersRequest::SetExpectTime(const string& _expectTime) { m_expectTime = _expectTime; m_expectTimeHasBeenSet = true; } bool CreateClustersRequest::ExpectTimeHasBeenSet() const { return m_expectTimeHasBeenSet; } uint64_t CreateClustersRequest::GetExpectTimeThresh() const { return m_expectTimeThresh; } void CreateClustersRequest::SetExpectTimeThresh(const uint64_t& _expectTimeThresh) { m_expectTimeThresh = _expectTimeThresh; m_expectTimeThreshHasBeenSet = true; } bool CreateClustersRequest::ExpectTimeThreshHasBeenSet() const { return m_expectTimeThreshHasBeenSet; } int64_t CreateClustersRequest::GetStorageLimit() const { return m_storageLimit; } void CreateClustersRequest::SetStorageLimit(const int64_t& _storageLimit) { m_storageLimit = _storageLimit; m_storageLimitHasBeenSet = true; } bool CreateClustersRequest::StorageLimitHasBeenSet() const { return m_storageLimitHasBeenSet; } int64_t CreateClustersRequest::GetInstanceCount() const { return m_instanceCount; } void CreateClustersRequest::SetInstanceCount(const int64_t& _instanceCount) { m_instanceCount = _instanceCount; m_instanceCountHasBeenSet = true; } bool CreateClustersRequest::InstanceCountHasBeenSet() const { return m_instanceCountHasBeenSet; } int64_t CreateClustersRequest::GetTimeSpan() const { return m_timeSpan; } void CreateClustersRequest::SetTimeSpan(const int64_t& _timeSpan) { m_timeSpan = _timeSpan; m_timeSpanHasBeenSet = true; } bool CreateClustersRequest::TimeSpanHasBeenSet() const { return m_timeSpanHasBeenSet; } string CreateClustersRequest::GetTimeUnit() const { return m_timeUnit; } void CreateClustersRequest::SetTimeUnit(const string& _timeUnit) { m_timeUnit = _timeUnit; m_timeUnitHasBeenSet = true; } bool CreateClustersRequest::TimeUnitHasBeenSet() const { return m_timeUnitHasBeenSet; } int64_t CreateClustersRequest::GetAutoRenewFlag() const { return m_autoRenewFlag; } void CreateClustersRequest::SetAutoRenewFlag(const int64_t& _autoRenewFlag) { m_autoRenewFlag = _autoRenewFlag; m_autoRenewFlagHasBeenSet = true; } bool CreateClustersRequest::AutoRenewFlagHasBeenSet() const { return m_autoRenewFlagHasBeenSet; } int64_t CreateClustersRequest::GetAutoVoucher() const { return m_autoVoucher; } void CreateClustersRequest::SetAutoVoucher(const int64_t& _autoVoucher) { m_autoVoucher = _autoVoucher; m_autoVoucherHasBeenSet = true; } bool CreateClustersRequest::AutoVoucherHasBeenSet() const { return m_autoVoucherHasBeenSet; } int64_t CreateClustersRequest::GetHaCount() const { return m_haCount; } void CreateClustersRequest::SetHaCount(const int64_t& _haCount) { m_haCount = _haCount; m_haCountHasBeenSet = true; } bool CreateClustersRequest::HaCountHasBeenSet() const { return m_haCountHasBeenSet; } string CreateClustersRequest::GetOrderSource() const { return m_orderSource; } void CreateClustersRequest::SetOrderSource(const string& _orderSource) { m_orderSource = _orderSource; m_orderSourceHasBeenSet = true; } bool CreateClustersRequest::OrderSourceHasBeenSet() const { return m_orderSourceHasBeenSet; } vector<Tag> CreateClustersRequest::GetResourceTags() const { return m_resourceTags; } void CreateClustersRequest::SetResourceTags(const vector<Tag>& _resourceTags) { m_resourceTags = _resourceTags; m_resourceTagsHasBeenSet = true; } bool CreateClustersRequest::ResourceTagsHasBeenSet() const { return m_resourceTagsHasBeenSet; } string CreateClustersRequest::GetDbMode() const { return m_dbMode; } void CreateClustersRequest::SetDbMode(const string& _dbMode) { m_dbMode = _dbMode; m_dbModeHasBeenSet = true; } bool CreateClustersRequest::DbModeHasBeenSet() const { return m_dbModeHasBeenSet; } double CreateClustersRequest::GetMinCpu() const { return m_minCpu; } void CreateClustersRequest::SetMinCpu(const double& _minCpu) { m_minCpu = _minCpu; m_minCpuHasBeenSet = true; } bool CreateClustersRequest::MinCpuHasBeenSet() const { return m_minCpuHasBeenSet; } double CreateClustersRequest::GetMaxCpu() const { return m_maxCpu; } void CreateClustersRequest::SetMaxCpu(const double& _maxCpu) { m_maxCpu = _maxCpu; m_maxCpuHasBeenSet = true; } bool CreateClustersRequest::MaxCpuHasBeenSet() const { return m_maxCpuHasBeenSet; } string CreateClustersRequest::GetAutoPause() const { return m_autoPause; } void CreateClustersRequest::SetAutoPause(const string& _autoPause) { m_autoPause = _autoPause; m_autoPauseHasBeenSet = true; } bool CreateClustersRequest::AutoPauseHasBeenSet() const { return m_autoPauseHasBeenSet; } int64_t CreateClustersRequest::GetAutoPauseDelay() const { return m_autoPauseDelay; } void CreateClustersRequest::SetAutoPauseDelay(const int64_t& _autoPauseDelay) { m_autoPauseDelay = _autoPauseDelay; m_autoPauseDelayHasBeenSet = true; } bool CreateClustersRequest::AutoPauseDelayHasBeenSet() const { return m_autoPauseDelayHasBeenSet; } int64_t CreateClustersRequest::GetStoragePayMode() const { return m_storagePayMode; } void CreateClustersRequest::SetStoragePayMode(const int64_t& _storagePayMode) { m_storagePayMode = _storagePayMode; m_storagePayModeHasBeenSet = true; } bool CreateClustersRequest::StoragePayModeHasBeenSet() const { return m_storagePayModeHasBeenSet; } vector<string> CreateClustersRequest::GetSecurityGroupIds() const { return m_securityGroupIds; } void CreateClustersRequest::SetSecurityGroupIds(const vector<string>& _securityGroupIds) { m_securityGroupIds = _securityGroupIds; m_securityGroupIdsHasBeenSet = true; } bool CreateClustersRequest::SecurityGroupIdsHasBeenSet() const { return m_securityGroupIdsHasBeenSet; } vector<string> CreateClustersRequest::GetAlarmPolicyIds() const { return m_alarmPolicyIds; } void CreateClustersRequest::SetAlarmPolicyIds(const vector<string>& _alarmPolicyIds) { m_alarmPolicyIds = _alarmPolicyIds; m_alarmPolicyIdsHasBeenSet = true; } bool CreateClustersRequest::AlarmPolicyIdsHasBeenSet() const { return m_alarmPolicyIdsHasBeenSet; } vector<ParamItem> CreateClustersRequest::GetClusterParams() const { return m_clusterParams; } void CreateClustersRequest::SetClusterParams(const vector<ParamItem>& _clusterParams) { m_clusterParams = _clusterParams; m_clusterParamsHasBeenSet = true; } bool CreateClustersRequest::ClusterParamsHasBeenSet() const { return m_clusterParamsHasBeenSet; } int64_t CreateClustersRequest::GetDealMode() const { return m_dealMode; } void CreateClustersRequest::SetDealMode(const int64_t& _dealMode) { m_dealMode = _dealMode; m_dealModeHasBeenSet = true; } bool CreateClustersRequest::DealModeHasBeenSet() const { return m_dealModeHasBeenSet; } int64_t CreateClustersRequest::GetParamTemplateId() const { return m_paramTemplateId; } void CreateClustersRequest::SetParamTemplateId(const int64_t& _paramTemplateId) { m_paramTemplateId = _paramTemplateId; m_paramTemplateIdHasBeenSet = true; } bool CreateClustersRequest::ParamTemplateIdHasBeenSet() const { return m_paramTemplateIdHasBeenSet; }
25.009579
104
0.712294
[ "vector", "model" ]
785a4c868e827d17b323efcbea9acaca1fb8e5c9
79,797
cpp
C++
src/gausskernel/cbb/utils/aes/cipherfn.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
src/gausskernel/cbb/utils/aes/cipherfn.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
src/gausskernel/cbb/utils/aes/cipherfn.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * File Name : cipherfn.cpp * Brief : * Description : encrypt and decrypt functions for MPPDB * * History : 2014-10 * * IDENTIFICATION * src/gausskernel/cbb/utils/aes/cipherfn.cpp * * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "cipher.h" #include "utils/builtins.h" #include "utils/aes.h" #include "utils/evp_cipher.h" #include "storage/lwlock.h" #include "port.h" #include "getopt_long.h" #include "pgxc/pgxc.h" #include "gaussdb_version.h" #include "gssapi/gssapi_krb5.h" #include "keymanagement/KeyManager.h" #include "openssl/rand.h" #include "openssl/evp.h" #include "openssl/crypto.h" const char* pgname = "gs_encrypt"; void getOBSKeyString(GS_UCHAR** cipherKey); static GS_UCHAR* getECKeyString(void); char prefixCipherKey[2] = {'\0'}; char suffixCipherKey[100] = {'\0'}; bool gs_encrypt_aes_speed(GS_UCHAR* plaintext, GS_UCHAR* key, GS_UCHAR* ciphertext, GS_UINT32* cipherlen); bool gs_decrypt_aes_speed( GS_UCHAR* ciphertext, GS_UINT32 cipherlen, GS_UCHAR* key, GS_UCHAR* plaintext, GS_UINT32* plainlen); static char* gs_strdup(const char* s); static void do_help(void); static void do_advice(void); static void free_global_value(void); static bool is_prefix_in_key_mode(const char* mode); GS_UCHAR* trans_encrypt_dek = NULL; GS_UCHAR* trans_encrypt_iv = NULL; // Fi root certificate path char* g_fi_ca_path = NULL; // tde algo TDE_ALGO g_tde_algo; // the prefix of the output cipher/randfile char* g_prefix = NULL; int g_vector_len = 0; // key text char* g_key = NULL; int g_key_len = 0; // vector text char* g_vector = NULL; #define EC_ENCRYPT_PREFIX "encryptOpt" // free the malloc memory #define GS_FREE(ptr) \ if (NULL != (ptr)) { \ free((char*)(ptr)); \ ptr = NULL; \ } // check the character value #define IsIllegalCharacter(c) ((c) != '/' && !isdigit((c)) && !isalpha((c)) && (c) != '_' && (c) != '-') /* * @@GaussDB@@ * Brief : char *gs_strdup(const char *s) * Description : * Notes : */ static char* gs_strdup(const char* s) { char* result = NULL; result = strdup(s); if (result == NULL) { (void)fprintf(stderr, _("%s: out of memory\n\n"), pgname); exit(1); } return result; } /* * decrypt the ciphertext with ase128 algorithms through OpenSSL API * old version, but still used by the new version in case there are data encrypted * by gs_encrypt_aes. */ bool gs_decrypt_aes(GS_UCHAR* ciphertext, GS_UINT32 cipherlen, GS_UCHAR* key, GS_UCHAR* plaintext, GS_UINT32* plainlen) { GS_UINT32 cipherpartlen = 0; GS_UCHAR* cipherpart = NULL; GS_UCHAR* randpart = NULL; bool decryptstatus = false; errno_t errorno = EOK; cipherpartlen = cipherlen - RANDOM_LEN; /* split the cipher text to cipherpart(ciphertext + vectorsalt) and randpart for decrypt */ cipherpart = (GS_UCHAR*)palloc0(cipherpartlen + 1); randpart = (GS_UCHAR*)palloc0(RANDOM_LEN); errorno = memcpy_s(cipherpart, cipherpartlen + 1, ciphertext, cipherpartlen); securec_check(errorno, "\0", "\0"); errorno = memcpy_s(randpart, RANDOM_LEN, ciphertext + cipherpartlen, RANDOM_LEN); securec_check(errorno, "\0", "\0"); /* the real decrypt operation */ decryptstatus = aes128Decrypt( cipherpart, cipherpartlen, key, (GS_UINT32)strlen((const char*)key), randpart, plaintext, plainlen); errorno = memset_s(cipherpart, cipherpartlen + 1, '\0', cipherpartlen + 1); securec_check(errorno, "\0", "\0"); pfree_ext(cipherpart); errorno = memset_s(randpart, RANDOM_LEN, '\0', RANDOM_LEN); securec_check(errorno, "\0", "\0"); pfree_ext(randpart); if (!decryptstatus) { return false; } else { return true; } } /* * Target :Encrypt functions for security. * Description :Encrypt with standard aes128 algorthm using OpenSSL functions. * Notes :The Key used here must be the same as it was used in decrypt. * Input :PG_FUNCTION_ARGS, containing plaintext and key * Output :Pointer of the CipherText which is encrypted and encoded from plaintext * Revision :Using random initial vector and one fixed salt in one thread * in order to avoid generating deriveKey everytime. */ Datum gs_encrypt_aes128(PG_FUNCTION_ARGS) { GS_UCHAR* key = NULL; GS_UINT32 keylen = 0; GS_UCHAR* plaintext = NULL; GS_UINT32 plaintextlen = 0; GS_UCHAR* ciphertext = NULL; GS_UINT32 ciphertextlen = 0; GS_UINT32 retval = 0; char* encodetext = NULL; GS_UINT32 encodetextlen = 0; GS_UINT32 ciphertextlen_max = 0; text* outtext = NULL; errno_t errorno = EOK; /* check input paramaters */ if (PG_ARGISNULL(0)) { fcinfo->isnull = true; outtext = NULL; PG_RETURN_TEXT_P(outtext); } if (PG_ARGISNULL(1)) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("The encryption key can not be empty!"))); } plaintext = (GS_UCHAR*)(text_to_cstring(PG_GETARG_TEXT_P(0))); plaintextlen = strlen((const char*)plaintext); key = (GS_UCHAR*)(text_to_cstring(PG_GETARG_TEXT_P(1))); keylen = strlen((const char*)key); /* The input key must shorter than RANDOM_LEN(16) */ if (keylen > RANDOM_LEN) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("The encryption key must be shorter than 16 bytes!"))); } /* * Calculate the max length of ciphertext: * contain aes-expand length, IV length, Salt length and backup length. * Add mac text length. */ ciphertextlen_max = plaintextlen + RANDOM_LEN * 4 + MAC_LEN; /* refer combo_encrypt_len function ,cipherlen = plainlen + 64 */ ciphertext = (GS_UCHAR*)palloc(ciphertextlen_max); errorno = memset_s(ciphertext, ciphertextlen_max, '\0', ciphertextlen_max); securec_check(errorno, "\0", "\0"); /* encrypt the plaintext to ciphertext */ retval = gs_encrypt_aes_speed(plaintext, key, ciphertext, &ciphertextlen); errorno = memset_s(plaintext, plaintextlen, '\0', plaintextlen); securec_check(errorno, "\0", "\0"); pfree_ext(plaintext); errorno = memset_s(key, keylen, '\0', keylen); securec_check(errorno, "\0", "\0"); pfree_ext(key); if (!retval) { errorno = memset_s(ciphertext, ciphertextlen, '\0', ciphertextlen); securec_check(errorno, "\0", "\0"); pfree_ext(ciphertext); ereport( ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("encrypt the plain text failed!"))); } /* encode the ciphertext for nice show and decrypt operation */ encodetext = SEC_encodeBase64((char*)ciphertext, ciphertextlen); errorno = memset_s(ciphertext, ciphertextlen, '\0', ciphertextlen); securec_check(errorno, "\0", "\0"); pfree_ext(ciphertext); if (encodetext == NULL) { ciphertextlen_max = 0; ereport( ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("encode the plain text failed!"))); } encodetextlen = strlen(encodetext); outtext = cstring_to_text((char*)encodetext); errorno = memset_s(encodetext, encodetextlen, '\0', encodetextlen); securec_check(errorno, "\0", "\0"); OPENSSL_free(encodetext); encodetext = NULL; PG_RETURN_TEXT_P(outtext); } /* * Target :Decrypt functions for security. * Description :Decrypt with standard aes128 algorthm using OpenSSL functions. * Notes :The Key used here must be the same as it was used in encrypt. * Input :PG_FUNCTION_ARGS, containing ciphertext and key * Output :Pointer of the PlainText which is decrypted and decoded from ciphertext * Revision :Save several derivekeys and salts in one thread * in order to avoid generating deriveKey everytime. */ Datum gs_decrypt_aes128(PG_FUNCTION_ARGS) { GS_UCHAR* key = NULL; GS_UINT32 keylen = 0; GS_UCHAR* plaintext = NULL; GS_UINT32 plaintextlen = 0; GS_UCHAR* ciphertext = NULL; GS_UINT32 retval = 0; GS_UCHAR* decodetext = NULL; GS_UINT32 decodetextlen = 0; text* outtext = NULL; errno_t errorno = EOK; if (PG_ARGISNULL(0)) { fcinfo->isnull = true; outtext = NULL; PG_RETURN_TEXT_P(outtext); } if (PG_ARGISNULL(1)) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("The decryption key can not be empty!"))); } decodetext = (GS_UCHAR*)(text_to_cstring(PG_GETARG_TEXT_P(0))); key = (GS_UCHAR*)(text_to_cstring(PG_GETARG_TEXT_P(1))); keylen = strlen((const char*)key); /* decode the ciphertext for decrypt operation */ ciphertext = (GS_UCHAR*)(SEC_decodeBase64((char*)decodetext, &decodetextlen)); if ((ciphertext == NULL) || (decodetextlen <= RANDOM_LEN)) { if (ciphertext != NULL) { OPENSSL_free(ciphertext); ciphertext = NULL; } errorno = memset_s(decodetext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); pfree_ext(decodetext); errorno = memset_s(key, keylen, '\0', keylen); securec_check(errorno, "\0", "\0"); pfree_ext(key); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Decode the cipher text failed or the ciphertext is too short!"))); } errorno = memset_s(decodetext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); pfree_ext(decodetext); plaintext = (GS_UCHAR*)palloc(decodetextlen); errorno = memset_s(plaintext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); /* * decrypt the ciphertext to plaintext using the new version function first * try :old vesion of decryption function if the new one failed. * if the old one also failed, return alarm. */ retval = gs_decrypt_aes_speed(ciphertext, decodetextlen, key, plaintext, &plaintextlen); if (!retval) { /* reset plaintext */ errorno = memset_s(plaintext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); /* try different decrypt function */ retval = gs_decrypt_aes(ciphertext, decodetextlen, key, plaintext, &plaintextlen); (void)fprintf(stderr, _("Try previous version of decrypt-function!\n")); } errorno = memset_s(key, keylen, '\0', keylen); securec_check(errorno, "\0", "\0"); pfree_ext(key); if (!retval) { errorno = memset_s(ciphertext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); OPENSSL_free(ciphertext); ciphertext = NULL; errorno = memset_s(plaintext, plaintextlen, '\0', plaintextlen); securec_check(errorno, "\0", "\0"); pfree_ext(plaintext); ereport( ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("decrypt the cipher text failed!"))); } errorno = memset_s(ciphertext, decodetextlen, '\0', decodetextlen); securec_check(errorno, "\0", "\0"); OPENSSL_free(ciphertext); ciphertext = NULL; outtext = cstring_to_text((char*)plaintext); errorno = memset_s(plaintext, plaintextlen, '\0', plaintextlen); securec_check(errorno, "\0", "\0"); pfree_ext(plaintext); PG_RETURN_TEXT_P(outtext); } /* * Generate random and compute plain text length. * This function use key and random to encrypt plain text * ATTENTION: * The cipherlen is an "IN&OUT" param!!!!!!! */ bool gs_encrypt_aes_128( GS_UCHAR* plaintext, GS_UCHAR* key, GS_UINT32 keylen, GS_UCHAR* ciphertext, GS_UINT32* cipherlen) { errno_t rc = 0; errno_t ret = 0; GS_UINT32 retval = 0; GS_UINT32 plainlen = 0; GS_UCHAR init_rand[RANDOM_LEN + 1] = {0}; GS_UCHAR tmp_cipher[CIPHER_LEN + 1] = {0}; bool encryptstatus = false; char* gausshome = NULL; char randfile[MAXPGPATH] = {'\0'}; char cipherfile[MAXPGPATH] = {'\0'}; size_t cipherbufferlen = (size_t)(*cipherlen); /* the result of do getKeyVectorFromCipherFile */ bool status = false; if (NULL == plaintext) { return false; } plainlen = strlen((const char*)plaintext); /* default branch should do decode */ /* -f is in key mode */ if ((NULL == g_prefix && NULL == g_key && NULL == g_vector) || (NULL != g_prefix && is_prefix_in_key_mode((const char*)g_prefix))) { /* get a random values as salt for encrypt */ retval = RAND_bytes(init_rand, RANDOM_LEN); if (retval != 1) { (void)fprintf(stderr, _("generate random key failed, errcode:%u\n"), retval); return false; } /* the real encrypt operation */ encryptstatus = aes128Encrypt(plaintext, plainlen, key, keylen, init_rand, ciphertext, cipherlen); if (!encryptstatus) { return false; } if (((size_t)(*cipherlen) + RANDOM_LEN) > cipherbufferlen) { (void)fprintf(stderr, _("ciphertext buffer is too small\n")); return false; } /* add init_rand to the end of ciphertext for decrypt */ rc = memcpy_s(ciphertext + (*cipherlen), (Size)RANDOM_LEN, init_rand, (Size)RANDOM_LEN); securec_check(rc, "\0", "\0"); } else { /* -f is not in key mode */ if (NULL != g_prefix) { gausshome = gs_getenv_r("GAUSSHOME"); char real_gausshome[MAXPGPATH * 4] = {'\0'}; // 4096 bytes is more secure. if (gausshome == NULL || realpath(gausshome, real_gausshome) == NULL || strlen(real_gausshome) >= MAXPGPATH) { (void)fprintf(stderr, _("get environment of GAUSSHOME failed or GAUSSHOME is too long.\n")); exit(1); } gausshome = real_gausshome; check_backend_env(gausshome); ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/%s.key.rand", gausshome, g_prefix); securec_check_ss(ret, "\0", "\0"); ret = snprintf_s(cipherfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/%s.key.cipher", gausshome, g_prefix); securec_check_ss(ret, "\0", "\0"); gausshome = NULL; /* get key from file */ status = getKeyVectorFromCipherFile(cipherfile, randfile, tmp_cipher, init_rand); if (status) { encryptstatus = aes128Encrypt(plaintext, plainlen, tmp_cipher, CIPHER_LEN, init_rand, ciphertext, cipherlen); if (!encryptstatus) { return false; } } if (!status) { (void)fprintf( stderr, _("Failed to decrypt key from transparent encryption random file %s.\n"), randfile); return false; } if (cipherbufferlen < ((size_t)(*cipherlen) + RANDOM_LEN)) { (void)fprintf(stderr, _("ciphertext buffer is too small.\n")); return false; } /* add init_rand to the end of ciphertext for decrypt */ rc = memcpy_s(ciphertext + (*cipherlen), (Size)RANDOM_LEN, init_rand, (Size)RANDOM_LEN); securec_check(rc, "\0", "\0"); } else { encryptstatus = aes128Encrypt(plaintext, plainlen, (GS_UCHAR*)g_key, (GS_UINT32)g_key_len, (GS_UCHAR*)g_vector, ciphertext, cipherlen); if (!encryptstatus) { return false; } if (((size_t)(*cipherlen) + (size_t)g_vector_len) > cipherbufferlen) { (void)fprintf(stderr, _("ciphertext buffer is too small\n")); return false; } /* add init_rand to the end of ciphertext for decrypt */ rc = memcpy_s(ciphertext + (*cipherlen), (Size)g_vector_len, g_vector, (Size)g_vector_len); securec_check(rc, "\0", "\0"); } } return true; } /* * Split cipher text to cipher part and random part. * This function use key and random to decrypt cipher text */ bool gs_decrypt_aes_128(GS_UCHAR* ciphertext, GS_UINT32 cipherlen, GS_UCHAR* key, GS_UINT32 keylen, GS_UCHAR* plaintext, GS_UINT32* plainlen) { errno_t rc; GS_UINT32 cipherpartlen = 0; GS_UCHAR* cipherpart = NULL; GS_UCHAR* randpart = NULL; bool decryptstatus = false; if (NULL == ciphertext) { return false; } /* split the cipher text to cipher(cipher + vector_salt) part and rand part for decrypt */ cipherpartlen = cipherlen - RANDOM_LEN; cipherpart = (GS_UCHAR*)palloc0(cipherpartlen + 1); randpart = (GS_UCHAR*)palloc0(RANDOM_LEN + 1); rc = memcpy_s(cipherpart, cipherpartlen + 1, ciphertext, cipherpartlen); securec_check(rc, "\0", "\0"); rc = memcpy_s(randpart, RANDOM_LEN + 1, ciphertext + cipherpartlen, RANDOM_LEN); securec_check(rc, "\0", "\0"); /* the real decrypt operation */ decryptstatus = aes128Decrypt(cipherpart, cipherpartlen, key, keylen, randpart, plaintext, plainlen); rc = memset_s(cipherpart, cipherpartlen + 1, 0, cipherpartlen + 1); securec_check(rc, "\0", "\0"); pfree_ext(cipherpart); rc = memset_s(randpart, RANDOM_LEN, 0, RANDOM_LEN); securec_check(rc, "\0", "\0"); pfree_ext(randpart); if (!decryptstatus) { return false; } return true; } /* * Encrypt plain text to cipher text. * This function use aes128 to encrypt plain text,key comes from certificate file */ void encryptOBS(const char* srcplaintext, char destciphertext[], uint32 destcipherlength) { errno_t rc = EOK; GS_UINT32 cipher_text_len = 512; GS_UINT32 encode_text_len = 0; GS_UCHAR* cipher_text = NULL; GS_UCHAR* decipher_key = NULL; getOBSKeyString(&decipher_key); cipher_text = (GS_UCHAR*)palloc(cipher_text_len); rc = memset_s(cipher_text, cipher_text_len, 0, cipher_text_len); securec_check(rc, "\0", "\0"); if (!gs_encrypt_aes_128((GS_UCHAR*)srcplaintext, decipher_key, (GS_UINT32)strlen((const char*)decipher_key), cipher_text, &cipher_text_len)) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Encrypt OBS AK/SK failed."))); } char* encodetext = SEC_encodeBase64((char*)cipher_text, cipher_text_len + RANDOM_LEN); if (encodetext == NULL || destcipherlength < strlen(encodetext) + 1) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Encrypt OBS AK/SK internal error"))); } encode_text_len = strlen(encodetext); rc = memcpy_s(destciphertext, destcipherlength, encodetext, (encode_text_len + 1)); securec_check(rc, "\0", "\0"); rc = memset_s(encodetext, encode_text_len + 1, 0, encode_text_len + 1); securec_check(rc, "\0", "\0"); OPENSSL_free(encodetext); encodetext = NULL; rc = memset_s(cipher_text, cipher_text_len, 0, cipher_text_len); securec_check(rc, "\0", "\0"); pfree_ext(cipher_text); rc = memset_s(decipher_key, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(rc, "\0", "\0"); pfree_ext(decipher_key); } /* * Decrypt cipher text to plain text. * This function use aes128 to decrypt cipher text,key comes from certificate file */ void decryptOBS(const char* srcciphertext, char destplaintext[], uint32 destplainlength, const char* obskey) { errno_t rc = EOK; GS_UCHAR* ciphertext = NULL; GS_UINT32 decodetextlen = 0; GS_UCHAR* plaintext = NULL; GS_UINT32 plaintextlen = 0; GS_UCHAR* decipherkey = NULL; if (NULL == srcciphertext || NULL == destplaintext) { return; } if (obskey != NULL) { decipherkey = (GS_UCHAR*)palloc(RANDOM_LEN + 1); rc = memset_s(decipherkey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(rc, "\0", "\0"); int keysize = strlen(obskey); rc = memcpy_s(decipherkey, RANDOM_LEN + 1, obskey, keysize); securec_check(rc, "\0", "\0"); } else { getOBSKeyString(&decipherkey); } ciphertext = (GS_UCHAR*)(SEC_decodeBase64((char*)srcciphertext, &decodetextlen)); plaintext = (GS_UCHAR*)palloc(decodetextlen); rc = memset_s(plaintext, decodetextlen, 0, decodetextlen); securec_check(rc, "\0", "\0"); if (!gs_decrypt_aes_128(ciphertext, decodetextlen, decipherkey, (GS_UINT32)strlen((const char*)decipherkey), plaintext, &plaintextlen)) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Decrypt OBS AK/SK failed."))); } /* 1 byte for \0 */ if (plaintextlen + 1 > destplainlength) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Decrypt OBS AK/SK internal error."))); } rc = memcpy_s(destplaintext, destplainlength, plaintext, plaintextlen); securec_check(rc, "\0", "\0"); destplaintext[plaintextlen] = '\0'; rc = memset_s(plaintext, decodetextlen, 0, decodetextlen); securec_check(rc, "\0", "\0"); pfree_ext(plaintext); rc = memset_s(decipherkey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(rc, "\0", "\0"); pfree_ext(decipherkey); /* * ciphertext should not be null. If ciphertext is null, * the processing throwed ERROR after calling gs_decrypt_aes_128 */ Assert(NULL != ciphertext); rc = memset_s(ciphertext, decodetextlen, 0, decodetextlen); securec_check(rc, "\0", "\0"); OPENSSL_free(ciphertext); ciphertext = NULL; } void getOBSKeyString(GS_UCHAR** cipherKey) { /* * Notice: cypherKey will be overwritten. */ Assert(NULL == *cipherKey); int ret = 0; char* cipherpath = NULL; char cipherkeyfile[MAXPGPATH] = {'\0'}; char isexistscipherkeyfile[MAXPGPATH] = {'\0'}; /* * Important: function getenv() is not thread safe. */ LWLockAcquire(OBSGetPathLock, LW_SHARED); cipherpath = gs_getenv_r("GAUSSHOME"); char real_gausshome[PATH_MAX] = {'\0'}; LWLockRelease(OBSGetPathLock); check_backend_env(cipherpath); if (realpath(cipherpath, real_gausshome) == NULL) { (void)fprintf(stderr, _("Get environment of GAUSSHOME failed or it is invalid.\n")); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to get OBS certificate file."))); } cipherpath = real_gausshome; ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin", cipherpath); securec_check_ss(ret, "\0", "\0"); ret = snprintf_s(isexistscipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/obsserver.key.cipher", cipherpath); securec_check_ss_c(ret, "\0", "\0"); *cipherKey = (GS_UCHAR*)palloc(RANDOM_LEN + 1); ret = memset_s(*cipherKey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); // proccess for unit test failed for no obsserver key if (file_exists(isexistscipherkeyfile)) { decode_cipher_files(OBS_MODE, NULL, cipherkeyfile, *cipherKey); } else { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FILE), errmsg("No key file %s", isexistscipherkeyfile), errhint("Please create %s file with gs_guc, such as : gs_guc generate -S XXX -D $GAUSSHOME/bin -o " "obsserver", isexistscipherkeyfile))); } } /* * Target :Encrypt functions for security. * Description :Generating random salt if there is not a saved one, * and then use the random salt to encrypt plaintext. * Input :Pointer of plaintext, key, ciphertext and cipherlen * Output :successed: true, failed: false. */ bool gs_encrypt_aes_speed(GS_UCHAR* plaintext, GS_UCHAR* key, GS_UCHAR* ciphertext, GS_UINT32* cipherlen) { GS_UINT32 retval = 0; GS_UINT32 plainlen = 0; GS_UCHAR init_rand[RANDOM_LEN] = {0}; bool encryptstatus = false; errno_t errorno = EOK; /* use saved random salt unless unavailable */ static THR_LOCAL GS_UCHAR random_salt_saved[RANDOM_LEN] = {0}; static THR_LOCAL bool random_salt_tag = false; static THR_LOCAL GS_UINT64 random_salt_count = 0; /* A limitation of using times of one random salt */ const GS_UINT64 random_salt_count_max = 24000000; if (random_salt_tag == false || random_salt_count > random_salt_count_max) { /* get a random values as salt for encrypt */ retval = RAND_bytes(init_rand, RANDOM_LEN); if (retval != 1) { (void)fprintf(stderr, _("generate random key failed,errcode:%u\n"), retval); return false; } random_salt_tag = true; errorno = memcpy_s(random_salt_saved, RANDOM_LEN, init_rand, RANDOM_LEN); securec_check(errorno, "\0", "\0"); random_salt_count = 0; } else { errorno = memcpy_s(init_rand, RANDOM_LEN, random_salt_saved, RANDOM_LEN); securec_check(errorno, "\0", "\0"); random_salt_count++; } plainlen = strlen((const char*)plaintext); /* the real encrypt operation */ encryptstatus = aes128EncryptSpeed(plaintext, plainlen, key, init_rand, ciphertext, cipherlen); if (!encryptstatus) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("aes128EncryptSpeedFailed!"))); return false; } /* add init_rand to the head of ciphertext for decrypt */ GS_UCHAR mac_temp[MAC_LEN] = {0}; errorno = memcpy_s(mac_temp, MAC_LEN, ciphertext + *cipherlen - MAC_LEN, MAC_LEN); securec_check(errorno, "\0", "\0"); errorno = memcpy_s(ciphertext + *cipherlen - MAC_LEN + RANDOM_LEN, MAC_LEN, mac_temp, MAC_LEN); securec_check(errorno, "\0", "\0"); GS_UCHAR temp[RANDOM_LEN] = {0}; for (GS_UINT32 i = (*cipherlen - MAC_LEN) / RANDOM_LEN; i >= 1; --i) { errorno = memcpy_s(temp, RANDOM_LEN, ciphertext + (i - 1) * RANDOM_LEN, RANDOM_LEN); securec_check(errorno, "\0", "\0"); errorno = memcpy_s(ciphertext + i * RANDOM_LEN, RANDOM_LEN, temp, RANDOM_LEN); securec_check(errorno, "\0", "\0"); } errorno = memcpy_s(ciphertext, RANDOM_LEN, init_rand, RANDOM_LEN); securec_check(errorno, "\0", "\0"); *cipherlen = *cipherlen + RANDOM_LEN; errorno = memset_s(temp, RANDOM_LEN, '\0', RANDOM_LEN); securec_check(errorno, "\0", "\0"); return true; } /* * Target :Decrypt functions for security. * Description :Read random salt from ciphertext, * and then use the random salt to decrypt plaintext. * Input :Pointer of plaintext, key, ciphertext and the value of cipherlen and plainlen. * Output :successed: true, failed: false. */ bool gs_decrypt_aes_speed( GS_UCHAR* ciphertext, GS_UINT32 cipherlen, GS_UCHAR* key, GS_UCHAR* plaintext, GS_UINT32* plainlen) { GS_UINT32 cipherpartlen = 0; GS_UCHAR* cipherpart = NULL; GS_UCHAR* randpart = NULL; bool decryptstatus = false; errno_t errorno = EOK; if (cipherlen < (3 * RANDOM_LEN + MAC_LEN)) { (void)fprintf(stderr, _("Cipertext is too short to decrypt\n")); return false; } cipherpartlen = cipherlen - RANDOM_LEN; /* split the ciphertext to cipherpart and randpart for decrypt */ cipherpart = (GS_UCHAR*)palloc(cipherpartlen + 1); randpart = (GS_UCHAR*)palloc(RANDOM_LEN); errorno = memcpy_s(cipherpart, cipherpartlen + 1, ciphertext + RANDOM_LEN, cipherpartlen); securec_check(errorno, "\0", "\0"); errorno = memcpy_s(randpart, RANDOM_LEN, ciphertext, RANDOM_LEN); securec_check(errorno, "\0", "\0"); /* the real decrypt operation */ decryptstatus = aes128DecryptSpeed(cipherpart, cipherpartlen, key, randpart, plaintext, plainlen); errorno = memset_s(cipherpart, cipherpartlen + 1, '\0', cipherpartlen + 1); securec_check(errorno, "\0", "\0"); pfree_ext(cipherpart); errorno = memset_s(randpart, RANDOM_LEN, '\0', RANDOM_LEN); securec_check(errorno, "\0", "\0"); pfree_ext(randpart); if (!decryptstatus) { return false; } else { return true; } } /* * getECKeyString: * Get Extension Connector(EC) key string * * @IN/OUT cipherKey: get key string and stored in cipherKey * @RETURN: void */ static GS_UCHAR* getECKeyString(void) { GS_UCHAR* plainkey = NULL; char* gshome = NULL; char cipherdir[MAXPGPATH] = {0}; char cipherfile[MAXPGPATH] = {0}; int ret = 0; /* * Get cipher file and prepare the plain buffer */ gshome = gs_getenv_r("GAUSSHOME"); char real_gausshome[PATH_MAX] = {'\0'}; check_backend_env(gshome); if (realpath(gshome, real_gausshome) == NULL) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to get EC certificate file: get env GAUSSHOME failed."))); } gshome = real_gausshome; check_backend_env(gshome); ret = snprintf_s(cipherdir, MAXPGPATH, MAXPGPATH - 1, "%s/bin", gshome); securec_check_ss(ret, "\0", "\0"); ret = snprintf_s(cipherfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/datasource.key.cipher", gshome); securec_check_ss_c(ret, "\0", "\0"); gshome = NULL; /* Alloc plain key buffer and clear it */ plainkey = (GS_UCHAR*)palloc(RANDOM_LEN + 1); ret = memset_s(plainkey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); /* * Decode cipher file, if not given SOURCE cipher file, we use SERVER mode */ if (file_exists(cipherfile)) { decode_cipher_files(SOURCE_MODE, NULL, cipherdir, plainkey); } else { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FILE), errmsg("No key file %s", cipherfile), errhint("Please create %s file with gs_guc and gs_ssh, such as : gs_ssh -c \"gs_guc generate -S XXX -D " "$GAUSSHOME/bin -o datasource\"", cipherfile))); } /* * Note: plainkey is of length RANDOM_LEN + 1 */ return plainkey; } /* * encryptECString: * Encrypt Extension Connector(EC) string(username/password, etc.) into cipher text. * This function use aes128 to encrypt plain text; key comes from certificate file * * @IN src_plain_text: source plain text to be encrypted * @OUT dest_cipher_text: dest buffer to be filled with encrypted string, this buffer * should be given by caller * @IN dest_cipher_length: dest buffer length which is given by the caller * @RETURN: void */ void encryptECString(const char* src_plain_text, char* dest_cipher_text, uint32 dest_cipher_length) { GS_UINT32 cipher_text_len = 0; GS_UCHAR cipher_text[1024]; GS_UCHAR* cipher_key = NULL; char* encode_text = NULL; GS_UINT32 encode_text_len = 0; errno_t ret = EOK; if (NULL == src_plain_text) { return; } /* First, get encrypt key */ cipher_key = getECKeyString(); /* Clear cipher buffer which will be used later */ ret = memset_s(cipher_text, sizeof(cipher_text), 0, sizeof(cipher_text)); securec_check(ret, "\0", "\0"); /* * Step-1: Cipher * src_text with cipher key -> cipher text */ cipher_text_len = (GS_UINT32)sizeof(cipher_text); if (!gs_encrypt_aes_128((GS_UCHAR*)src_plain_text, cipher_key, (GS_UINT32)strlen((const char*)cipher_key), cipher_text, &cipher_text_len)) { ereport( ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("encrypt the EC string failed!"))); } /* * Step-2: Encode * cipher text by Base64 -> encode text */ encode_text = SEC_encodeBase64((char*)cipher_text, cipher_text_len + RANDOM_LEN); /* Check dest buffer length */ if (encode_text == NULL || dest_cipher_length < strlen(EC_ENCRYPT_PREFIX) + strlen(encode_text) + 1) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Encrypt EC internal error: dest cipher length is too short."))); } encode_text_len = strlen(encode_text); /* Copy the encrypt string into the dest buffer */ ret = memcpy_s(dest_cipher_text, dest_cipher_length, EC_ENCRYPT_PREFIX, strlen(EC_ENCRYPT_PREFIX)); securec_check(ret, "\0", "\0"); ret = memcpy_s(dest_cipher_text + strlen(EC_ENCRYPT_PREFIX), dest_cipher_length - strlen(EC_ENCRYPT_PREFIX), encode_text, encode_text_len + 1); securec_check(ret, "\0", "\0"); /* Clear buffer for safety's sake */ ret = memset_s(encode_text, encode_text_len, 0, encode_text_len); securec_check(ret, "\0", "\0"); ret = memset_s(cipher_text, sizeof(cipher_text), 0, sizeof(cipher_text)); securec_check(ret, "\0", "\0"); ret = memset_s(cipher_key, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); OPENSSL_free(encode_text); encode_text = NULL; pfree_ext(cipher_key); } /* * decryptECString: * Decrypt Extension Connector(EC) string(username/password, etc.) into plain text. * This function use aes128 to decrypt cipher text; key comes from certificate file * * @IN src_cipher_text: source cipher text to be decrypted * @OUT dest_plain_text: dest buffer to be filled with plain text, this buffer * should be given by caller * @IN dest_plain_length: dest buffer length which is given by the caller * @RETURN: void */ void decryptECString(const char* src_cipher_text, char* dest_plain_text, uint32 dest_plain_length) { GS_UCHAR* ciphertext = NULL; GS_UINT32 ciphertextlen = 0; GS_UCHAR* plaintext = NULL; GS_UINT32 plaintextlen = 0; GS_UCHAR* cipherkey = NULL; errno_t ret = EOK; if (NULL == src_cipher_text || !IsECEncryptedString(src_cipher_text)) { return; } /* Get key string */ cipherkey = getECKeyString(); /* Step-1: Decode */ ciphertext = (GS_UCHAR*)(SEC_decodeBase64((char*)(src_cipher_text + strlen(EC_ENCRYPT_PREFIX)), &ciphertextlen)); plaintext = (GS_UCHAR*)palloc(ciphertextlen); ret = memset_s(plaintext, ciphertextlen, 0, ciphertextlen); securec_check(ret, "\0", "\0"); /* Step-2: Decipher */ if (!gs_decrypt_aes_128(ciphertext, ciphertextlen, cipherkey, (GS_UINT32)strlen((const char*)cipherkey), plaintext, &plaintextlen)) { ereport( ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("decrypt the EC string failed!"))); } /* Check dest buffer length */ if (plaintextlen > dest_plain_length) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Decrypt EC internal error: dest plain length is too short."))); } /* Copy the decrypted string into the dest buffer */ ret = memcpy_s(dest_plain_text, dest_plain_length, plaintext, plaintextlen); securec_check(ret, "\0", "\0"); /* Clear the buffer for safety's sake */ ret = memset_s(plaintext, plaintextlen, 0, plaintextlen); securec_check(ret, "\0", "\0"); ret = memset_s(cipherkey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); ret = memset_s(ciphertext, ciphertextlen, 0, ciphertextlen); securec_check(ret, "\0", "\0"); pfree_ext(plaintext); pfree_ext(cipherkey); OPENSSL_free(ciphertext); ciphertext = NULL; } /* * IsECEncryptedString: * check the input string whether encypted * * @IN src_cipher_text: source cipher text to be decrypted * @RETURN: bool, true if encrypted, false if not */ bool IsECEncryptedString(const char* src_cipher_text) { if (NULL == src_cipher_text || strlen(src_cipher_text) <= RANDOM_LEN + strlen(EC_ENCRYPT_PREFIX)) { return false; } if (0 == strncmp(src_cipher_text, EC_ENCRYPT_PREFIX, strlen(EC_ENCRYPT_PREFIX))) { return true; } else { return false; } } /* * encryptBlockAndCU: * encrypt block or CU exclude header and filling,user data must encrypt,if block or cu encrypt failed, * retry three times,if it still failed then quit process,shoud use panic not fatal for result in hang * on checkpoint or bgwriter * @IN plain text and plain text length * @OUT cipher text and cipher text length * @RETURN: NONE */ void encryptBlockOrCUData(const char* plainText, const size_t plainLength, char* cipherText, size_t* cipherLength) { int retryCnt = 0; GS_UINT32 ret = 0; /* * decrypt block or CU exclude header and filling,user data must decrypt,if block or cu decrypt failed, * retry three times,if it still failed then quit process,shoud use panic not fatal for result in hang * on autovacuum * * @IN cipher text and cipher text length * @OUT plain text and plain text length * @RETURN: NONE */ if ((trans_encrypt_dek == NULL || *trans_encrypt_dek == '\0') || (trans_encrypt_iv == NULL || *trans_encrypt_iv == '\0')) { ereport(PANIC, (errmsg("it's an encrypted cluster, but parameter not initialized!"), errdetail("decrypt DEK or IV is empty or both length is not equal 16"))); } do { if (g_tde_algo == TDE_ALGO_SM4_CTR_128) { ret = sm4_ctr_enc_partial_mode( plainText, plainLength, cipherText, cipherLength, trans_encrypt_dek, trans_encrypt_iv); } else { ret = aes_ctr_enc_partial_mode( plainText, plainLength, cipherText, cipherLength, trans_encrypt_dek, trans_encrypt_iv); } if (ret != 0) { retryCnt++; } else { if (plainLength != *cipherLength) { ereport(PANIC, (errmsg("encrypt failed, return code is %u!", ret), errdetail("cipher length is not correct, \ plian length is %lu, cipher length is %lu", plainLength, *cipherLength))); } return; } if (retryCnt == 2) { ereport(PANIC, (errmsg("encrypt failed after retry three times, error code is %u!", ret), errdetail("ret code is Invalid arguments or \ Invalid IV length or Internal error "))); } } while (retryCnt < 3); } /* * decrypt block or CU exclude header and filling,user data must decrypt,if block or cu decrypt failed, * retry three times,if it still failed then quit process,shoud use panic not fatal for result in hang * on autovacuum * * @IN cipher text and cipher text length * @OUT plain text and plain text length * @RETURN: NONE */ void decryptBlockOrCUData(const char* cipherText, const size_t cipherLength, char* plainText, size_t* plainLength) { int retryCnt = 0; GS_UINT32 ret = 0; if ((trans_encrypt_dek == NULL || *trans_encrypt_dek == '\0') || (trans_encrypt_iv == NULL || *trans_encrypt_iv == '\0')) { ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("it's an encrypted cluster, but parameter not initialized!"), errdetail("decrypt DEK or IV is empty or both length is not equal 16"))); } do { if (g_tde_algo == TDE_ALGO_SM4_CTR_128) { ret = sm4_ctr_dec_partial_mode( cipherText, cipherLength, plainText, plainLength, trans_encrypt_dek, trans_encrypt_iv); } else { ret = aes_ctr_dec_partial_mode( cipherText, cipherLength, plainText, plainLength, trans_encrypt_dek, trans_encrypt_iv); } if (ret != 0) { retryCnt++; } else { if (cipherLength != *plainLength) { ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), errmsg("decrypt failed, return code is %u!", ret), errdetail("plainLength length is not correct, cipher length is %lu,plian length is %lu", cipherLength, *plainLength))); } return; } if (retryCnt == 2) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("decrypt failed after retry three times, error code is %u!", ret), errdetail("ret code is Invalid arguments or Invalid IV length or Internal error "))); } } while (retryCnt < 3); } /* Get the FI root cert */ void add_fi_ca_cert() { if (g_fi_ca_path != NULL) { return; } char* node_agent_env = gs_getenv_r("NODE_AGENT_HOME"); if (node_agent_env == NULL) { ereport(WARNING, (errmsg("Transparent encryption Getting environment variable NODE_AGENT_HOME."))); return; } check_backend_env(node_agent_env); g_fi_ca_path = (char*)palloc0(MAXPGPATH); int ret = snprintf_s(g_fi_ca_path, MAXPGPATH, MAXPGPATH - 1, "%s/security/cert/subcert/certFile/ca.crt", node_agent_env); securec_check_ss_c(ret, "\0", "\0"); } /* Using MPPDB_KRB5_FILE_PATH instead of KRB5_CONF. Add the FI root cert. */ void init_the_kerberos_env() { char* gaussdb_krb5_env = gs_getenv_r("MPPDB_KRB5_FILE_PATH"); if (gaussdb_krb5_env == NULL) { ereport(WARNING, (errmsg("Transparent encryption Getting environment variable MPPDB_KRB5_FILE_PATH NULL."))); return; } check_backend_env(gaussdb_krb5_env); krb5_set_profile_path(gaussdb_krb5_env); add_fi_ca_cert(); } static void do_advice(void) { (void)printf(_("Try \"%s --help\" for more information.\n"), pgname); } static void do_help(void) { (void)printf(_("%s is an inferface to encrypt input plaintext string.\n\n"), pgname); (void)printf(_("Usage:\n")); (void)printf(_(" %s [OPTION]... PLAINTEXT\n"), pgname); (void)printf(_("\nGeneral options:\n")); (void)printf(_(" -?, --help show this help, then exit.\n")); (void)printf(_(" -V, --version output version information, then exit.\n")); (void)printf(_(" -k, --key=Value the key value for AES128.\n")); (void)printf(_(" -v, --vector=Value the random value for AES128.\n")); (void)printf(_(" -f, --file-prefix=Value the cipher files prefix.\n")); (void)printf(_(" -B, --key-base64=Value the key value encoded in base64.\n")); (void)printf(_(" -D, --vector-base64=Value the random value encoded in base64.\n")); (void)printf(_(" -N, --key-name=value the cluster key name in KMS.\n")); (void)printf(_(" -U, --kms-url-=value the kms internet address.for " "example,\"kms://https@host2;host3:29800/kms\".\n")); (void)printf(_(" -I, --init=value init the tde key.the value must be SM4-CTR-128 or AES-CTR-128.\n")); (void)printf(_(" PLAINTEXT the plain text you want to encrypt.\n")); } /* * @@GaussDB@@ * Brief : IsLegalPreix() * Input : prefixStr -> the input parameter value * Description : check the parameter. It is only support digit/alpha/'-'/'_' */ bool IsLegalPreix(const char* prefixStr) { int NBytes = int(strlen(prefixStr)); for (int i = 0; i < NBytes; i++) { /* check whether the character is correct */ if (IsIllegalCharacter(prefixStr[i])) { return false; } } return true; } static void free_global_value(void) { GS_FREE(g_prefix); GS_FREE(g_key); GS_FREE(g_vector); } static bool is_prefix_in_key_mode(const char* mode) { int slen = strlen("server"); int clen = strlen("client"); int srclen = strlen("source"); int obslen = strlen("obsserver"); int sm4len = strlen("SM4-CTR-128"); int aeslen = strlen("AES-CTR-128"); if ((0 == strncmp(mode, "server", slen) && '\0' == mode[slen]) || (0 == strncmp(mode, "client", clen) && '\0' == mode[clen]) || (0 == strncmp(mode, "source", srclen) && '\0' == mode[srclen]) || (0 == strncmp(mode, "obsserver", obslen) && '\0' == mode[obslen]) || (0 == strncmp(mode, "SM4-CTR-128", sm4len) && '\0' == mode[sm4len]) || (0 == strncmp(mode, "AES-CTR-128", aeslen) && '\0' == mode[aeslen])) { return true; } else { return false; } } #define CIPHERTEXT_LEN 512 int encrypte_main(int argc, char* const argv[]) { #define MAXLOGINFOLEN 1024 static struct option long_options[] = {{"help", no_argument, NULL, '?'}, {"version", no_argument, NULL, 'V'}, {"file-prefix", required_argument, NULL, 'f'}, {"key", required_argument, NULL, 'k'}, {"vector", required_argument, NULL, 'v'}, {"key-base64", required_argument, NULL, 'B'}, {"vector-base64", required_argument, NULL, 'D'}, {"init", required_argument, NULL, 'I'}, {"key-name", required_argument, NULL, 'N'}, {"kms-url", required_argument, NULL, 'U'}, {NULL, 0, NULL, 0}}; int ret = 0; int result = 0; GS_UCHAR* plaintext = NULL; GS_UCHAR* ciphertext = NULL; GS_UINT32 ciphertextlen = 0; char* encode_text = NULL; GS_UINT32 encode_text_len = 0; GS_UCHAR* decipherkey = NULL; char* kmsurl = NULL; char* keyname = NULL; char* tdealgo = NULL; char* cipherpath = NULL; char cipherkeyfile[MAXPGPATH] = {'\0'}; char destciphertext[CIPHERTEXT_LEN] = {0}; char isexistscipherkeyfile[MAXPGPATH] = {'\0'}; char isexistsrandfile[MAXPGPATH] = {'\0'}; int c = 0; int optindex = 0; errno_t rc = 0; set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("gs_encrypt")); /* support --help and --version even if invoked as root */ if (argc > 1) { if (strncmp(argv[1], "--help", sizeof("--help")) == 0 || strncmp(argv[1], "-?", sizeof("-?")) == 0) { do_help(); exit(0); } else if (strncmp(argv[1], "-V", sizeof("-V")) == 0 || strncmp(argv[1], "--version", sizeof("--version")) == 0) { puts("gs_encrypt " DEF_GS_VERSION); exit(0); } } /* process command-line options */ while ((c = getopt_long(argc, argv, "f:v:k:B:D:I:N:U:", long_options, &optindex)) != -1) { switch (c) { case 'f': { GS_FREE(g_prefix); g_prefix = gs_strdup(optarg); if (0 == strlen(g_prefix) || !IsLegalPreix(g_prefix)) { (void)fprintf(stderr, _("%s: -f only be formed of 'a~z', 'A~Z', '0~9', '-', '_'\n"), pgname); do_advice(); exit(1); } break; } case 'v': { GS_FREE(g_vector); g_vector = gs_strdup(optarg); // the length of g_vector must equal to 16 if (strlen(g_vector) != RANDOM_LEN) { (void)fprintf(stderr, _("%s: the length of -v must equal to %d\n"), pgname, RANDOM_LEN); do_advice(); exit(1); } g_vector_len = (int)strlen(g_vector); break; } case 'k': { GS_FREE(g_key); g_key = gs_strdup(optarg); if (0 == strlen(optarg) || !mask_single_passwd(optarg)) { (void)fprintf(stderr, _("%s: mask passwd failed. optarg is null, or out of memory!\n"), pgname); do_advice(); exit(1); }; g_key_len = (int)strlen(g_key); break; } case 'B': { GS_UCHAR* decoded_key = NULL; GS_UINT32 decodelen = 0; GS_FREE(g_key); decoded_key = (GS_UCHAR*)SEC_decodeBase64(optarg, &decodelen); if (decoded_key == NULL || decodelen == 0) { (void)fprintf(stderr, _("%s: failed to decode base64 encoded key.\n"), pgname); do_advice(); exit(1); } g_key = (char*)decoded_key; g_key_len = (int)decodelen; break; } case 'D': { GS_UCHAR* decoded_vector = NULL; GS_UINT32 decodelen = 0; GS_FREE(g_vector); decoded_vector = (GS_UCHAR*)SEC_decodeBase64(optarg, &decodelen); if (decoded_vector == NULL || decodelen == 0) { (void)fprintf(stderr, _("%s: failed to decode base64 encoded vector.\n"), pgname); do_advice(); exit(1); } // the length of g_vector must equal to 16 if (decodelen != RANDOM_LEN) { (void)fprintf( stderr, _("%s: the decoded length of vector must be equal to %d.\n"), pgname, RANDOM_LEN); do_advice(); exit(1); } g_vector = (char*)decoded_vector; g_vector_len = (int)decodelen; break; } case 'N': { keyname = gs_strdup(optarg); if (keyname == NULL) { (void)fprintf(stderr, _("%s: Key name is wrrong,it must be usable!\n"), pgname); do_advice(); exit(1); } break; } case 'U': { kmsurl = gs_strdup(optarg); if (kmsurl == NULL) { (void)fprintf( stderr, _("%s: KMS url is wrrong,it must be an accessible network address.\n"), pgname); do_advice(); exit(1); } break; } case 'I': { tdealgo = gs_strdup(optarg); if (tdealgo == NULL || !is_prefix_in_key_mode(tdealgo)) { (void)fprintf(stderr, _("%s: Init TDE failed. optarg is wrrong, it must be SM4-CTR-128 or AES-CTR-128.\n"), pgname); do_advice(); exit(1); } } break; default: do_help(); exit(1); } } /* init the key */ if (tdealgo != NULL) { if (keyname == NULL) { (void)fprintf(stderr, _("%s: Init TDE failed.keyname is wrrong,you must add -N keyname.\n"), pgname); do_advice(); exit(1); } init_the_kerberos_env(); KeyManager table_a_key("0", "0"); // next version for different tabe and database. char* gausshome = getGaussHome(); if (gausshome == NULL) { (void)fprintf(stderr, _("%s: Getting environment variable $GAUSSHOME error, please check.\n"), pgname); exit(1); } table_a_key.setfile(gausshome); if (kmsurl != NULL) { g_instance.attr.attr_common.transparent_encrypt_kms_url = kmsurl; } if (!table_a_key.init_Key(tdealgo, keyname)) { (void)fprintf(stderr, _("%s: Key inited error,please check net.\n"), pgname); do_advice(); exit(1); } if (getAndCheckTranEncryptDEK() && trans_encrypt_dek != NULL) { (void)fprintf(stdout, _("%s: Inited sucess!\n"), pgname); } else { (void)fprintf(stderr, _("%s: The key value is fail,please check kms.\n"), pgname); exit(1); } exit(0); } if (kmsurl != NULL) { free(kmsurl); kmsurl = NULL; } if (keyname != NULL) { free(keyname); keyname = NULL; } /* Get plaintext from command line */ if (optind < argc) { plaintext = (GS_UCHAR*)argv[optind++]; } /* Complain if any arguments remain */ if (optind < argc) { (void)fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), pgname, argv[optind]); (void)fprintf(stderr, _("Try \"%s --help\" for more information.\n"), pgname); free_global_value(); exit(1); } if (NULL == plaintext || 0 == strlen((char*)plaintext)) { (void)fprintf(stderr, _("%s: options PLAINTEXT must be input and it is not null\n"), pgname); free_global_value(); exit(1); } /* check the parameter value */ if ((NULL == g_key && NULL != g_vector) || (NULL != g_key && NULL == g_vector)) { (void)fprintf(stderr, _("%s: key and vector should be both specified.\n"), pgname); free_global_value(); exit(1); } if (NULL != g_prefix && (NULL != g_key || NULL != g_vector)) { (void)fprintf(stderr, _("%s: key/vector and cipher files cannot be used together.\n"), pgname); free_global_value(); exit(1); } cipherpath = gs_getenv_r("GAUSSHOME"); char real_gausshome[PATH_MAX] = {'\0'}; check_backend_env(cipherpath); if (realpath(cipherpath, real_gausshome) == NULL) { (void)fprintf(stderr, _("get environment of GAUSSHOME failed.\n")); free_global_value(); return -1; } cipherpath = real_gausshome; char* tmp_cipherpath = (char*)malloc(strlen(cipherpath) + 1); if (tmp_cipherpath == NULL) { (void)fprintf(stderr, _("memory is temporarily unavailable.\n")); free_global_value(); return -1; } rc = strcpy_s(tmp_cipherpath, strlen(cipherpath) + 1, cipherpath); securec_check(rc, "\0", "\0"); ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin", cipherpath); securec_check_ss(ret, "\0", "\0"); /* set the g_prefix default value */ if (NULL != g_prefix) { ret = snprintf_s( isexistscipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/%s.key.cipher", tmp_cipherpath, g_prefix); securec_check_ss_c(ret, "\0", "\0"); ret = snprintf_s(isexistsrandfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/%s.key.rand", tmp_cipherpath, g_prefix); securec_check_ss_c(ret, "\0", "\0"); if (!file_exists(isexistscipherkeyfile) || !file_exists(isexistsrandfile)) { (void)fprintf(stderr, _("%s: options -f is not correct. Failed to get cipher file[%s] and random file[%s]\n"), pgname, isexistscipherkeyfile, isexistsrandfile); free(tmp_cipherpath); tmp_cipherpath = NULL; free_global_value(); exit(1); } } else { ret = snprintf_s(isexistscipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/obsserver.key.cipher", tmp_cipherpath); securec_check_ss_c(ret, "\0", "\0"); } free(tmp_cipherpath); tmp_cipherpath = NULL; cipherpath = NULL; ciphertext = (GS_UCHAR*)malloc(RANDOM_LEN + 1); if (ciphertext == NULL) { (void)fprintf(stderr, _("memory is temporarily unavailable.\n")); result = -1; goto ENCRYPTE_MAIN_EXIT; } ret = memset_s(ciphertext, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); /* default branch should do decode */ /* -f is in key mode */ if ((NULL == g_prefix && NULL == g_key && NULL == g_vector) || (NULL != g_prefix && is_prefix_in_key_mode((const char*)g_prefix))) { /* get key from file */ if (file_exists(isexistscipherkeyfile)) { decode_cipher_files(OBS_MODE, NULL, cipherkeyfile, ciphertext); } else { decode_cipher_files(SERVER_MODE, NULL, cipherkeyfile, ciphertext, true); } } decipherkey = ciphertext; ciphertext = (GS_UCHAR*)malloc(CIPHERTEXT_LEN); if (ciphertext == NULL) { (void)fprintf(stderr, _("memory is temporarily unavailable.\n")); result = -1; goto ENCRYPTE_MAIN_EXIT; } ret = memset_s(ciphertext, CIPHERTEXT_LEN, 0, CIPHERTEXT_LEN); securec_check(ret, "\0", "\0"); ciphertextlen = CIPHERTEXT_LEN; if (!gs_encrypt_aes_128((GS_UCHAR*)plaintext, decipherkey, (GS_UINT32)strlen((const char*)decipherkey), ciphertext, &ciphertextlen)) { (void)fprintf(stderr, _("Encrypt input text failed.\n")); result = -1; goto ENCRYPTE_MAIN_EXIT; } encode_text = SEC_encodeBase64((char*)ciphertext, ciphertextlen + RANDOM_LEN); if (NULL == encode_text) { (void)fprintf(stderr, _("Encrypt input text internal error.\n")); result = -1; goto ENCRYPTE_MAIN_EXIT; } encode_text_len = strlen(encode_text); if (CIPHERTEXT_LEN < encode_text_len + 1) { (void)fprintf(stderr, _("Encrypt input text internal error.\n")); result = -1; goto ENCRYPTE_MAIN_EXIT; } ret = memcpy_s(destciphertext, CIPHERTEXT_LEN, encode_text, (encode_text_len + 1)); securec_check(ret, "\0", "\0"); (void)fprintf(stdout, _("%s\n"), destciphertext); ENCRYPTE_MAIN_EXIT: /* clean all footprint for security. */ if (encode_text != NULL) { ret = memset_s(encode_text, encode_text_len + 1, 0, encode_text_len + 1); securec_check(ret, "\0", "\0"); OPENSSL_free(encode_text); encode_text = NULL; } if (ciphertext != NULL) { ret = memset_s(ciphertext, CIPHERTEXT_LEN, 0, CIPHERTEXT_LEN); securec_check(ret, "\0", "\0"); free(ciphertext); ciphertext = NULL; } if (decipherkey != NULL) { ret = memset_s(decipherkey, RANDOM_LEN + 1, 0, RANDOM_LEN + 1); securec_check(ret, "\0", "\0"); free(decipherkey); decipherkey = NULL; } free_global_value(); return result; } /* * Read key and vector from cipher key and random file. * key: must be with length of CIPHER_LEN + 1 * vector: must be with length of CIPHER_LEN + 1. * Which is the random of cipherkeyfile. */ bool getKeyVectorFromCipherFile(char* cipherkeyfile, const char* cipherrndfile, GS_UCHAR* key, GS_UCHAR* vector) { GS_UINT32 plainlen = 0; RandkeyFile rand_file_content; CipherkeyFile cipher_file_content; int ret = 0; if (!ReadContentFromFile(cipherkeyfile, &cipher_file_content, sizeof(cipher_file_content)) || !ReadContentFromFile(cipherrndfile, &rand_file_content, sizeof(rand_file_content))) { (void)fprintf(stderr, _("Failed to read contents of cipher files of transparent encryption: %s, %s.\n"), cipherkeyfile, cipherrndfile); return false; } if (!CipherFileIsValid(&cipher_file_content) || !RandFileIsValid(&rand_file_content)) { ClearCipherKeyFile(&cipher_file_content); ClearRandKeyFile(&rand_file_content); (void)fprintf( stderr, _("Corrupt cipher files of transparent encryption: %s, %s.\n"), cipherkeyfile, cipherrndfile); return false; } if (!DecryptInputKey(cipher_file_content.cipherkey, CIPHER_LEN, rand_file_content.randkey, cipher_file_content.key_salt, cipher_file_content.vector_salt, key, &plainlen)) { ClearCipherKeyFile(&cipher_file_content); ClearRandKeyFile(&rand_file_content); return false; } ret = memcpy_s( vector, sizeof(rand_file_content.randkey), rand_file_content.randkey, sizeof(rand_file_content.randkey)); securec_check_c(ret, "", ""); return true; } /* getTransEncryptKeyString: * Get the key which used to encrypted ak/sk in transparent encryption. * cipherKey: [input] Pointer to the buffer pointer which stores the key in trans_encrypt.key.cipher. * rndm: [input] Pointer to the buffer pointer which stores the vector(random) value in * trans_encrypt.key.rand. * NOTICE: The caller should free the memory allocated to *cipherKey and *rndm */ bool getTransEncryptKeyString(GS_UCHAR** cipherKey, GS_UCHAR** rndm) { int ret = 0; char* gausshome = NULL; char cipherkeyfile[MAXPGPATH] = {'\0'}; char cipherrndfile[MAXPGPATH] = {'\0'}; gausshome = getGaussHome(); ret = snprintf_s(cipherrndfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/trans_encrypt" RAN_KEY_FILE, gausshome); securec_check_ss_c(ret, "\0", "\0"); ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/trans_encrypt" CIPHER_KEY_FILE, gausshome); securec_check_ss_c(ret, "\0", "\0"); pfree_ext(gausshome); gausshome = NULL; *cipherKey = (GS_UCHAR*)malloc(CIPHER_LEN + 1); if (*cipherKey == NULL) { (void)fprintf(stderr, _("Out of memory while getting transparent encryption key string.")); return false; } ret = memset_s(*cipherKey, CIPHER_LEN + 1, 0, CIPHER_LEN + 1); securec_check_c(ret, "\0", "\0"); /* Here we use CIPHER_LEN, because that CipherkeyFile.vector is with length of CIPHER_LEN+1 */ *rndm = (GS_UCHAR*)malloc(CIPHER_LEN + 1); if (NULL == *rndm) { (void)fprintf(stderr, _("Out of memory while getting transparent encryption key string.")); free(*cipherKey); *cipherKey = NULL; return false; } ret = memset_s(*rndm, CIPHER_LEN + 1, 0, CIPHER_LEN + 1); securec_check_c(ret, "\0", "\0"); if (!file_exists(cipherkeyfile)) { (void)fprintf(stderr, _("%s not exists."), cipherkeyfile); free(*cipherKey); free(*rndm); *cipherKey = NULL; *rndm = NULL; return false; } else if (!file_exists(cipherrndfile)) { (void)fprintf(stderr, _("%s not exists."), cipherrndfile); free(*cipherKey); free(*rndm); *cipherKey = NULL; *rndm = NULL; return false; } else if (!getKeyVectorFromCipherFile(cipherkeyfile, cipherrndfile, *cipherKey, *rndm)) { (void)fprintf(stderr, _("Failed to decrypt key from transparent encryption cipher file %s.\n"), cipherrndfile); free(*cipherKey); free(*rndm); *cipherKey = NULL; *rndm = NULL; return false; } (void)fprintf(stderr, _("Successfully to decrypt %s.\n"), cipherkeyfile); return true; } /* * AK: '0-9A-Za-z' * SK: '0-9A-Za-z' */ bool getAkSkForTransEncrypt(char* ak, int akbuflen, char* sk, int skbuflen) { #define MAX_AK_SK_FILE_SIZE 2048 GS_UCHAR* key = NULL; GS_UCHAR* vector = NULL; char* gausshome = NULL; char akskfile[MAXPGPATH] = {'\0'}; FILE* fp = NULL; int ret; size_t cnt; GS_UINT32 akskenplainlen = 0; char akskfilecontent[MAX_AK_SK_FILE_SIZE] = {'\0'}; char akskplaintext[MAX_AK_SK_FILE_SIZE] = {'\0'}; char* enterlocation = NULL; int aklen, sklen; GS_UCHAR* decodestring = NULL; GS_UINT32 decodelen = 0; gausshome = getGaussHome(); ret = snprintf_s(akskfile, MAXPGPATH, MAXPGPATH - 1, "%s/bin/trans_encrypt_ak_sk.key", gausshome); securec_check_ss_c(ret, "\0", "\0"); pfree_ext(gausshome); gausshome = NULL; if (!file_exists(akskfile)) { (void)fprintf(stderr, _("AK/SK file for transparent encryption does not exist: %s\n"), akskfile); return false; } if (-1 == access(akskfile, R_OK)) { (void)fprintf(stderr, _("Permission denied to access AK/SK file for transparent encryption: %s\n"), akskfile); return false; } canonicalize_path(akskfile); fp = fopen(akskfile, "rb"); if (NULL == fp) { (void)fprintf(stderr, _("Failed to open AK/SK file for transparent encryption: %s\n"), akskfile); return false; } cnt = fread(akskfilecontent, 1, sizeof(akskfilecontent), fp); (void)fclose(fp); fp = NULL; /* akskfile is just an encrypted file of ak&sk. Its length should be less than MAX_AK_SK_FILE_SIZE. */ if (cnt >= sizeof(akskfilecontent)) { (void)fprintf(stderr, _("Corrupted AK/SK file(too long) for transparent encryption: %s\n"), akskfile); return false; } akskfilecontent[MAX_AK_SK_FILE_SIZE - 1] = '\0'; if (!getTransEncryptKeyString(&key, &vector)) { return false; } decodestring = (GS_UCHAR*)SEC_decodeBase64((char*)akskfilecontent, &decodelen); if (decodestring == NULL || !gs_decrypt_aes_128((GS_UCHAR*)decodestring, (GS_UINT32)decodelen, (GS_UCHAR*)key, CIPHER_LEN, (GS_UCHAR*)akskplaintext, &akskenplainlen)) { (void)fprintf(stderr, _("Failed to decrypt AK/SK file for transparent encryption: %s\n"), akskfile); free(key); free(vector); key = NULL; vector = NULL; if (decodestring != NULL) { OPENSSL_free(decodestring); decodestring = NULL; } return false; } free(key); free(vector); OPENSSL_free(decodestring); decodestring = NULL; key = NULL; vector = NULL; /* akskplaintext: "ak\nsk" */ enterlocation = strchr(akskplaintext, '|'); if (enterlocation == NULL) { (void)fprintf(stderr, _("Failed to split AK/SK file content for transparent encryption: %s\n"), akskfile); return false; } aklen = enterlocation - akskplaintext; sklen = akskplaintext + akskenplainlen - enterlocation - 1; if (aklen > (akbuflen - 1) || 0 == aklen) { (void)fprintf(stderr, _("Invalid AK length for transparent encryption: %s\n"), akskfile); return false; } if (sklen > (skbuflen - 1) || 0 == sklen) { (void)fprintf(stderr, _("Invalid SK length for transparent encryption: %s\n"), akskfile); return false; } ret = strncpy_s(ak, akbuflen, akskplaintext, aklen); securec_check_c(ret, "\0", "\0"); ak[aklen] = '\0'; ret = strncpy_s(sk, skbuflen, enterlocation + 1, sklen); securec_check_c(ret, "\0", "\0"); sk[sklen] = '\0'; for (int i = 0; ak[i]; i++) { if (NULL == strchr(AK_VALID_CHRS, ak[i])) { (void)fprintf(stderr, _("Illegal character(%c) in AK for transparent encryption: %s\n"), ak[i], akskfile); return false; } } for (int i = 0; sk[i]; i++) { if (NULL == strchr(SK_VALID_CHRS, sk[i])) { (void)fprintf(stderr, _("Illegal character(%c) in SK for transparent encryption: %s\n"), sk[i], akskfile); return false; } } (void)fprintf(stderr, _("Successfully to decrypt ak/sk for transparent encryption.\n")); return true; #undef MAX_AK_SK_FILE_SIZE } /* Get $GAUSSHOME, and check if any injection risk in it. * If any, throw a PANIC error. */ char* getGaussHome() { char* tmp = NULL; char* danger_token[] = {"|", ";", "&", "$", "<", ">", "`", "\\", "!", "\n", NULL}; const int MAX_GAUSSHOME_LEN = 4096; tmp = gs_getenv_r("GAUSSHOME"); if (NULL == tmp) { ereport(WARNING, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("get environment of GAUSSHOME failed.\n"))); return NULL; } if (strlen(tmp) > MAX_GAUSSHOME_LEN) { ereport(WARNING, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("environment of GAUSSHOME is too long.\n"))); return NULL; } char* tmp_tmp = (char*)palloc(strlen(tmp) + 1); errno_t rc = strcpy_s(tmp_tmp, strlen(tmp) + 1, tmp); securec_check(rc, "\0", "\0"); if ('\0' == *tmp_tmp) { ereport(WARNING, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("$GAUSSHOME is not set or it's NULL.\n"))); return tmp_tmp; } for (int i = 0; danger_token[i] != NULL; ++i) { if (strstr(tmp_tmp, danger_token[i])) { ereport(WARNING, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid character '%s' in $GAUSSHOME.\n", danger_token[i]))); } } return tmp_tmp; } /* * Get DEK from KMS. * Throw a PANIC if any error occurs. * dek: the buffer to store DEK, which length should be with CIHPER_LEN + 1. */ void getTransEncryptDEK(GS_UCHAR* dek) { FILE* fp = NULL; char *cmd = NULL; char *cmd_log = NULL; char *url = NULL; char *tmp = NULL; char *region = NULL; char* get_result = NULL; int rc = 0; /* On POSIX Linux, max command line length is 4096. */ const int MAX_CMD_LEN = 4096; char* gausshome = NULL; int i = 0; char ak[AK_LEN] = {'\0'}; char sk[SK_LEN] = {'\0'}; GS_UCHAR* decodedkey = NULL; GS_UINT32 decodedlen = 0; if (NULL == g_instance.attr.attr_common.transparent_encrypt_kms_url || '\0' == g_instance.attr.attr_common.transparent_encrypt_kms_url[0] || NULL == g_instance.attr.attr_security.transparent_encrypt_kms_region || '\0' == g_instance.attr.attr_security.transparent_encrypt_kms_region[0]) { ereport(PANIC, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("transparent_encrypt_kms_url and transparent_encrypt_kms_region should not be empty when " "transparent encryption enabled.\n"))); } if (!getAkSkForTransEncrypt(ak, sizeof(ak), sk, sizeof(sk))) { ereport(PANIC, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to get ak/sk for transparent encryption.\n"))); } cmd = (char*)palloc0(MAX_CMD_LEN); url = (char*)palloc0(MAX_CMD_LEN); region = (char*)palloc0(MAX_CMD_LEN); /* Replace $ with "\$" . */ for (i = 0, tmp = g_instance.attr.attr_common.transparent_encrypt_kms_url; i < MAX_CMD_LEN && *tmp; i++, tmp++) { if (*tmp == '$') { url[i++] = '\\'; } url[i] = *tmp; } for (i = 0, tmp = g_instance.attr.attr_security.transparent_encrypt_kms_region; i < MAX_CMD_LEN && *tmp; i++, tmp++) { if (*tmp == '$') { region[i++] = '\\'; } region[i] = *tmp; } /* If we need to expand the transparent encryption to FI, use security_mode to * identify whether it's running on DWS now. */ gausshome = getGaussHome(); rc = snprintf_s(cmd, MAX_CMD_LEN, MAX_CMD_LEN - 1, "export JAVA_HOME=$GAUSSHOME/jdk;export JRE_HOME=$JAVA_HOME/jre;export " "LD_LIBRARY_PATH=$JRE_HOME/lib/amd64/server:$LD_LIBRARY_PATH;export " "PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH;java -jar \"%s/bin/getDEK.jar\" \"%s\" \"%s\" \"%s\" \"%s\"", gausshome, url, region, ak, sk); securec_check_ss(rc, "", ""); /* This command is for logging, masked AK/SK to avoid password leak risk. */ cmd_log = (char*)palloc(MAX_CMD_LEN); rc = snprintf_s(cmd_log, MAX_CMD_LEN, MAX_CMD_LEN - 1, "export JAVA_HOME=$GAUSSHOME/jdk;export JRE_HOME=$JAVA_HOME/jre;export " "LD_LIBRARY_PATH=$JRE_HOME/lib/amd64/server:$LD_LIBRARY_PATH;export " "PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH;java -jar \"%s/bin/getDEK.jar\" \"%s\" \"%s\" \"ak\" \"sk\"", gausshome, url, region); securec_check_ss(rc, "", ""); pfree_ext(region); pfree_ext(url); pfree_ext(gausshome); fp = popen(cmd, "r"); pfree_ext(cmd); get_result = (char*)palloc0(MAX_CMD_LEN + 1); if (NULL == fp || fgets(get_result, MAX_CMD_LEN, fp) == NULL) { if (fp != NULL) { pclose(fp); } pfree_ext(get_result); ereport(PANIC, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to fork subprocess to get DEK for transparent encryption. Failure command is: [%s]\n", cmd_log))); } pclose(fp); i = (int)strlen(get_result); /* If any error occurs, getDEK.jar will give a message starts with "ERROR:". */ if (0 == i || strncmp(get_result, "ERROR:", 6) == 0) { ereport(PANIC, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to get DEK for transparent encryption. Failure command is [%s], error message is [%s]\n", cmd_log, (0 == i ? "<NULL>" : get_result)))); } if (get_result[i - 1] == '\n') { get_result[i - 1] = '\0'; } decodedkey = (GS_UCHAR*)SEC_decodeBase64(get_result, &decodedlen); /* Here we failed to decode DEK, so get_result must be error message. */ if (NULL == decodedkey || decodedlen != DEK_LEN) { ereport(PANIC, (errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION), errmsg("Failed to get decode DEK for transparent encryption. Failure content is [%s].\n", get_result))); } else { rc = memcpy_s(dek, DEK_LEN, decodedkey, decodedlen); securec_check(rc, "\0", "\0"); pfree_ext(cmd_log); pfree_ext(get_result); OPENSSL_free(decodedkey); decodedkey = NULL; } } /* Get iv from transparent encrypted string */ static void getIV(GS_UCHAR* encrypted_string, GS_UINT32 decodelen) { GS_UINT32 cipherpartlen = decodelen - RANDOM_LEN; int ret = memcpy_s(trans_encrypt_iv, TDE_IV_LEN, encrypted_string + cipherpartlen, RANDOM_LEN); securec_check(ret,"\0","\0"); ereport(LOG, (errmsg("Successfully get IV from transparent encrypted string.\n"))); } /* check if it's the correct database encryption key. */ static void testDEK(GS_UCHAR* dek) { GS_UCHAR* encrypted_sample_string = NULL; GS_UINT32 decodelen = 0; GS_UINT32 plainlen = 0; GS_UCHAR* plaintext = NULL; /* The guc transparent_encrypted_string is a string in base64 mode. */ encrypted_sample_string = (GS_UCHAR*)SEC_decodeBase64((char *)g_instance.attr.attr_security.transparent_encrypted_string, &decodelen); if (encrypted_sample_string == NULL || decodelen < RANDOM_LEN) { if (encrypted_sample_string != NULL) { OPENSSL_free(encrypted_sample_string); encrypted_sample_string = NULL; } ereport(PANIC, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Decode transparent_encrypted_string failed, please check it.\n"))); } getIV(encrypted_sample_string, decodelen); plaintext = (GS_UCHAR*)palloc0(decodelen); if (!gs_decrypt_aes_128(encrypted_sample_string, decodelen, dek, DEK_LEN, plaintext, &plainlen)) { if (encrypted_sample_string != NULL) { OPENSSL_free(encrypted_sample_string); encrypted_sample_string = NULL; } pfree_ext(plaintext); ereport(PANIC, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Decrypt transparent_encrypted_string failed, please check it!\n"))); } if (encrypted_sample_string != NULL) { OPENSSL_free(encrypted_sample_string); encrypted_sample_string = NULL; } if ((size_t)plainlen != strlen(DEK_SAMPLE_STRING) || strncmp((const char*)plaintext, DEK_SAMPLE_STRING, strlen(DEK_SAMPLE_STRING)) != 0) { pfree_ext(plaintext); ereport(PANIC, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Decrypt transparent_encrypted_string failed, please check it!\n"))); } pfree_ext(plaintext); } bool getAndCheckTranEncryptDEK() { GS_UCHAR dek[DEK_LEN] = {'\0'}; int ret = 0; /* Transparent encryption disabled. */ if (!isEncryptedCluster()) { ereport(LOG, (errmsg("Transparent encryption disabled."))); return true; } ereport(LOG, (errmsg("Transparent encryption enabled.\n"))); if (trans_encrypt_iv == NULL) { trans_encrypt_iv = (GS_UCHAR*)palloc0(TDE_IV_LEN); if (trans_encrypt_iv == NULL) { ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("Out of memory while getting transparent encryption iv.\n"))); return false; } } if (isSecurityMode) { getTransEncryptDEK(dek); testDEK((GS_UCHAR*)dek); } else { init_the_kerberos_env(); char* gausshome = getGaussHome(); if (gausshome == NULL) { ereport(WARNING, (errmsg("Transparent encryption Getting environment variable $GAUSSHOME error.\n"))); (void)fprintf(stderr, _("%s:Getting environment variable $GAUSSHOME error, please check.\n"), pgname); return false; } KeyManager table_a_key("1", "1"); // next version for different database or table. table_a_key.setfile(gausshome); pfree_ext(gausshome); if (!table_a_key.init_Key()) { ereport(WARNING, (errmsg("Transparent encryption init key failed.\n"))); return false; } std::string dek_b64 = table_a_key.getDEK(); std::string tde_sample_str = table_a_key.getEncryptedSampleStr(); if (tde_sample_str.empty()) { ereport(WARNING, (errmsg("Transparent encryption tde_sample_str error, please check.\n"))); (void)fprintf(stderr, _("%s:tde_sample_str error, please check.\n"), pgname); return false; } if (dek_b64.length() < DEK_LEN) { ereport(WARNING, (errmsg("Transparent encryption get key failed.\n"))); return false; } GS_UINT32 dek_origian_len = 0; char* dek_origian = SEC_decodeBase64((char*)dek_b64.c_str(), &dek_origian_len); if (dek_origian == NULL) { ereport(WARNING, (errmsg("decode Base64 failed.\n"))); return false; } ret = memcpy_s(dek, DEK_LEN, dek_origian, dek_origian_len); securec_check(ret, "\0", "\0"); OPENSSL_free(dek_origian); dek_origian = NULL; if (!table_a_key.check_key((unsigned char*)dek)) { ereport(WARNING, (errmsg("Transparent encryption get key failed.\n"))); } table_a_key.getIV(trans_encrypt_iv); g_tde_algo = table_a_key.get_tde_algo(); } /* init dek and iv global values */ trans_encrypt_dek = (GS_UCHAR*)palloc0(DEK_LEN); ret = memcpy_s(trans_encrypt_dek, DEK_LEN, dek, DEK_LEN); securec_check(ret, "\0", "\0"); ereport(LOG, (errmsg("Succeeded to check DEK for transparent encryption.\n"))); return true; } bool isEncryptedCluster() { if (isSecurityMode && (g_instance.attr.attr_security.transparent_encrypted_string == NULL || *g_instance.attr.attr_security.transparent_encrypted_string == '\0')) { ereport(DEBUG5, (errmsg("Transparent encryption disabled in DWS."))); return false; } else if ((!isSecurityMode) && (g_instance.attr.attr_common.transparent_encrypt_kms_url == NULL || *g_instance.attr.attr_common.transparent_encrypt_kms_url == '\0')) { ereport(DEBUG5, (errmsg("Transparent encryption disabled in GaussDB."))); return false; } if (is_feature_disabled(TRANSPARENT_ENCRYPTION) == true) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("TDE is not supported."))); return false; } return true; }
36.139946
120
0.613908
[ "vector" ]
785aed9792fdd48fd233d3f89b56e96f7c49170e
4,313
cxx
C++
Modules/Core/Mesh/test/itkInteriorExteriorMeshFilterTest.cxx
eile/ITK
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
[ "Apache-2.0" ]
4
2015-05-22T03:47:43.000Z
2016-06-16T20:57:21.000Z
Modules/Core/Mesh/test/itkInteriorExteriorMeshFilterTest.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
1
2019-03-18T14:19:49.000Z
2020-01-11T13:54:33.000Z
Modules/Core/Mesh/test/itkInteriorExteriorMeshFilterTest.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
9
2016-06-23T16:03:12.000Z
2022-03-31T09:25:08.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkInteriorExteriorMeshFilter.h" #include "itkMesh.h" #include "itkSphereSpatialFunction.h" int itkInteriorExteriorMeshFilterTest(int, char* [] ) { // Declare the mesh pixel type. // Those are the values associated // with each mesh point. (not used on this filter test) typedef int PixelType; // Declare the types of the Mesh // By default it is a 3D mesh using itk::Point<float,3> // on the vertices, and an itk::VectorContainter // as containter for points typedef itk::Mesh<PixelType> MeshType; // Declare the type for PointsContainer typedef MeshType::PointsContainer PointsContainerType; // Declare the type for PointsContainerPointer typedef MeshType::PointsContainerPointer PointsContainerPointer; // Declare the type for Points typedef MeshType::PointType PointType; // Create an input Mesh MeshType::Pointer inputMesh = MeshType::New(); // Insert data on the Mesh PointsContainerPointer points = inputMesh->GetPoints(); // Fill a cube with points , just to get some data int n = 3; // let's start with a few of them PointsContainerType::ElementIdentifier count = 0; // count them for(int x= -n; x <= n; x++) { for(int y= -n; y <= n; y++) { for(int z= -n; z <= n; z++) { PointType p; p[0] = x; p[1] = y; p[2] = z; points->InsertElement( count, p ); count++; } } } // Declare the function type typedef itk::SphereSpatialFunction< MeshType::PointDimension, MeshType::PointType > SpatialFunctionType; // Declare the type for the filter typedef itk::InteriorExteriorMeshFilter< MeshType, MeshType, SpatialFunctionType > FilterType; // Create a Filter FilterType::Pointer filter = FilterType::New(); // Create the Spatial Function SpatialFunctionType::Pointer spatialFunction = SpatialFunctionType::New(); SpatialFunctionType::InputType center; center[0] = 0; center[1] = 0; center[2] = 2; // Here we are assuming 3D !!! const double radius = 1.1f; spatialFunction->SetCenter( center ); spatialFunction->SetRadius( radius ); // Connect the inputs filter->SetInput( inputMesh ); filter->SetSpatialFunction( spatialFunction ); // Execute the filter filter->Update(); // Get the Smart Pointer to the Filter Output MeshType::Pointer outputMesh = filter->GetOutput(); // Get the the point container MeshType::PointsContainerPointer transformedPoints = outputMesh->GetPoints(); PointsContainerType::ConstIterator it = transformedPoints->Begin(); while( it != transformedPoints->End() ) { PointType p = it.Value(); const double distance = p.EuclideanDistanceTo( center ); if( distance > radius ) { std::cerr << "Point " << p << std::endl; std::cerr << " is at distance " << distance << std::endl; std::cerr << " from the center " << center << std::endl; std::cerr << " so it is outside the sphere of radius "; std::cerr << radius << std::endl; return EXIT_FAILURE; } ++it; } // All objects shall be automatically destroyed at this point std::cout << "Test passed ! " << std::endl; return EXIT_SUCCESS; }
29.951389
77
0.600046
[ "mesh", "3d" ]
785ba6a8b8ce6f0fd9c4aa26ed227bab50303d56
2,112
cpp
C++
ver1/answers/lp-10-12.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-10-12.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-10-12.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
// 18/01/23 = Mon // 18/02/21 = Wed: rewrite // Exercise 10.12: Write a function named compareIsbn that compares the isbn() members of two Sales_data objects. Use that function to sort a vector that holds Sales_data objects. // Class definition copied from lp-08-06.cpp // To run, enter "a <data\records" in command prompt. #include <algorithm> #include <iostream> #include <stdexcept> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::invalid_argument; using std::istream; using std::ostream; using std::string; using std::vector; class Sales_data { string book_number; unsigned quantity = 0u; double revenue = 0.0; public: string isbn() const; Sales_data & combine(const Sales_data &); static istream & read(istream &, Sales_data &); static ostream & print(ostream &, const Sales_data &); private: double avg_price() const; }; inline string Sales_data::isbn() const { return book_number; } Sales_data & Sales_data::combine(const Sales_data & data) { if (book_number != data.book_number) throw invalid_argument("ISBNs differ!"); quantity += data.quantity; revenue += data.revenue; return *this; } istream & Sales_data::read(istream & is, Sales_data & data) { double price; is >> data.book_number >> data.quantity >> price; data.revenue = data.quantity * price; return is; } ostream & Sales_data::print(ostream & os, Sales_data const& data) { return os << data.isbn() << " " << data.quantity << " " << data.revenue << " " << data.avg_price(); } inline double Sales_data::avg_price() const { return revenue / quantity; } bool compareIsbn(const Sales_data & data1, const Sales_data & data2) { return data1.isbn() < data2.isbn(); } void print(const vector<Sales_data> & v) { cout << string(30, '-') << endl; for (const auto & e : v) Sales_data::print(cout, e) << endl; } void process(vector<Sales_data> & v) { for (Sales_data data; Sales_data::read(cin, data); v.push_back(data)) ; print(v); sort(v.begin(), v.end(), compareIsbn); print(v); } int main() { vector<Sales_data> records; process(records); return 0; }
21.55102
179
0.694602
[ "vector" ]
785df1d981875c6392dfb814cde42ce47de7b501
308
cpp
C++
SoA/PdaRenderStage.cpp
Revan1985/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
[ "MIT" ]
267
2018-06-03T23:05:05.000Z
2022-03-17T00:28:40.000Z
SoA/PdaRenderStage.cpp
davidkestering/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
[ "MIT" ]
16
2018-06-05T18:59:11.000Z
2021-09-28T05:05:16.000Z
SoA/PdaRenderStage.cpp
davidkestering/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
[ "MIT" ]
113
2018-06-03T23:56:13.000Z
2022-03-21T00:07:16.000Z
#include "stdafx.h" #include "PdaRenderStage.h" #include "PDA.h" PdaRenderStage::PdaRenderStage() { // Empty } void PdaRenderStage::hook(const PDA* pda) { _pda = pda; } void PdaRenderStage::render(const Camera* camera VORB_MAYBE_UNUSED) { if (_pda->isOpen()) { _pda->draw(); } }
15.4
69
0.642857
[ "render" ]
785f88ff911af5431b3f077b4a18184a5a2c36cf
1,089
cpp
C++
leetcode/304.range-sum-query-2-d-immutable.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/304.range-sum-query-2-d-immutable.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
null
null
null
leetcode/304.range-sum-query-2-d-immutable.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
/* * @lc app=leetcode id=304 lang=cpp * * [304] Range Sum Query 2D - Immutable */ // @lc code=start class NumMatrix { public: vector<vector<int>> v; int n,m; NumMatrix(vector<vector<int>>& matrix) { v = matrix; n = matrix.size(); if(n>=1) m = matrix[0].size(); for(int i=1;i<m;i++) { v[0][i] += v[0][i-1]; } for(int i=1;i<n;i++) { v[i][0] += v[i-1][0]; } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { v[i][j]+=v[i-1][j] + v[i][j-1] - v[i-1][j-1]; } } } int sumRegion(int row1, int col1, int row2, int col2) { if(n==0) return 0; return v[row2][col2] - ((row1-1>=0) ? v[row1-1][col2] : 0) - ((col1-1>=0) ? v[row2][col1-1] : 0) + ((row1>0 and col1>0) ?v[row1-1][col1-1] : 0); } }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */ // @lc code=end
25.325581
152
0.455464
[ "object", "vector" ]
786839e1075e6a17c5acca961d8e04afa8bf22fb
626
cpp
C++
CodeForces/Codeforces Global Round 19/A_Sorting Parts .cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
CodeForces/Codeforces Global Round 19/A_Sorting Parts .cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
CodeForces/Codeforces Global Round 19/A_Sorting Parts .cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; int t; int main(int argc, char const *argv[]) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> t; while (t--) { int n; cin >> n; vector<int> a; vector<int> b; for (int i = 1; i <= n; ++i) { int p; cin >> p; a.push_back(p); b.push_back(p); } sort(b.begin(), b.end()); if (a == b) cout << "NO" << endl; else cout << "YES" << endl; } return 0; }
16.473684
38
0.413738
[ "vector" ]
786e045f1b97920c3413bc4ebc0a2aff26519754
36,736
cpp
C++
src/appcontext.cpp
sanderfoobar/wowlet
ee3713b16b4883a95cb94a07f2f44ab3fc384083
[ "BSD-3-Clause" ]
1
2021-09-24T18:20:16.000Z
2021-09-24T18:20:16.000Z
src/appcontext.cpp
sanderfoobar/wowlet
ee3713b16b4883a95cb94a07f2f44ab3fc384083
[ "BSD-3-Clause" ]
null
null
null
src/appcontext.cpp
sanderfoobar/wowlet
ee3713b16b4883a95cb94a07f2f44ab3fc384083
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2020-2021, The Monero Project. #include <QDir> #include <QMessageBox> #include "appcontext.h" #include "globals.h" #include "config-wowlet.h" // libwalletqt #include "libwalletqt/TransactionHistory.h" #include "libwalletqt/Subaddress.h" #include "libwalletqt/Coins.h" #include "model/TransactionHistoryModel.h" #include "model/SubaddressModel.h" Prices *AppContext::prices = nullptr; WalletKeysFilesModel *AppContext::wallets = nullptr; TxFiatHistory *AppContext::txFiatHistory = nullptr; double AppContext::balance = 0; QMap<QString, QString> AppContext::txDescriptionCache; QMap<QString, QString> AppContext::txCache; bool AppContext::isQML = false; AppContext::AppContext(QCommandLineParser *cmdargs) { this->m_walletKeysFilesModel = new WalletKeysFilesModel(this, this); this->network = new QNetworkAccessManager(); this->networkClearnet = new QNetworkAccessManager(); this->cmdargs = cmdargs; AppContext::isQML = false; // OS & env #if defined(Q_OS_MAC) this->isMac = true; this->isTorSocks = qgetenv("DYLD_INSERT_LIBRARIES").indexOf("libtorsocks") >= 0; #elif __ANDROID__ this->isAndroid = true; #elif defined(Q_OS_LINUX) this->isLinux = true; this->isTorSocks = qgetenv("LD_PRELOAD").indexOf("libtorsocks") >= 0; this->isTails = TailsOS::detect(); this->isWhonix = WhonixOS::detect(); #elif defined(Q_OS_WIN) this->isWindows = true; this->isTorSocks = false; #endif this->androidDebug = cmdargs->isSet("android-debug"); // Paths this->pathGenericData = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); this->configRoot = QDir::homePath(); this->accountName = Utils::getUnixAccountName(); this->homeDir = QDir::homePath(); this->configDirectory = QString("%1/.config/wowlet/").arg(this->configRoot); this->configDirectoryVR = QString("%1%2").arg(this->configDirectory, "vr"); if (isTails) this->setupPathsTails(); QString walletDir = config()->get(Config::walletDirectory).toString(); if(walletDir.isEmpty()) { if (isAndroid && !androidDebug) setupPathsAndroid(); else if (isWindows) setupPathsWindows(); else if (isLinux || isMac) setupPathsUnix(); } else { this->defaultWalletDir = walletDir; this->defaultWalletDirRoot = walletDir; } #ifdef __ANDROID__ // can haz disk I/O? QVector<QString> perms = { "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE" }; Utils::androidAskPermissions(perms); #endif // Create wallet dirs qDebug() << "creating " << defaultWalletDir; if (!QDir().mkpath(defaultWalletDir)) qCritical() << "Unable to create dir: " << defaultWalletDir; // Create some directories createConfigDirectory(this->configDirectory); this->networkType = NetworkType::MAINNET; qDebug() << "configRoot: " << this->configRoot; qDebug() << "homeDir: " << this->homeDir; qDebug() << "customWalletDir: " << walletDir; qDebug() << "defaultWalletDir: " << this->defaultWalletDir; qDebug() << "defaultWalletDirRoot: " << this->defaultWalletDirRoot; qDebug() << "configDirectory: " << this->configDirectory; // auto nodeSourceUInt = config()->get(Config::nodeSource).toUInt(); // AppContext::nodeSource = static_cast<NodeSource>(nodeSourceUInt); this->nodes = new Nodes(this, this->networkClearnet); connect(this, &AppContext::nodeSourceChanged, this->nodes, &Nodes::onNodeSourceChanged); connect(this, &AppContext::setCustomNodes, this->nodes, &Nodes::setCustomNodes); // Tor & socks proxy this->ws = new WSClient(this, wsUrl); connect(this->ws, &WSClient::WSMessage, this, &AppContext::onWSMessage); connect(this->ws, &WSClient::connectionEstablished, this, &AppContext::wsConnected); connect(this->ws, &WSClient::closed, this, &AppContext::wsDisconnected); // Store the wallet every 2 minutes m_storeTimer.start(2 * 60 * 1000); connect(&m_storeTimer, &QTimer::timeout, [this](){ this->storeWallet(); }); // If system clock skewed for >= 300 seconds, assume a wake-up from hibernate and reload the websocket connection if(!this->isAndroid) m_hibernateTimer.start(3 * 1000); m_hibernatePreviousTime = std::chrono::steady_clock::now(); connect(&m_hibernateTimer, &QTimer::timeout, [this]() { const auto now = std::chrono::steady_clock::now(); const auto elapsed = now - m_hibernatePreviousTime; if(elapsed >= m_hibernateDetectInterval) { qCritical() << "Clock skew detected, resetting websocket connection"; this->ws->webSocket.abort(); this->ws->start(); } m_hibernatePreviousTime = now; }); // restore height lookup this->initRestoreHeights(); // price history lookup auto genesis_timestamp = this->restoreHeights[NetworkType::Type::MAINNET]->data.firstKey(); AppContext::txFiatHistory = new TxFiatHistory(genesis_timestamp, this->configDirectory); connect(this->ws, &WSClient::connectionEstablished, AppContext::txFiatHistory, &TxFiatHistory::onUpdateDatabase); connect(AppContext::txFiatHistory, &TxFiatHistory::requestYear, [=](int year){ QByteArray data = QString(R"({"cmd": "txFiatHistory", "data": {"year": %1}})").arg(year).toUtf8(); this->ws->sendMsg(data); }); connect(AppContext::txFiatHistory, &TxFiatHistory::requestYearMonth, [=](int year, int month) { QByteArray data = QString(R"({"cmd": "txFiatHistory", "data": {"year": %1, "month": %2}})").arg(year).arg(month).toUtf8(); this->ws->sendMsg(data); }); // fiat/crypto lookup AppContext::prices = new Prices(); // XMRig #ifdef HAS_XMRIG this->XMRig = new XmRig(this->configDirectory, this); this->XMRig->prepare(); #endif this->walletManager = WalletManager::instance(); QString logPath = QString("%1/daemon.log").arg(configDirectory); Monero::Utils::onStartup(); Monero::Wallet::init("", "wowlet", logPath.toStdString(), true); bool logLevelFromEnv; int logLevel = qEnvironmentVariableIntValue("MONERO_LOG_LEVEL", &logLevelFromEnv); if(this->cmdargs->isSet("quiet")) this->walletManager->setLogLevel(-1); else if (logLevelFromEnv && logLevel >= 0 && logLevel <= Monero::WalletManagerFactory::LogLevel_Max) Monero::WalletManagerFactory::setLogLevel(logLevel); connect(this, &AppContext::createTransactionError, this, &AppContext::onCreateTransactionError); // libwallet connects connect(this->walletManager, &WalletManager::walletOpened, this, &AppContext::onWalletOpened); } void AppContext::initTor() { this->tor = new Tor(this, this); this->tor->start(); if (!isWhonix && wsUrl.contains(".onion")) { this->networkProxy = new QNetworkProxy(QNetworkProxy::Socks5Proxy, Tor::torHost, Tor::torPort); this->network->setProxy(*networkProxy); this->ws->webSocket.setProxy(*networkProxy); } } void AppContext::initWS() { this->ws->start(); } void AppContext::onCancelTransaction(PendingTransaction *tx, const QVector<QString> &address) { // tx cancelled by user double amount = tx->amount() / globals::cdiv; emit createTransactionCancelled(address, amount); this->currentWallet->disposeTransaction(tx); } void AppContext::onSweepOutput(const QString &keyImage, QString address, bool churn, int outputs) const { if(this->currentWallet == nullptr){ qCritical() << "Cannot create transaction; no wallet loaded"; return; } if (churn) { address = this->currentWallet->address(0, 0); // primary address } qCritical() << "Creating transaction"; this->currentWallet->createTransactionSingleAsync(keyImage, address, outputs, this->tx_priority); } void AppContext::onCreateTransaction(QString address, quint64 amount, QString description, bool all) { // tx creation this->tmpTxDescription = description; if(this->currentWallet == nullptr) { emit createTransactionError("Cannot create transaction; no wallet loaded"); return; } if (!all && amount == 0) { emit createTransactionError("Cannot send nothing"); return; } auto balance = this->currentWallet->balance(); auto unlocked_balance = this->currentWallet->unlockedBalance(); if(!all && amount > unlocked_balance) { emit createTransactionError("Not enough money to spend"); return; } else if(unlocked_balance == 0) { emit createTransactionError("No money to spend"); return; } qDebug() << "creating tx"; if (all) this->currentWallet->createTransactionAllAsync(address, "", this->tx_mixin, this->tx_priority); else this->currentWallet->createTransactionAsync(address, "", amount, this->tx_mixin, this->tx_priority); emit initiateTransaction(); } void AppContext::onCreateTransactionMultiDest(const QVector<QString> &addresses, const QVector<quint64> &amounts, const QString &description) { this->tmpTxDescription = description; if (this->currentWallet == nullptr) { emit createTransactionError("Cannot create transaction; no wallet loaded"); return; } quint64 total_amount = 0; for (auto &amount : amounts) { total_amount += amount; } auto unlocked_balance = this->currentWallet->unlockedBalance(); if (total_amount > unlocked_balance) { emit createTransactionError("Not enough money to spend"); } qDebug() << "Creating tx"; this->currentWallet->createTransactionMultiDestAsync(addresses, amounts, this->tx_priority); emit initiateTransaction(); } void AppContext::onCreateTransactionError(const QString &msg) { this->tmpTxDescription = ""; emit endTransaction(); } void AppContext::closeWallet(bool emitClosedSignal, bool storeWallet) { if (this->currentWallet == nullptr) return; emit walletAboutToClose(); if (storeWallet) { this->storeWallet(); } this->currentWallet->disconnect(); this->walletManager->closeWallet(); this->currentWallet = nullptr; if (emitClosedSignal) emit walletClosed(); } void AppContext::onOpenWallet(const QString &path, const QString &password){ if(this->currentWallet != nullptr){ emit walletOpenedError("There is an active wallet opened."); return; } if(!Utils::fileExists(path)) { emit walletOpenedError(QString("Wallet not found: %1").arg(path)); return; } if (password.isEmpty()) { this->walletPassword = ""; } config()->set(Config::firstRun, false); this->walletPath = path; this->walletManager->openWalletAsync(path, password, this->networkType, 1); } void AppContext::onPreferredFiatCurrencyChanged(const QString &symbol) { if(this->currentWallet) { auto *model = this->currentWallet->transactionHistoryModel(); if(model != nullptr) { model->preferredFiatSymbol = symbol; } } } void AppContext::onWalletOpened(Wallet *wallet) { auto state = wallet->status(); if (state != Wallet::Status_Ok) { auto errMsg = wallet->errorString(); if(errMsg == QString("basic_string::_M_replace_aux") || errMsg == QString("std::bad_alloc")) { qCritical() << errMsg; this->walletManager->clearWalletCache(this->walletPath); errMsg = QString("%1\n\nAttempted to clean wallet cache. Please restart WOWlet.").arg(errMsg); this->closeWallet(false); emit walletOpenedError(errMsg); } else if(errMsg.contains("wallet cannot be opened as")) { this->closeWallet(false); emit walletOpenedError(errMsg); } else if(errMsg.contains("is opened by another wallet program")) { this->closeWallet(false); emit walletOpenedError(errMsg); } else { this->closeWallet(false); emit walletOpenPasswordNeeded(!this->walletPassword.isEmpty(), wallet->path()); } return; } this->refreshed = false; this->currentWallet = wallet; this->walletPath = this->currentWallet->path() + ".keys"; QFileInfo fileInfo(this->currentWallet->path()); this->walletName = fileInfo.fileName(); this->walletViewOnly = this->currentWallet->viewOnly(); config()->set(Config::walletPath, this->walletPath); connect(this->currentWallet, &Wallet::moneySpent, this, &AppContext::onMoneySpent); connect(this->currentWallet, &Wallet::moneyReceived, this, &AppContext::onMoneyReceived); connect(this->currentWallet, &Wallet::unconfirmedMoneyReceived, this, &AppContext::onUnconfirmedMoneyReceived); connect(this->currentWallet, &Wallet::newBlock, this, &AppContext::onWalletNewBlock); connect(this->currentWallet, &Wallet::updated, this, &AppContext::onWalletUpdate); connect(this->currentWallet, &Wallet::refreshed, this, &AppContext::onWalletRefreshed); connect(this->currentWallet, &Wallet::transactionCommitted, this, &AppContext::onTransactionCommitted); connect(this->currentWallet, &Wallet::heightRefreshed, this, &AppContext::onHeightRefreshed); connect(this->currentWallet, &Wallet::transactionCreated, this, &AppContext::onTransactionCreated); emit walletOpened(wallet); connect(this->currentWallet, &Wallet::connectionStatusChanged, [this]{ this->nodes->autoConnect(); }); this->nodes->connectToNode(); this->updateBalance(); #ifdef DONATE_BEG this->donateBeg(); #endif // force trigger preferredFiat signal for history model this->onPreferredFiatCurrencyChanged(config()->get(Config::preferredFiatCurrency).toString()); this->setWindowTitle(); } void AppContext::setWindowTitle(bool mining) { QFileInfo fileInfo(this->walletPath); auto title = QString("WOWlet - [%1]").arg(fileInfo.fileName()); if(this->walletViewOnly) title += " [view-only]"; if(mining) title += " [mining]"; emit setTitle(title); } void AppContext::onWSMessage(const QJsonObject &msg) { QString cmd = msg.value("cmd").toString(); if(cmd == "blockheights") { auto heights = msg.value("data").toObject(); auto mainnet = heights.value("mainnet").toInt(); auto stagenet = heights.value("stagenet").toInt(); auto changed = false; if(!this->heights.contains("mainnet")) { this->heights["mainnet"] = mainnet; changed = true; } else { if (mainnet > this->heights["mainnet"]) { this->heights["mainnet"] = mainnet; changed = true; } } if(!this->heights.contains("stagenet")) { this->heights["stagenet"] = stagenet; changed = true; } else { if (stagenet > this->heights["stagenet"]) { this->heights["stagenet"] = stagenet; changed = true; } } if(changed) emit blockHeightWSUpdated(this->heights); } else if(cmd == "rpc_nodes") { this->onWSNodes(msg.value("data").toArray()); } #if defined(HAS_XMRIG) else if(cmd == "xmrig") { this->XMRigDownloads(msg.value("data").toObject()); } #endif else if(cmd == "crypto_rates") { QJsonArray crypto_rates = msg.value("data").toArray(); AppContext::prices->cryptoPricesReceived(crypto_rates); } else if(cmd == "fiat_rates") { QJsonObject fiat_rates = msg.value("data").toObject(); AppContext::prices->fiatPricesReceived(fiat_rates); } else if(cmd == "reddit") { QJsonArray reddit_data = msg.value("data").toArray(); this->onWSReddit(reddit_data); } else if(cmd == "forum") { QJsonArray forum_data = msg.value("data").toArray(); this->onWSForum(forum_data); } else if(cmd == "funding_proposals") { auto ccs_data = msg.value("data").toArray(); this->onWSCCS(ccs_data); } else if(cmd == "suchwow") { QJsonArray such_data = msg.value("data").toArray(); emit suchWowUpdated(such_data); } else if(cmd == "txFiatHistory") { auto txFiatHistory_data = msg.value("data").toObject(); AppContext::txFiatHistory->onWSData(txFiatHistory_data); } else if(cmd == "wowlet_releases") { versionPending = msg.value("data").toObject(); auto version_str = versionPending.value("version").toString(); if(Utils::versionOutdated(WOWLET_VERSION_SEMVER, version_str)) emit versionOutdated(version_str, versionPending); } else if(cmd == "kill") { // used *only* in dire emergencies auto killme = msg.value("data").toBool(); if(killme) QCoreApplication::quit(); } #if defined(HAS_OPENVR) else if(cmd == "requestPIN") { auto pin = msg.value("data").toString(); emit pinReceived(pin); } else if(cmd == "lookupPIN") { auto lookup_data = msg.value("data").toObject(); auto address = lookup_data.value("address").toString(); auto pin = lookup_data.value("PIN").toString(); if(address.isEmpty()) emit pinLookupErrorReceived(); else emit pinLookupReceived(address, pin); } #endif } void AppContext::onWSNodes(const QJsonArray &nodes) { QList<QSharedPointer<WowletNode>> l; for (auto &&entry: nodes) { auto obj = entry.toObject(); auto nettype = obj.value("nettype"); auto type = obj.value("type"); // filter remote node network types if(nettype == "mainnet" && this->networkType != NetworkType::MAINNET) continue; if(nettype == "stagenet" && this->networkType != NetworkType::STAGENET) continue; if(nettype == "testnet" && this->networkType != NetworkType::TESTNET) continue; if(type == "clearnet" && (this->isTails || this->isWhonix || this->isTorSocks)) continue; if(type == "tor" && (!(this->isTails || this->isWhonix || this->isTorSocks))) continue; auto node = new WowletNode( obj.value("address").toString(), obj.value("height").toInt(), obj.value("target_height").toInt(), obj.value("online").toBool()); QSharedPointer<WowletNode> r = QSharedPointer<WowletNode>(node); l.append(r); } this->nodes->onWSNodesReceived(l); } void AppContext::onWSForum(const QJsonArray& forum_data) { QList<QSharedPointer<ForumPost>> l; for (auto &&entry: forum_data) { auto obj = entry.toObject(); auto forumPost = new ForumPost( obj.value("title").toString(), obj.value("author").toString(), obj.value("permalink").toString(), obj.value("comments").toInt()); QSharedPointer<ForumPost> r = QSharedPointer<ForumPost>(forumPost); l.append(r); } emit forumUpdated(l); } void AppContext::onWSReddit(const QJsonArray& reddit_data) { QList<QSharedPointer<RedditPost>> l; for (auto &&entry: reddit_data) { auto obj = entry.toObject(); auto redditPost = new RedditPost( obj.value("title").toString(), obj.value("author").toString(), obj.value("permalink").toString(), obj.value("comments").toInt()); QSharedPointer<RedditPost> r = QSharedPointer<RedditPost>(redditPost); l.append(r); } emit redditUpdated(l); } void AppContext::onWSCCS(const QJsonArray &ccs_data) { QList<QSharedPointer<CCSEntry>> l; QStringList fonts = {"state", "address", "author", "date", "title", "target_amount", "raised_amount", "percentage_funded", "contributions"}; for (auto &&entry: ccs_data) { auto obj = entry.toObject(); auto c = QSharedPointer<CCSEntry>(new CCSEntry()); if (obj.value("state").toString() != "FUNDING-REQUIRED") continue; c->state = obj.value("state").toString(); c->address = obj.value("address").toString(); c->author = obj.value("author").toString(); c->date = obj.value("date").toString(); c->title = obj.value("title").toString(); c->url = obj.value("url").toString(); c->target_amount = obj.value("target_amount").toDouble(); c->raised_amount = obj.value("raised_amount").toDouble(); c->percentage_funded = obj.value("percentage_funded").toDouble(); c->contributions = obj.value("contributions").toInt(); l.append(c); } emit ccsUpdated(l); } void AppContext::createConfigDirectory(const QString &dir) { auto config_dir_tor = QString("%1%2").arg(dir).arg("tor"); auto config_dir_tordata = QString("%1%2").arg(dir).arg("tor/data"); QStringList createDirs({dir, config_dir_tor, config_dir_tordata}); for(const auto &d: createDirs) { if(!Utils::dirExists(d)) { qDebug() << QString("Creating directory: %1").arg(d); if (!QDir().mkpath(d)) throw std::runtime_error("Could not create directory " + d.toStdString()); } } #ifdef HAS_OPENVR auto config_dir_vr = QString("%1%2").arg(dir, "vr"); if(!Utils::dirExists(config_dir_vr)) { qDebug() << QString("Creating directory: %1").arg(config_dir_vr); if (!QDir().mkpath(config_dir_vr)) throw std::runtime_error("Could not create directory " + config_dir_vr.toStdString()); } #endif } void AppContext::createWalletWithoutSpecifyingSeed(const QString &name, const QString &password) { WowletSeed seed = WowletSeed(this->restoreHeights[this->networkType], this->coinName, this->seedLanguage); auto path = QDir(this->defaultWalletDir).filePath(name); this->createWallet(seed, path, password); } void AppContext::createWallet(WowletSeed seed, const QString &path, const QString &password) { if(Utils::fileExists(path)) { auto err = QString("Failed to write wallet to path: \"%1\"; file already exists.").arg(path); qCritical() << err; emit walletCreatedError(err); return; } if(seed.mnemonic.isEmpty()) { emit walletCreatedError("Mnemonic seed error. Failed to write wallet."); return; } Wallet *wallet = nullptr; if (seed.seedType == SeedType::TEVADOR) { wallet = this->walletManager->createDeterministicWalletFromSpendKey(path, password, seed.language, this->networkType, seed.spendKey, seed.restoreHeight, this->kdfRounds); wallet->setCacheAttribute("wowlet.seed", seed.mnemonic.join(" ")); } if (seed.seedType == SeedType::MONERO) { wallet = this->walletManager->recoveryWallet(path, password, seed.mnemonic.join(" "), "", this->networkType, seed.restoreHeight, this->kdfRounds); } this->currentWallet = wallet; if(this->currentWallet == nullptr) { emit walletCreatedError("Failed to write wallet"); return; } this->createWalletFinish(password); } void AppContext::createWalletViewOnly(const QString &path, const QString &password, const QString &address, const QString &viewkey, const QString &spendkey, quint64 restoreHeight) { if(Utils::fileExists(path)) { auto err = QString("Failed to write wallet to path: \"%1\"; file already exists.").arg(path); qCritical() << err; emit walletCreatedError(err); return; } if(!this->walletManager->addressValid(address, this->networkType)) { auto err = QString("Failed to create wallet. Invalid address provided.").arg(path); qCritical() << err; emit walletCreatedError(err); return; } if(!this->walletManager->keyValid(viewkey, address, true, this->networkType)) { auto err = QString("Failed to create wallet. Invalid viewkey provided.").arg(path); qCritical() << err; emit walletCreatedError(err); return; } if(!spendkey.isEmpty() && !this->walletManager->keyValid(spendkey, address, false, this->networkType)) { auto err = QString("Failed to create wallet. Invalid spendkey provided.").arg(path); qCritical() << err; emit walletCreatedError(err); return; } this->currentWallet = this->walletManager->createWalletFromKeys(path, this->seedLanguage, this->networkType, address, viewkey, spendkey, restoreHeight); this->createWalletFinish(password); } void AppContext::createWalletFinish(const QString &password) { this->currentWallet->setPassword(password); this->currentWallet->store(); this->walletPassword = password; emit walletCreated(this->currentWallet); // emit signal on behalf of walletManager, open wallet this->walletManager->walletOpened(this->currentWallet); } void AppContext::initRestoreHeights() { restoreHeights[NetworkType::TESTNET] = RestoreHeightLookup::fromFile(":/assets/restore_heights_wownero_mainnet.txt", NetworkType::TESTNET); restoreHeights[NetworkType::STAGENET] = RestoreHeightLookup::fromFile(":/assets/restore_heights_wownero_mainnet.txt", NetworkType::STAGENET); restoreHeights[NetworkType::MAINNET] = RestoreHeightLookup::fromFile(":/assets/restore_heights_wownero_mainnet.txt", NetworkType::MAINNET); } void AppContext::onSetRestoreHeight(quint64 height){ auto seed = this->currentWallet->getCacheAttribute("wowlet.seed"); if(!seed.isEmpty()) { const auto msg = "This wallet has a 14 word mnemonic seed which has the restore height embedded."; emit setRestoreHeightError(msg); return; } this->currentWallet->setWalletCreationHeight(height); this->currentWallet->setPassword(this->currentWallet->getPassword()); // trigger .keys write // nuke wallet cache const auto fn = this->currentWallet->path(); this->walletManager->clearWalletCache(fn); emit customRestoreHeightSet(height); } void AppContext::onOpenAliasResolve(const QString &openAlias) { // @TODO: calling this freezes for about 1-2 seconds :/ const auto result = this->walletManager->resolveOpenAlias(openAlias); const auto spl = result.split("|"); auto msg = QString(""); if(spl.count() != 2) { msg = "Internal error"; emit openAliasResolveError(msg); return; } const auto &status = spl.at(0); const auto &address = spl.at(1); const auto valid = this->walletManager->addressValid(address, this->networkType); if(status == "false"){ if(valid){ msg = "Address found, but the DNSSEC signatures could not be verified, so this address may be spoofed"; emit openAliasResolveError(msg); return; } else { msg = "No valid address found at this OpenAlias address, but the DNSSEC signatures could not be verified, so this may be spoofed"; emit openAliasResolveError(msg); return; } } else if(status != "true") { msg = "Internal error"; emit openAliasResolveError(msg); return; } if(valid){ emit openAliasResolved(address, openAlias); return; } msg = QString("Address validation error."); if(!address.isEmpty()) msg += QString(" Perhaps it is of the wrong network type." "\n\nOpenAlias: %1\nAddress: %2").arg(openAlias).arg(address); emit openAliasResolveError(msg); } void AppContext::donateBeg() { if(this->currentWallet == nullptr) return; if(this->networkType != NetworkType::Type::MAINNET) return; if(this->currentWallet->viewOnly()) return; auto donationCounter = config()->get(Config::donateBeg).toInt(); if(donationCounter == -1) return; // previously donated donationCounter += 1; if (donationCounter % m_donationBoundary == 0) emit donationNag(); config()->set(Config::donateBeg, donationCounter); } AppContext::~AppContext() {} // ############################################## LIBWALLET QT ######################################################### void AppContext::onMoneySpent(const QString &txId, quint64 amount) { auto amount_num = amount / globals::cdiv; qDebug() << Q_FUNC_INFO << txId << " " << QString::number(amount_num); } void AppContext::onMoneyReceived(const QString &txId, quint64 amount) { // Incoming tx included in a block. auto amount_num = amount / globals::cdiv; qDebug() << Q_FUNC_INFO << txId << " " << QString::number(amount_num); } void AppContext::onUnconfirmedMoneyReceived(const QString &txId, quint64 amount) { // Incoming transaction in pool auto amount_num = amount / globals::cdiv; qDebug() << Q_FUNC_INFO << txId << " " << QString::number(amount_num); if(this->currentWallet->synchronized()) { auto notify = QString("%1 WOW (pending)").arg(amount_num); Utils::desktopNotify("Payment received", notify, 5000); } } void AppContext::onWalletUpdate() { if (this->currentWallet->synchronized()) { this->refreshModels(); this->storeWallet(); } this->updateBalance(); } void AppContext::onWalletRefreshed(bool success) { if (!this->refreshed) { refreshModels(); this->refreshed = true; emit walletRefreshed(); // store wallet immediately upon finishing synchronization this->currentWallet->store(); } qDebug() << "Wallet refresh status: " << success; this->currentWallet->refreshHeightAsync(); } void AppContext::onWalletNewBlock(quint64 blockheight, quint64 targetHeight) { this->syncStatusUpdated(blockheight, targetHeight); if (this->currentWallet->synchronized()) { this->currentWallet->coins()->refreshUnlocked(); this->currentWallet->history()->refresh(this->currentWallet->currentSubaddressAccount()); // Todo: only refresh tx confirmations } } void AppContext::onHeightRefreshed(quint64 walletHeight, quint64 daemonHeight, quint64 targetHeight) { qDebug() << Q_FUNC_INFO << walletHeight << daemonHeight << targetHeight; if (this->currentWallet->connectionStatus() == Wallet::ConnectionStatus_Disconnected) return; if (daemonHeight < targetHeight) { emit blockchainSync(daemonHeight, targetHeight); } else { this->syncStatusUpdated(walletHeight, daemonHeight); } } void AppContext::onTransactionCreated(PendingTransaction *tx, const QVector<QString> &address) { for (auto &addr : address) { if (addr == this->donationAddress) { this->donationSending = true; } } // Let UI know that the transaction was constructed emit endTransaction(); // Some validation auto tx_status = tx->status(); auto err = QString("Can't create transaction: "); if(tx_status != PendingTransaction::Status_Ok){ auto tx_err = tx->errorString(); qCritical() << tx_err; if (this->currentWallet->connectionStatus() == Wallet::ConnectionStatus_WrongVersion) err = QString("%1 Wrong daemon version: %2").arg(err).arg(tx_err); else err = QString("%1 %2").arg(err).arg(tx_err); qDebug() << Q_FUNC_INFO << err; emit createTransactionError(err); this->currentWallet->disposeTransaction(tx); return; } else if (tx->txCount() == 0) { err = QString("%1 %2").arg(err).arg("No unmixable outputs to sweep."); qDebug() << Q_FUNC_INFO << err; emit createTransactionError(err); this->currentWallet->disposeTransaction(tx); return; } // tx created, but not sent yet. ask user to verify first. emit createTransactionSuccess(tx, address); if(this->autoCommitTx) { this->currentWallet->commitTransactionAsync(tx); } } QString AppContext::getAddress(quint32 accountIndex, quint32 addressIndex) { return this->currentWallet->address(accountIndex, addressIndex); } void AppContext::onAskReceivingPIN() { // request new receiving PIN from wowlet-backend if(this->currentWallet == nullptr) return; auto address = this->currentWallet->address(0, 1); QString signature = this->currentWallet->signMessage(address, false, address); QJsonObject data; data["signature"] = signature; data["address"] = address; QJsonObject obj; obj["cmd"] = "requestPIN"; obj["data"] = data; QJsonDocument doc = QJsonDocument(obj); this->ws->sendMsg(doc.toJson(QJsonDocument::Compact)); } void AppContext::onLookupReceivingPIN(QString pin) { // lookup PIN -> address if(this->currentWallet == nullptr) return; auto address = this->currentWallet->address(0, 1); QString signature = this->currentWallet->signMessage(address, false, address); QJsonObject data; data["PIN"] = pin; QJsonObject obj; obj["cmd"] = "lookupPIN"; obj["data"] = data; QJsonDocument doc = QJsonDocument(obj); this->ws->sendMsg(doc.toJson(QJsonDocument::Compact)); } void AppContext::onTransactionCommitted(bool status, PendingTransaction *tx, const QStringList& txid){ this->currentWallet->history()->refresh(this->currentWallet->currentSubaddressAccount()); this->currentWallet->coins()->refresh(this->currentWallet->currentSubaddressAccount()); // Store wallet immediately so we don't risk losing tx key if wallet crashes this->currentWallet->store(); this->updateBalance(); emit transactionCommitted(status, tx, txid); // this tx was a donation to WOWlet, stop our nagging if(this->donationSending) { this->donationSending = false; config()->set(Config::donateBeg, -1); } } void AppContext::storeWallet() { // Do not store a synchronizing wallet: store() is NOT thread safe and may crash the wallet if (this->currentWallet == nullptr || !this->currentWallet->synchronized()) return; qDebug() << "Storing wallet"; this->currentWallet->store(); } void AppContext::updateBalance() { if (!this->currentWallet) return; quint64 balance_u = this->currentWallet->balance(); AppContext::balance = balance_u / globals::cdiv; double spendable = this->currentWallet->unlockedBalance(); // formatted QString fmt_str = QString("Balance: %1 WOW").arg(Utils::balanceFormat(spendable)); if (balance > spendable) fmt_str += QString(" (+%1 WOW unconfirmed)").arg(Utils::balanceFormat(balance - spendable)); emit balanceUpdated(balance_u, spendable); emit balanceUpdatedFormatted(fmt_str); } void AppContext::syncStatusUpdated(quint64 height, quint64 target) { if (height < (target - 1)) { emit refreshSync(height, target); } else { this->updateBalance(); emit synchronized(); } } void AppContext::refreshModels() { if (!this->currentWallet) return; this->currentWallet->history()->refresh(this->currentWallet->currentSubaddressAccount()); this->currentWallet->subaddress()->refresh(this->currentWallet->currentSubaddressAccount()); this->currentWallet->coins()->refresh(this->currentWallet->currentSubaddressAccount()); // Todo: set timer for refreshes } void AppContext::setupPathsUnix() { this->defaultWalletDir = QString("%1/Wownero/wallets").arg(this->configRoot); this->defaultWalletDirRoot = QString("%1/Wownero").arg(this->configRoot); } void AppContext::setupPathsWindows() { this->defaultWalletDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/Wownero"; this->defaultWalletDirRoot = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); } void AppContext::setupPathsAndroid() { this->defaultWalletDir = QString("%1/Wownero/wallets").arg(this->pathGenericData); this->defaultWalletDirRoot = QString("%1/Wownero").arg(this->pathGenericData); } void AppContext::setupPathsTails() { QString portablePath = []{ QString appImagePath = qgetenv("APPIMAGE"); if (appImagePath.isEmpty()) { qDebug() << "Not an appimage, using currentPath()"; return QDir::currentPath() + "/.wowlet"; } QFileInfo appImageDir(appImagePath); return appImageDir.absoluteDir().path() + "/.wowlet"; }(); if (QDir().mkpath(portablePath)) { this->configRoot = portablePath; } else { qCritical() << "Unable to create portable directory: " << portablePath; } }
35.666019
181
0.651377
[ "model" ]
787167e796c488d8576c8bc7a2c0f35e9a38c33c
1,247
cc
C++
test/lib/function_def_lister_test.cc
losalamos/CoARCT
9fa4a96aa338bfdf78fed1cd1370942967562602
[ "BSD-3-Clause" ]
108
2017-02-09T17:56:35.000Z
2022-02-14T12:35:45.000Z
test/lib/function_def_lister_test.cc
losalamos/CoARCT
9fa4a96aa338bfdf78fed1cd1370942967562602
[ "BSD-3-Clause" ]
3
2017-10-11T22:41:41.000Z
2020-04-06T13:18:42.000Z
test/lib/function_def_lister_test.cc
losalamos/CoARCT
9fa4a96aa338bfdf78fed1cd1370942967562602
[ "BSD-3-Clause" ]
15
2017-02-15T22:55:32.000Z
2022-01-25T12:00:39.000Z
// global_matchers_test.cc // Jan 06, 2017 // (c) Copyright 2017 LANSLLC, all rights reserved #include "function_definition_lister.h" #include "gtest/gtest.h" #include "prep_code.h" #include <tuple> using namespace corct; using namespace clang; using namespace clang::ast_matchers; /** \brief Run a test case, \tparam Tester: subclass of finder_t; has matcher() method. \param code to match \param tst: Test object \return number of matchers*/ template <typename Tester> inline uint32_t run_case(str_t_cr code, Tester & tst) { ASTUPtr ast; ASTContext * pctx; TranslationUnitDecl * decl; std::tie(ast, pctx, decl) = prep_code(code); // decl->dump(); // uncomment for debugging auto m(tst.matcher()); finder_t finder; finder.addMatcher(m, &tst); finder.matchAST(*pctx); return tst.m_num_funcs; } TEST(func_decl_matcher, case1_BasicHit) { string_t code = "#include <iostream>\n" "void f(){}\n" "class C{\n" " public: \n" " double \n" "c(){ return 2.0;}\n" "};\n" "int g(int, C const &){\n" " /* comment */\n" "return 42;\n" "}"; FunctionDefLister fdp("f_decl"); uint32_t n_matches = run_case(code, fdp); EXPECT_EQ(n_matches, 3u); } // End of file
22.267857
59
0.653569
[ "object" ]
7876542b4a35de5f71ab9eb921e55f9953c9c0d5
24,431
hpp
C++
boost/boost/property_map/parallel/distributed_property_map.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
boost/boost/property_map/parallel/distributed_property_map.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
boost/boost/property_map/parallel/distributed_property_map.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Copyright (C) 2004-2008 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Nick Edmonds // Andrew Lumsdaine // The placement of this #include probably looks very odd relative to // the #ifndef/#define pair below. However, this placement is // extremely important to allow the various property map headers to be // included in any order. #include <boost/property_map/property_map.hpp> #ifndef BOOST_PARALLEL_DISTRIBUTED_PROPERTY_MAP_HPP #define BOOST_PARALLEL_DISTRIBUTED_PROPERTY_MAP_HPP #include <boost/assert.hpp> #include <boost/type_traits/is_base_and_derived.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <boost/optional.hpp> #include <boost/property_map/parallel/process_group.hpp> #include <boost/function/function1.hpp> #include <vector> #include <set> #include <boost/property_map/parallel/basic_reduce.hpp> #include <boost/property_map/parallel/detail/untracked_pair.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/property_map/parallel/local_property_map.hpp> #include <map> #include <boost/version.hpp> #include <boost/property_map/parallel/unsafe_serialize.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/sequenced_index.hpp> // Serialization functions for constructs we use #include <boost/serialization/utility.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace parallel { namespace detail { /************************************************************************** * Metafunction that degrades an Lvalue Property Map category tag to * a Read Write Property Map category tag. **************************************************************************/ template<bool IsLvaluePropertyMap> struct make_nonlvalue_property_map { template<typename T> struct apply { typedef T type; }; }; template<> struct make_nonlvalue_property_map<true> { template<typename> struct apply { typedef read_write_property_map_tag type; }; }; /************************************************************************** * Performs a "put" on a property map so long as the property map is * a Writable Property Map or a mutable Lvalue Property Map. This * is required because the distributed property map's message * handler handles "put" messages even for a const property map, * although receipt of a "put" message is ill-formed. **************************************************************************/ template<bool IsLvaluePropertyMap> struct maybe_put_in_lvalue_pm { template<typename PropertyMap, typename Key, typename Value> static inline void do_put(PropertyMap, const Key&, const Value&) { BOOST_ASSERT(false); } }; template<> struct maybe_put_in_lvalue_pm<true> { template<typename PropertyMap, typename Key, typename Value> static inline void do_put(PropertyMap pm, const Key& key, const Value& value) { using geofeatures_boost::put; put(pm, key, value); } }; template<typename PropertyMap, typename Key, typename Value> inline void maybe_put_impl(PropertyMap pm, const Key& key, const Value& value, writable_property_map_tag) { using geofeatures_boost::put; put(pm, key, value); } template<typename PropertyMap, typename Key, typename Value> inline void maybe_put_impl(PropertyMap pm, const Key& key, const Value& value, lvalue_property_map_tag) { typedef typename property_traits<PropertyMap>::value_type value_type; typedef typename property_traits<PropertyMap>::reference reference; // DPG TBD: Some property maps are improperly characterized as // lvalue_property_maps, when in fact they do not provide true // references. The most typical example is those property maps // built from vector<bool> and its iterators, which deal with // proxies. We don't want to mischaracterize these as not having a // "put" operation, so we only consider an lvalue_property_map as // constant if its reference is const value_type&. In fact, this // isn't even quite correct (think of a // vector<bool>::const_iterator), but at present C++ doesn't // provide us with any alternatives. typedef is_same<const value_type&, reference> is_constant; maybe_put_in_lvalue_pm<(!is_constant::value)>::do_put(pm, key, value); } template<typename PropertyMap, typename Key, typename Value> inline void maybe_put_impl(PropertyMap, const Key&, const Value&, ...) { BOOST_ASSERT(false); } template<typename PropertyMap, typename Key, typename Value> inline void maybe_put(PropertyMap pm, const Key& key, const Value& value) { maybe_put_impl(pm, key, value, typename property_traits<PropertyMap>::category()); } } // end namespace detail /** The consistency model used by the distributed property map. */ enum consistency_model { cm_forward = 1 << 0, cm_backward = 1 << 1, cm_bidirectional = cm_forward | cm_backward, cm_flush = 1 << 2, cm_reset = 1 << 3, cm_clear = 1 << 4 }; /** Distributed property map adaptor. * * The distributed property map adaptor is a property map whose * stored values are distributed across multiple non-overlapping * memory spaces on different processes. Values local to the current * process are stored within a local property map and may be * immediately accessed via @c get and @c put. Values stored on * remote processes may also be access via @c get and @c put, but the * behavior differs slightly: * * - @c put operations update a local ghost cell and send a "put" * message to the process that owns the value. The owner is free to * update its own "official" value or may ignore the put request. * * - @c get operations returns the contents of the local ghost * cell. If no ghost cell is available, one is created using the * default value provided by the "reduce" operation. See, e.g., * @ref basic_reduce and @ref property_reduce. * * Using distributed property maps requires a bit more care than using * local, sequential property maps. While the syntax and semantics are * similar, distributed property maps may contain out-of-date * information that can only be guaranteed to be synchronized by * calling the @ref synchronize function in all processes. * * To address the issue of out-of-date values, distributed property * maps are supplied with a reduction operation. The reduction * operation has two roles: * * -# When a value is needed for a remote key but no value is * immediately available, the reduction operation provides a * suitable default. For instance, a distributed property map * storing distances may have a reduction operation that returns * an infinite value as the default, whereas a distributed * property map for vertex colors may return white as the * default. * * -# When a value is received from a remote process, the process * owning the key associated with that value must determine which * value---the locally stored value, the value received from a * remote process, or some combination of the two---will be * stored as the "official" value in the property map. The * reduction operation transforms the local and remote values * into the "official" value to be stored. * * @tparam ProcessGroup the type of the process group over which the * property map is distributed and is also the medium for * communication. * * @tparam StorageMap the type of the property map that will * store values for keys local to this processor. The @c value_type of * this property map will become the @c value_type of the distributed * property map. The distributed property map models the same property * map concepts as the @c LocalPropertyMap, with one exception: a * distributed property map cannot be an LvaluePropertyMap (because * remote values are not addressable), and is therefore limited to * ReadWritePropertyMap. */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> class distributed_property_map { public: /// The key type of the property map. typedef typename property_traits<GlobalMap>::key_type key_type; /// The value type of the property map. typedef typename property_traits<StorageMap>::value_type value_type; typedef typename property_traits<StorageMap>::reference reference; typedef ProcessGroup process_group_type; private: typedef distributed_property_map self_type; typedef typename property_traits<StorageMap>::category local_category; typedef typename property_traits<StorageMap>::key_type local_key_type; typedef typename property_traits<GlobalMap>::value_type owner_local_pair; typedef typename ProcessGroup::process_id_type process_id_type; enum property_map_messages { /** A request to store a value in a property map. The message * contains a std::pair<key, data>. */ property_map_put, /** A request to retrieve a particular value in a property * map. The message contains a key. The owner of that key will * reply with a value. */ property_map_get, /** A request to update values stored on a remote processor. The * message contains a vector of keys for which the source * requests updated values. This message will only be transmitted * during synchronization. */ property_map_multiget, /** A request to store values in a ghost cell. This message * contains a vector of key/value pairs corresponding to the * sequence of keys sent to the source processor. */ property_map_multiget_reply, /** The payload containing a vector of local key-value pairs to be * put into the remote property map. A key-value std::pair will be * used to store each local key-value pair. */ property_map_multiput }; // Code from Joaquín M López Muñoz to work around unusual implementation of // std::pair in VC++ 10: template<typename First,typename Second> class pair_first_extractor { typedef std::pair<First,Second> value_type; public: typedef First result_type; const result_type& operator()(const value_type& x) const { return x.first; } result_type& operator()(value_type& x) const { return x.first; } }; public: /// The type of the ghost cells typedef multi_index::multi_index_container< std::pair<key_type, value_type>, multi_index::indexed_by< multi_index::sequenced<>, multi_index::hashed_unique< pair_first_extractor<key_type, value_type> > > > ghost_cells_type; /// Iterator into the ghost cells typedef typename ghost_cells_type::iterator iterator; /// Key-based index into the ghost cells typedef typename ghost_cells_type::template nth_index<1>::type ghost_cells_key_index_type; /// Iterator into the ghost cells (by key) typedef typename ghost_cells_key_index_type::iterator key_iterator; /** The property map category. A distributed property map cannot be * an Lvalue Property Map, because values on remote processes cannot * be addresses. */ typedef typename detail::make_nonlvalue_property_map< (is_base_and_derived<lvalue_property_map_tag, local_category>::value || is_same<lvalue_property_map_tag, local_category>::value)> ::template apply<local_category>::type category; /** Default-construct a distributed property map. This function * creates an initialized property map that must be assigned to a * valid value before being used. It is only provided here because * property maps must be Default Constructible. */ distributed_property_map() {} /** Construct a distributed property map. Builds a distributed * property map communicating over the given process group and using * the given local property map for storage. Since no reduction * operation is provided, the default reduction operation @c * basic_reduce<value_type> is used. */ distributed_property_map(const ProcessGroup& pg, const GlobalMap& global, const StorageMap& pm) : data(new data_t(pg, global, pm, basic_reduce<value_type>(), false)) { typedef handle_message<basic_reduce<value_type> > Handler; data->ghost_cells.reset(new ghost_cells_type()); Handler handler(data); data->process_group.replace_handler(handler, true); data->process_group.template get_receiver<Handler>() ->setup_triggers(data->process_group); } /** Construct a distributed property map. Builds a distributed * property map communicating over the given process group and using * the given local property map for storage. The given @p reduce * parameter is used as the reduction operation. */ template<typename Reduce> distributed_property_map(const ProcessGroup& pg, const GlobalMap& global, const StorageMap& pm, const Reduce& reduce); ~distributed_property_map(); /// Set the reduce operation of the distributed property map. template<typename Reduce> void set_reduce(const Reduce& reduce); // Set the consistency model for the distributed property map void set_consistency_model(int model); // Get the consistency model int get_consistency_model() const { return data->model; } // Set the maximum number of ghost cells that we are allowed to // maintain. If 0, all ghost cells will be retained. void set_max_ghost_cells(std::size_t max_ghost_cells); // Clear out all ghost cells void clear(); // Reset the values in all ghost cells to the default value void reset(); // Flush all values destined for remote processors void flush(); reference operator[](const key_type& key) const { owner_local_pair p = get(data->global, key); if (p.first == process_id(data->process_group)) { return data->storage[p.second]; } else { return cell(key); } } process_group_type process_group() const { return data->process_group.base(); } StorageMap& base() { return data->storage; } const StorageMap& base() const { return data->storage; } /** Sends a "put" request. * \internal * */ void request_put(process_id_type p, const key_type& k, const value_type& v) const { send(data->process_group, p, property_map_put, geofeatures_boost::parallel::detail::make_untracked_pair(k, v)); } /** Access the ghost cell for the given key. * \internal */ value_type& cell(const key_type& k, bool request_if_missing = true) const; /** Perform synchronization * \internal */ void do_synchronize(); const GlobalMap& global() const { return data->global; } GlobalMap& global() { return data->global; } struct data_t { data_t(const ProcessGroup& pg, const GlobalMap& global, const StorageMap& pm, const function1<value_type, key_type>& dv, bool has_default_resolver) : process_group(pg), global(global), storage(pm), ghost_cells(), max_ghost_cells(1000000), get_default_value(dv), has_default_resolver(has_default_resolver), model(cm_forward) { } /// The process group ProcessGroup process_group; /// A mapping from the keys of this property map to the global /// descriptor. GlobalMap global; /// Local property map StorageMap storage; /// The ghost cells shared_ptr<ghost_cells_type> ghost_cells; /// The maximum number of ghost cells we are permitted to hold. If /// zero, we are permitted to have an infinite number of ghost /// cells. std::size_t max_ghost_cells; /// Default value for remote ghost cells, as defined by the /// reduction operation. function1<value_type, key_type> get_default_value; /// True if this resolver is the "default" resolver, meaning that /// we should not be able to get() a default value; it needs to be /// request()ed first. bool has_default_resolver; // Current consistency model int model; // Function that resets all of the ghost cells to their default // values. It knows the type of the resolver, so we can eliminate // a large number of calls through function pointers. void (data_t::*reset)(); // Clear out all ghost cells void clear(); // Flush all values destined for remote processors void flush(); // Send out requests to "refresh" the values of ghost cells that // we're holding. void refresh_ghost_cells(); private: template<typename Resolver> void do_reset(); friend class distributed_property_map; }; friend struct data_t; shared_ptr<data_t> data; private: // Prunes the least recently used ghost cells until we have @c // max_ghost_cells or fewer ghost cells. void prune_ghost_cells() const; /** Handles incoming messages. * * This function object is responsible for handling all incoming * messages for the distributed property map. */ template<typename Reduce> struct handle_message { explicit handle_message(const shared_ptr<data_t>& data, const Reduce& reduce = Reduce()) : data_ptr(data), reduce(reduce) { } void operator()(process_id_type source, int tag); /// Individual message handlers void handle_put(int source, int tag, const geofeatures_boost::parallel::detail::untracked_pair<key_type, value_type>& data, trigger_receive_context); value_type handle_get(int source, int tag, const key_type& data, trigger_receive_context); void handle_multiget(int source, int tag, const std::vector<key_type>& data, trigger_receive_context); void handle_multiget_reply (int source, int tag, const std::vector<geofeatures_boost::parallel::detail::untracked_pair<key_type, value_type> >& msg, trigger_receive_context); void handle_multiput (int source, int tag, const std::vector<unsafe_pair<local_key_type, value_type> >& data, trigger_receive_context); void setup_triggers(process_group_type& pg); private: weak_ptr<data_t> data_ptr; Reduce reduce; }; /* Sets up the next stage in a multi-stage synchronization, for bidirectional consistency. */ struct on_synchronize { explicit on_synchronize(const shared_ptr<data_t>& data) : data_ptr(data) { } void operator()(); private: weak_ptr<data_t> data_ptr; }; }; /* An implementation helper macro for the common case of naming distributed property maps with all of the normal template parameters. */ #define PBGL_DISTRIB_PMAP \ distributed_property_map<ProcessGroup, GlobalMap, StorageMap> /* Request that the value for the given remote key be retrieved in the next synchronization round. */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> inline void request(const PBGL_DISTRIB_PMAP& pm, typename PBGL_DISTRIB_PMAP::key_type const& key) { if (get(pm.data->global, key).first != process_id(pm.data->process_group)) pm.cell(key, false); } /** Get the value associated with a particular key. Retrieves the * value associated with the given key. If the key denotes a * locally-owned object, it returns the value from the local property * map; if the key denotes a remotely-owned object, retrieves the * value of the ghost cell for that key, which may be the default * value provided by the reduce operation. * * Complexity: For a local key, O(1) get operations on the underlying * property map. For a non-local key, O(1) accesses to the ghost cells. */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> inline typename PBGL_DISTRIB_PMAP::value_type get(const PBGL_DISTRIB_PMAP& pm, typename PBGL_DISTRIB_PMAP::key_type const& key) { using geofeatures_boost::get; typename property_traits<GlobalMap>::value_type p = get(pm.data->global, key); if (p.first == process_id(pm.data->process_group)) { return get(pm.data->storage, p.second); } else { return pm.cell(key); } } /** Put a value associated with the given key into the property map. * When the key denotes a locally-owned object, this operation updates * the underlying local property map. Otherwise, the local ghost cell * is updated and a "put" message is sent to the processor owning this * key. * * Complexity: For a local key, O(1) put operations on the underlying * property map. For a nonlocal key, O(1) accesses to the ghost cells * and will send O(1) messages of size O(sizeof(key) + sizeof(value)). */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> void put(const PBGL_DISTRIB_PMAP& pm, typename PBGL_DISTRIB_PMAP::key_type const & key, typename PBGL_DISTRIB_PMAP::value_type const & value) { using geofeatures_boost::put; typename property_traits<GlobalMap>::value_type p = get(pm.data->global, key); if (p.first == process_id(pm.data->process_group)) { put(pm.data->storage, p.second, value); } else { if (pm.data->model & cm_forward) pm.request_put(p.first, key, value); pm.cell(key, false) = value; } } /** Put a value associated with a given key into the local view of the * property map. This operation is equivalent to @c put, but with one * exception: no message will be sent to the owning processor in the * case of a remote update. The effect is that any value written via * @c local_put for a remote key may be overwritten in the next * synchronization round. */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> void local_put(const PBGL_DISTRIB_PMAP& pm, typename PBGL_DISTRIB_PMAP::key_type const & key, typename PBGL_DISTRIB_PMAP::value_type const & value) { using geofeatures_boost::put; typename property_traits<GlobalMap>::value_type p = get(pm.data->global, key); if (p.first == process_id(pm.data->process_group)) put(pm.data->storage, p.second, value); else pm.cell(key, false) = value; } /** Cache the value associated with the given remote key. If the key * is local, ignore the operation. */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap> inline void cache(const PBGL_DISTRIB_PMAP& pm, typename PBGL_DISTRIB_PMAP::key_type const & key, typename PBGL_DISTRIB_PMAP::value_type const & value) { typename ProcessGroup::process_id_type id = get(pm.data->global, key).first; if (id != process_id(pm.data->process_group)) pm.cell(key, false) = value; } /// Synchronize the property map. template<typename ProcessGroup, typename GlobalMap, typename StorageMap> void synchronize(PBGL_DISTRIB_PMAP& pm) { pm.do_synchronize(); } /// Create a distributed property map. template<typename ProcessGroup, typename GlobalMap, typename StorageMap> inline distributed_property_map<ProcessGroup, GlobalMap, StorageMap> make_distributed_property_map(const ProcessGroup& pg, GlobalMap global, StorageMap storage) { typedef distributed_property_map<ProcessGroup, GlobalMap, StorageMap> result_type; return result_type(pg, global, storage); } /** * \overload */ template<typename ProcessGroup, typename GlobalMap, typename StorageMap, typename Reduce> inline distributed_property_map<ProcessGroup, GlobalMap, StorageMap> make_distributed_property_map(const ProcessGroup& pg, GlobalMap global, StorageMap storage, Reduce reduce) { typedef distributed_property_map<ProcessGroup, GlobalMap, StorageMap> result_type; return result_type(pg, global, storage, reduce); } } } // end namespace geofeatures_boost::parallel #include <boost/property_map/parallel/impl/distributed_property_map.ipp> #undef PBGL_DISTRIB_PMAP #endif // BOOST_PARALLEL_DISTRIBUTED_PROPERTY_MAP_HPP
35.20317
118
0.707912
[ "object", "vector", "model" ]
7878c8495ca5088f0612212e5bc0be5f7f11bbe0
1,199
cpp
C++
tests/test_tbb.cpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
228
2018-11-23T19:32:42.000Z
2022-03-25T10:30:51.000Z
tests/test_tbb.cpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
14
2019-03-11T22:44:14.000Z
2022-03-16T14:50:35.000Z
tests/test_tbb.cpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
45
2018-12-31T02:04:57.000Z
2022-03-08T02:42:01.000Z
//////////////////////////////////////////////////////////////////////////////// #ifdef POLYFEM_WITH_TBB #include <catch.hpp> #include <iostream> #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> #include <tbb/enumerable_thread_specific.h> //////////////////////////////////////////////////////////////////////////////// TEST_CASE("parallel_for", "[tbb_test]") { std::vector<int> data(100000); tbb::parallel_for(size_t(0), data.size(), [&](size_t i) { data[i] = -10; }); } TEST_CASE("parallel_for_memory", "[tbb_test]") { typedef tbb::enumerable_thread_specific<std::pair<int, int>> CounterType; CounterType counters(std::make_pair(0, 0)); tbb::parallel_for(tbb::blocked_range<int>(0, 100000000), [&](const tbb::blocked_range<int> &r) { CounterType::reference loc_counter = counters.local(); ++loc_counter.first; for (int i = r.begin(); i != r.end(); ++i) ++loc_counter.second; }); for (CounterType::const_iterator i = counters.begin(); i != counters.end(); ++i) { printf("Thread stats:\n"); printf(" calls to operator(): %d", i->first); printf(" total # of iterations executed: %d\n\n", i->second); } } #endif
29.243902
95
0.559633
[ "vector" ]
787942ac47481e1b5db85b7b9f754eac223e75db
5,004
hpp
C++
framework/code/material/material.hpp
MikeCurrington/adreno-gpu-vulkan-code-sample-framework
2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb
[ "BSD-3-Clause" ]
null
null
null
framework/code/material/material.hpp
MikeCurrington/adreno-gpu-vulkan-code-sample-framework
2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb
[ "BSD-3-Clause" ]
null
null
null
framework/code/material/material.hpp
MikeCurrington/adreno-gpu-vulkan-code-sample-framework
2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause #pragma once #include <map> #include <vector> #include <string> #include <memory> #define VK_ENABLE_BETA_EXTENSIONS #include <vulkan/vulkan.h> #include "descriptorSetLayout.hpp" // Forward declarations class Vulkan; class Shader; class ShaderPass; class VulkanTexInfo; /// @defgroup Material /// Material and Shader loader. /// Handles creation of descriptor sets, buffer binding, shader binaries (everything in Vulkan that describes and is used to render a shader). /// /// Typically user (application) writes a Json description for each 'Shader' that describes the inputs, outputs, and internal state of the shader, and the shader code (glsl). /// The user then uses ShaderManager::AddShader to register (and load) each Json file and the shader binaries. /// /// From there the user uses MaterialManager::CreateMaterial to create a Material instance of the Shader (a Material contains bindings to the various texture/buffer inputs that a Shader requires - there can be many Materials using the same Shader (each Material with different textures, vertex buffers and/or uniform buffers etc) /// /// The Material returned by CreateMaterial can be used to Create a Drawable or Computable object that wraps everything together with one convenient interface! /// /// For more complex models the user should use DrawableLoader::LoadDrawable to load the mesh model file (and return a vector of Drawables). This api greatly simplifies the material creation and binding, splitting model meshes across material boundaries, automatically detecting instances (optionally). /// /// An instance of a ShaderPass material. /// @ingroup Material class MaterialPass { MaterialPass(const MaterialPass&) = delete; MaterialPass& operator=(const MaterialPass&) = delete; public: MaterialPass(MaterialPass&&) noexcept; struct ImageInfo { ImageInfo(ImageInfo&&) = default; ImageInfo(const ImageInfo&) = delete; ImageInfo& operator=(const ImageInfo&) = delete; ImageInfo(const VulkanTexInfo&); VkImage image; VkImageView imageView; VkImageLayout imageLayout; }; typedef std::vector<const VulkanTexInfo*> tPerFrameTexInfo; typedef std::vector<VkBuffer> tPerFrameVkBuffer; typedef std::vector <std::pair<tPerFrameTexInfo, DescriptorSetLayout::BindingTypeAndIndex>> tTextureBindings; typedef std::vector <std::pair<ImageInfo, DescriptorSetLayout::BindingTypeAndIndex>> tImageBindings; typedef std::vector <std::pair<tPerFrameVkBuffer, DescriptorSetLayout::BindingTypeAndIndex>> tBufferBindings; MaterialPass(Vulkan& vulkan, const ShaderPass&, VkDescriptorPool&&, std::vector<VkDescriptorSet>&&, tTextureBindings&&, tImageBindings&&, tBufferBindings&&); ~MaterialPass(); /// Get the descriptor set for the (numbered) frame buffer index, allows for a single descriptor set identical for all frames if required. const auto& GetVkDescriptorSet(uint32_t bufferIndex) const { return mDescriptorSets[mDescriptorSets.size() > 1 ? bufferIndex : 0]; } const auto& GetVkDescriptorSets() const { return mDescriptorSets; } const auto& GetTextureBindings() const { return mTextureBindings; } const auto& GetImageBindings() const { return mImageBindings; } bool UpdateDescriptorSets(uint32_t bufferIdx); const ShaderPass& mShaderPass; protected: Vulkan& mVulkan; // Vulkan objects VkDescriptorPool mDescriptorPool; std::vector<VkDescriptorSet> mDescriptorSets; ///< array of descriptor sets (one per NUM_VULKAN_BUFFERS) tTextureBindings mTextureBindings; ///< Images (textures) (with sampler) considered readonly tImageBindings mImageBindings; ///< Images that may be bound as writable (or read/write). tBufferBindings mBufferBindings; }; /// An instance of a Shader material. /// Container for MaterialPasses and reference to this material's Shader /// @ingroup Material class Material { Material(const Material&) = delete; Material& operator=(const Material&) = delete; public: Material(const Shader& shader); Material(Material&&) noexcept; ~Material(); void AddMaterialPass(const std::string& passName, MaterialPass&& pass) { if (m_materialPassNamesToIndex.try_emplace(passName, (uint32_t)m_materialPasses.size()).second == true) { m_materialPasses.emplace_back(std::move(pass)); } // else pass name already exists - do nothing! } const MaterialPass* GetMaterialPass(const std::string& passName) const; const auto& GetMaterialPasses() const { return m_materialPasses; } bool UpdateDescriptorSets(uint32_t bufferIdx); const Shader& m_shader; protected: std::map<std::string, uint32_t> m_materialPassNamesToIndex; // pass name to index in m_materialPasses std::vector<MaterialPass> m_materialPasses; };
43.513043
329
0.740608
[ "mesh", "render", "object", "vector", "model" ]
787c0f744aadcc454aa726dc478ebf0a56c1d220
2,338
cpp
C++
solved/0-b/a-question-of-time/time.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/a-question-of-time/time.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/a-question-of-time/time.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cstdio> #include <string> #include <vector> using namespace std; #define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v) #define MAXT 500 int gcd(int a, int b) { for (int c = a%b; c; a=b,b=c,c=a%b); return b; } // Fraction struct Fraction { int p, q; Fraction(int P, int Q) : p(P), q(Q) { simplify(); } Fraction(int P) : p(P), q(1) {} Fraction() {} void simplify() { int g = gcd(p, q); p /= g; q /= g; } Fraction operator+(const Fraction &f) const { return Fraction(p * f.q + q * f.p, q * f.q); } Fraction operator-(const Fraction &f) const { return Fraction(p * f.q - q * f.p, q * f.q); } Fraction operator*(const Fraction &f) const { return Fraction(p * f.p, q * f.q); } Fraction operator/(const Fraction &f) const { return Fraction(p * f.q, q * f.p); } Fraction operator*(int n) const { return Fraction(p * n, q); } Fraction operator%(int m) const { return Fraction(p % (m*q), q); } bool operator<(const Fraction &f) const { return p*f.q < f.p*q; } bool operator==(int n) const { return p == n*q; } bool operator<=(int n) const { return p <= n*q; } bool operator>=(int n) const { return p >= n*q; } }; typedef vector<Fraction> FV; int read_time() { int h, m, s; scanf("%d:%d:%d", &h, &m, &s); return h*3600 + m*60 + s; } void print_time(const Fraction &t) { printf("%02d:%02d:%02d", t.p / (3600*t.q), t.p / (60*t.q) % 60, t.p/t.q % 60); Fraction sec(t.p % t.q, t.q); if (sec.p != 0) printf(" %d/%d", sec.p, sec.q); puts(""); } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { int sym = read_time(); int str = read_time(); int end = read_time(); FV sol; Fraction x; Fraction f1(360, 43200); Fraction f2(360, 3600); for (int i = 0; i < 13; ++i) { x = (f1 * 2 * sym + f2 * 3600 * i) / (f1 + f2) % 43200; if (x >= str && x <= end) sol.push_back(x); } printf("Case %d: %d\n", ++ncase, sol.size()); sort(sol.begin(), sol.end()); cFor (FV, t, sol) print_time(*t); } return 0; }
22.921569
74
0.49059
[ "vector" ]
787dcff22d67e251c4505859378a15db2ac93a1e
12,026
cpp
C++
dev/Code/Framework/AzCore/AzCore/Debug/AssetTracking.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzCore/AzCore/Debug/AssetTracking.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzCore/AzCore/Debug/AssetTracking.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "AssetTracking.h" #include <AzCore/Debug/AssetTrackingTypes.h> #include <AzCore/Memory/AllocatorManager.h> #include <AzCore/Memory/HphaSchema.h> #include <AzCore/std/containers/map.h> #include <AzCore/std/smart_ptr/make_shared.h> namespace AZ { namespace Debug { namespace { struct AssetTreeNode; // Per-thread data that needs to be stored. struct ThreadData { AZStd::vector<AssetTreeNodeBase*, AZStdAssetTrackingAllocator> m_currentAssetStack; }; // Access thread data through a virtual function to ensure that the same thread-local data is being shared across DLLs. // Otherwise, the thread_local variables are replicated across DLLs that link the AzCore library, and you'll get a // different version in each module. class ThreadDataProvider { public: virtual ThreadData& GetThreadData() = 0; }; } class AssetTrackingImpl final : public ThreadDataProvider { public: AZ_TYPE_INFO(AssetTrackingImpl, "{01E2A099-3523-40BE-80E0-E0ADD861BEE1}"); AZ_CLASS_ALLOCATOR(AssetTrackingImpl, OSAllocator, 0); AssetTrackingImpl(AssetTreeBase* assetTree, AssetAllocationTableBase* allocationTable); ~AssetTrackingImpl(); void AssetBegin(const char* id, const char* file, int line); void AssetAttach(void* otherAllocation, const char* file, int line); void AssetEnd(); ThreadData& GetThreadData() override; private: static EnvironmentVariable<AssetTrackingImpl*>& GetEnvironmentVariable(); static AssetTrackingImpl* GetSharedInstance(); static ThreadData& GetSharedThreadData(); using MasterAssets = AZStd::unordered_map<AssetTrackingId, AssetMasterInfo, AZStd::hash<AssetTrackingId>, AZStd::equal_to<AssetTrackingId>, AZStdAssetTrackingAllocator>; using ThreadData = ThreadData; using mutex_type = AZStd::mutex; using lock_type = AZStd::lock_guard<mutex_type>; mutex_type m_mutex; MasterAssets m_masterAssets; AssetTreeNodeBase* m_assetRoot = nullptr; AssetAllocationTableBase* m_allocationTable = nullptr; bool m_performingAnalysis = false; friend class AssetTracking; friend class AssetTracking::Scope; }; } } /////////////////////////////////////////////////////////////////////////////// // AssetTrackingImpl methods /////////////////////////////////////////////////////////////////////////////// namespace AZ { namespace Debug { AssetTrackingImpl::AssetTrackingImpl(AssetTreeBase* assetTree, AssetAllocationTableBase* allocationTable) : m_assetRoot(&assetTree->GetRoot()), m_allocationTable(allocationTable) { AZ_Assert(!GetSharedInstance(), "Only one AssetTrackingImpl can exist!"); GetEnvironmentVariable().Set(this); AllocatorManager::Instance().EnterProfilingMode(); } AssetTrackingImpl::~AssetTrackingImpl() { AllocatorManager::Instance().ExitProfilingMode(); GetEnvironmentVariable().Reset(); } void AssetTrackingImpl::AssetBegin(const char* id, const char* file, int line) { // In the future it may be desirable to organize assets based on where in code the asset was entered into. // For now these are ignored. AZ_UNUSED(file); AZ_UNUSED(line); using namespace Internal; AssetTrackingId assetId(id); auto& threadData = GetSharedThreadData(); AssetTreeNodeBase* parentAsset = threadData.m_currentAssetStack.empty() ? nullptr : threadData.m_currentAssetStack.back(); AssetTreeNodeBase* childAsset; AssetMasterInfo* assetMasterInfo; if (!parentAsset) { parentAsset = m_assetRoot; } { lock_type lock(m_mutex); // Locate or create the master record for this asset auto masterItr = m_masterAssets.find(assetId); if (masterItr != m_masterAssets.end()) { assetMasterInfo = &masterItr->second; } else { auto insertResult = m_masterAssets.emplace(assetId, AssetMasterInfo()); assetMasterInfo = &insertResult.first->second; assetMasterInfo->m_id = &insertResult.first->first; } // Add this asset to the stack for this thread's context childAsset = parentAsset->FindOrAddChild(assetId, assetMasterInfo); } threadData.m_currentAssetStack.push_back(childAsset); } void AssetTrackingImpl::AssetAttach(void* otherAllocation, const char* file, int line) { AZ_UNUSED(file); AZ_UNUSED(line); using namespace Internal; AssetTreeNodeBase* assetInfo = m_allocationTable->FindAllocation(otherAllocation); // We will push back a nullptr if there is no asset, this is necessary to balance the call to AssetEnd() GetSharedThreadData().m_currentAssetStack.push_back(assetInfo); } void AssetTrackingImpl::AssetEnd() { AZ_Assert(!GetSharedThreadData().m_currentAssetStack.empty(), "AssetEnd() called without matching AssetBegin() or AssetAttach. Use the AZ_ASSET_NAMED_SCOPE and AZ_ASSET_ATTACH_TO_SCOPE macros to avoid this!"); GetSharedThreadData().m_currentAssetStack.pop_back(); } AssetTrackingImpl* AssetTrackingImpl::GetSharedInstance() { auto environmentVariable = GetEnvironmentVariable(); if(environmentVariable) { return *environmentVariable; } return nullptr; } ThreadData& AssetTrackingImpl::GetSharedThreadData() { // Cast to the base type so our virtual call doesn't get optimized away. We require GetThreadData() to be executed in the same DLL every time. return static_cast<ThreadDataProvider*>(GetSharedInstance())->GetThreadData(); } AssetTrackingImpl::ThreadData& AssetTrackingImpl::GetThreadData() { static thread_local ThreadData* data = nullptr; static thread_local typename AZStd::aligned_storage_t<sizeof(ThreadData), alignof(ThreadData)> storage; if (!data) { data = new (&storage) ThreadData; } return *data; } EnvironmentVariable<AssetTrackingImpl*>& AssetTrackingImpl::GetEnvironmentVariable() { static EnvironmentVariable<AssetTrackingImpl*> assetTrackingImpl = Environment::CreateVariable<AssetTrackingImpl*>(AzTypeInfo<AssetTrackingImpl*>::Name()); return assetTrackingImpl; } /////////////////////////////////////////////////////////////////////////////// // AssetTracking::Scope functions /////////////////////////////////////////////////////////////////////////////// AssetTracking::Scope AssetTracking::Scope::ScopeFromAssetId(const char* file, int line, const char* fmt, ...) { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { static const int BUFFER_SIZE = 1024; char buffer[BUFFER_SIZE]; va_list args; va_start(args, fmt); azvsnprintf(buffer, BUFFER_SIZE, fmt, args); va_end(args); impl->AssetBegin(buffer, file, line); } return Scope(); } AssetTracking::Scope AssetTracking::Scope::ScopeFromAttachment(void* attachTo, const char* file, int line) { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { impl->AssetAttach(attachTo, file, line); } return Scope(); } AssetTracking::Scope::~Scope() { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { impl->AssetEnd(); } } AssetTracking::Scope::Scope() { } /////////////////////////////////////////////////////////////////////////////// // AssetTracking functions /////////////////////////////////////////////////////////////////////////////// void AssetTracking::EnterScopeByAssetId(const char* file, int line, const char* fmt, ...) { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { static const int BUFFER_SIZE = 1024; char buffer[BUFFER_SIZE]; va_list args; va_start(args, fmt); azvsnprintf(buffer, BUFFER_SIZE, fmt, args); va_end(args); impl->AssetBegin(buffer, file, line); } } void AssetTracking::EnterScopeByAttachment(void* attachTo, const char* file, int line) { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { impl->AssetAttach(attachTo, file, line); } } void AssetTracking::ExitScope() { if (auto impl = AssetTrackingImpl::GetSharedInstance()) { impl->AssetEnd(); } } const char* AssetTracking::GetDebugScope() { // Output debug information about the current asset scope in the current thread. // Do not use in production code. #ifndef RELEASE static const int BUFFER_SIZE = 1024; static char buffer[BUFFER_SIZE]; const auto& assetStack = AssetTrackingImpl::GetSharedInstance()->GetThreadData().m_currentAssetStack; if (assetStack.empty()) { azsnprintf(buffer, BUFFER_SIZE, "<none>"); } else { char* pos = buffer; for (auto itr = assetStack.rbegin(); itr != assetStack.rend(); ++itr) { pos += azsnprintf(pos, BUFFER_SIZE - (pos - buffer), "%s\n", (*itr)->GetAssetMasterInfo()->m_id->m_id.c_str()); if (pos >= buffer + BUFFER_SIZE) { break; } } } return buffer; #else return ""; #endif } AssetTracking::AssetTracking(AssetTreeBase* assetTree, AssetAllocationTableBase* allocationTable) { m_impl.reset(aznew AssetTrackingImpl(assetTree, allocationTable)); } AssetTracking::~AssetTracking() { } AssetTreeNodeBase* AssetTracking::GetCurrentThreadAsset() const { const auto& assetStack = m_impl->GetThreadData().m_currentAssetStack; AssetTreeNodeBase* result = assetStack.empty() ? nullptr : assetStack.back(); return result; } } } // namespace AzFramework
35.266862
221
0.562947
[ "vector" ]
7881a94f353df7c9e2b502095f9eec1f3cfb3ef2
4,743
cc
C++
lib/native/writer.cc
NickNaso/orientjs-native
55d0ea6f60e151c96bfe9d8b4c2ceae7b1d1a13d
[ "Apache-2.0" ]
null
null
null
lib/native/writer.cc
NickNaso/orientjs-native
55d0ea6f60e151c96bfe9d8b4c2ceae7b1d1a13d
[ "Apache-2.0" ]
null
null
null
lib/native/writer.cc
NickNaso/orientjs-native
55d0ea6f60e151c96bfe9d8b4c2ceae7b1d1a13d
[ "Apache-2.0" ]
null
null
null
#include "writer.h" #include <math.h> #include <iostream> void writeMap(v8::Local<v8::Object> toWrite, Orient::RecordWriter & writer); void writeArray(v8::Local<v8::Array> toWrite, Orient::RecordWriter & writer); void writeValue(v8::Local<v8::Value> value, Orient::RecordWriter & writer); // not supported in node 0.x // //void writeBinary(v8::Local<v8::Uint8Array> toWrite, Orient::RecordWriter & writer); void writeObject(v8::Local<v8::Object> toWrite,Orient::RecordWriter & writer){ v8::Local<v8::String> classKey = Nan::New("@class").ToLocalChecked(); if(toWrite->Has(classKey)){ v8::Local<v8::Value> val = toWrite->Get(classKey); if(val->IsString()){ v8::Local<v8::String> clazz = val->ToString(); v8::String::Utf8Value clazzVal(clazz); writer.startDocument(*clazzVal); }else if(val->IsObject()) { v8::Local<v8::String> nameKey = Nan::New("name").ToLocalChecked(); v8::Local<v8::Object> classObj = val->ToObject(); if(classObj->Has(nameKey)){ v8::Local<v8::String> clazz = classObj->Get(nameKey)->ToString(); v8::String::Utf8Value clazzVal(clazz); writer.startDocument(*clazzVal); }else writer.startDocument(""); }else writer.startDocument(""); } else { writer.startDocument(""); } v8::Local<v8::Array> properties = toWrite->GetPropertyNames(); unsigned int i; for(i = 0; i< properties->Length() ; i ++){ v8::Local<v8::String> name = v8::Local<v8::String>::Cast(properties->Get(i)); v8::String::Utf8Value val(name); if((*val)[0] != '@') { writer.startField(*val); v8::Local<v8::Value> value = toWrite->Get(name); writeValue(value,writer); writer.endField(*val); } } writer.endDocument(); } void writeValue(v8::Local<v8::Value> value, Orient::RecordWriter & writer) { if(value->IsString()){ v8::String::Utf8Value sval(value->ToString()); writer.stringValue(*sval); } else if (value->IsInt32()){ writer.intValue(value->ToInt32(Nan::GetCurrentContext()).ToLocalChecked()->Value()); } else if (value->IsNumber()){ v8::Local<v8::Number> num = value->ToNumber(Nan::GetCurrentContext()).ToLocalChecked(); double val = num->Value(); if(ceil(val) != 0 ) writer.doubleValue(val); else writer.longValue(val); } else if (value->IsDate()){ long long int date= v8::Local<v8::Date>::Cast(value)->NumberValue(); writer.dateTimeValue(date); } else if (value->IsNull()){ writer.nullValue(); } else if (value->IsBoolean()){ writer.booleanValue(value->ToBoolean()->Value()); } else if (value->IsArray()){ writeArray(v8::Local<v8::Array>::Cast(value), writer); } else if (value->IsObject()){ // if(value->IsUint8Array()){ // writeBinary(value,writer); // }else { v8::Local<v8::String> typeKey = Nan::New("@type").ToLocalChecked(); //TODO: check if replace with RecordID prototype check v8::Local<v8::String> clusterKey = Nan::New("cluster").ToLocalChecked(); v8::Local<v8::String> positionKey = Nan::New("position").ToLocalChecked(); v8::Local<v8::String> dVal = Nan::New("d").ToLocalChecked(); v8::Local<v8::Object> obj = value->ToObject(); v8::String::Utf8Value val1(obj->ObjectProtoToString(Nan::GetCurrentContext()).ToLocalChecked()); if(obj->Has(typeKey) && obj->Get(typeKey)->Equals(dVal)){ writeObject(obj,writer); } else if(obj->Has(clusterKey) && obj->Has(positionKey)){ struct Orient::Link lnk; lnk.cluster = obj->Get(clusterKey)->ToNumber(Nan::GetCurrentContext()).ToLocalChecked()->Value(); lnk.position = obj->Get(positionKey)->ToNumber(Nan::GetCurrentContext()).ToLocalChecked()->Value(); writer.linkValue(lnk); } else { writeMap(obj,writer); } } } void writeMap(v8::Local<v8::Object> toWrite, Orient::RecordWriter & writer) { v8::Local<v8::Array> properties = toWrite->GetPropertyNames(); unsigned int i; writer.startMap(properties->Length(),Orient::EMBEDDEDMAP); for(i = 0; i< properties->Length() ; i ++){ v8::Local<v8::String> name = v8::Local<v8::String>::Cast(properties->Get(i)); v8::String::Utf8Value val(name); writer.mapKey(*val); v8::Local<v8::Value> value = toWrite->Get(name); writeValue(value,writer); } writer.endMap(Orient::EMBEDDEDMAP); } void writeArray(v8::Local<v8::Array> toWrite, Orient::RecordWriter & writer){ unsigned int i; writer.startCollection(toWrite->Length(),Orient::EMBEDDEDLIST); for(i = 0; i< toWrite->Length() ; i ++){ v8::Local<v8::Value> value = toWrite->Get(i); writeValue(value,writer); } writer.endCollection(Orient::EMBEDDEDLIST); } // Not supported in node 0.x //void writeBinary(v8::Local<v8::Uint8Array toWrite, Orient::RecordWriter & writer){ // // char* buf = node::Buffer::Data(toWrite->ToObject()); // writer.binaryValue(buf,toWrite->Length()); //}
35.133333
103
0.670251
[ "object" ]
78825ea28191c79846bbde9e6c6a4bc643b5feec
4,234
cpp
C++
src/parser/transform/expression/transform_expression.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/parser/transform/expression/transform_expression.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/parser/transform/expression/transform_expression.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/common/exception.hpp" #include "guinsoodb/parser/expression/default_expression.hpp" #include "guinsoodb/parser/transformer.hpp" namespace guinsoodb { unique_ptr<ParsedExpression> Transformer::TransformResTarget(guinsoodb_libpgquery::PGResTarget *root) { if (!root) { return nullptr; } auto expr = TransformExpression(root->val); if (!expr) { return nullptr; } if (root->name) { expr->alias = string(root->name); } return expr; } unique_ptr<ParsedExpression> Transformer::TransformNamedArg(guinsoodb_libpgquery::PGNamedArgExpr *root) { if (!root) { return nullptr; } auto expr = TransformExpression((guinsoodb_libpgquery::PGNode *)root->arg); if (root->name) { expr->alias = string(root->name); } return expr; } unique_ptr<ParsedExpression> Transformer::TransformExpression(guinsoodb_libpgquery::PGNode *node) { if (!node) { return nullptr; } switch (node->type) { case guinsoodb_libpgquery::T_PGColumnRef: return TransformColumnRef(reinterpret_cast<guinsoodb_libpgquery::PGColumnRef *>(node)); case guinsoodb_libpgquery::T_PGAConst: return TransformConstant(reinterpret_cast<guinsoodb_libpgquery::PGAConst *>(node)); case guinsoodb_libpgquery::T_PGAExpr: return TransformAExpr(reinterpret_cast<guinsoodb_libpgquery::PGAExpr *>(node)); case guinsoodb_libpgquery::T_PGFuncCall: return TransformFuncCall(reinterpret_cast<guinsoodb_libpgquery::PGFuncCall *>(node)); case guinsoodb_libpgquery::T_PGBoolExpr: return TransformBoolExpr(reinterpret_cast<guinsoodb_libpgquery::PGBoolExpr *>(node)); case guinsoodb_libpgquery::T_PGTypeCast: return TransformTypeCast(reinterpret_cast<guinsoodb_libpgquery::PGTypeCast *>(node)); case guinsoodb_libpgquery::T_PGCaseExpr: return TransformCase(reinterpret_cast<guinsoodb_libpgquery::PGCaseExpr *>(node)); case guinsoodb_libpgquery::T_PGSubLink: return TransformSubquery(reinterpret_cast<guinsoodb_libpgquery::PGSubLink *>(node)); case guinsoodb_libpgquery::T_PGCoalesceExpr: return TransformCoalesce(reinterpret_cast<guinsoodb_libpgquery::PGAExpr *>(node)); case guinsoodb_libpgquery::T_PGNullTest: return TransformNullTest(reinterpret_cast<guinsoodb_libpgquery::PGNullTest *>(node)); case guinsoodb_libpgquery::T_PGResTarget: return TransformResTarget(reinterpret_cast<guinsoodb_libpgquery::PGResTarget *>(node)); case guinsoodb_libpgquery::T_PGParamRef: return TransformParamRef(reinterpret_cast<guinsoodb_libpgquery::PGParamRef *>(node)); case guinsoodb_libpgquery::T_PGNamedArgExpr: return TransformNamedArg(reinterpret_cast<guinsoodb_libpgquery::PGNamedArgExpr *>(node)); case guinsoodb_libpgquery::T_PGSQLValueFunction: return TransformSQLValueFunction(reinterpret_cast<guinsoodb_libpgquery::PGSQLValueFunction *>(node)); case guinsoodb_libpgquery::T_PGSetToDefault: return make_unique<DefaultExpression>(); case guinsoodb_libpgquery::T_PGCollateClause: return TransformCollateExpr(reinterpret_cast<guinsoodb_libpgquery::PGCollateClause *>(node)); case guinsoodb_libpgquery::T_PGIntervalConstant: return TransformInterval(reinterpret_cast<guinsoodb_libpgquery::PGIntervalConstant *>(node)); case guinsoodb_libpgquery::T_PGLambdaFunction: return TransformLambda(reinterpret_cast<guinsoodb_libpgquery::PGLambdaFunction *>(node)); case guinsoodb_libpgquery::T_PGAIndirection: return TransformArrayAccess(reinterpret_cast<guinsoodb_libpgquery::PGAIndirection *>(node)); case guinsoodb_libpgquery::T_PGPositionalReference: return TransformPositionalReference(reinterpret_cast<guinsoodb_libpgquery::PGPositionalReference *>(node)); default: throw NotImplementedException("Expr of type %d not implemented\n", (int)node->type); } } bool Transformer::TransformExpressionList(guinsoodb_libpgquery::PGList *list, vector<unique_ptr<ParsedExpression>> &result) { if (!list) { return false; } for (auto node = list->head; node != nullptr; node = node->next) { auto target = reinterpret_cast<guinsoodb_libpgquery::PGNode *>(node->data.ptr_value); if (!target) { return false; } auto expr = TransformExpression(target); if (!expr) { return false; } result.push_back(move(expr)); } return true; } } // namespace guinsoodb
41.106796
109
0.791923
[ "vector" ]
7882eba101b14504e23b34eaaf09d43bca7d6d1d
2,804
cpp
C++
Parte2/mainParte2.cpp
epicLevi/Grafosaurio
33e897c117b93748c70f1734a47eef22ee736f77
[ "MIT" ]
null
null
null
Parte2/mainParte2.cpp
epicLevi/Grafosaurio
33e897c117b93748c70f1734a47eef22ee736f77
[ "MIT" ]
null
null
null
Parte2/mainParte2.cpp
epicLevi/Grafosaurio
33e897c117b93748c70f1734a47eef22ee736f77
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <vector> #include <queue> #include <limits.h> #include <cstdio> #include "GRAPH.h" using namespace std; GRAPH_ADJ_LIST AdjLgraph; int main(){ int i_op; int N; printf("Select an opotion\n"); printf("1.- Read from file\n"); printf("2.- Ingress values manually\n"); scanf("%d", &i_op); if (i_op == 1) { printf("Reading from file :)\n"); AdjLgraph = GRAPH_ADJ_LIST("graph_input/AdjList_input.txt"); } else { scanf("%d", &N); AdjLgraph = GRAPH_ADJ_LIST(N); } AdjLgraph.PrintGraph(); system("pause"); system("cls"); while(true){ printf("\nQue deseas hace con el grafo?\n\n"); printf("1.\tCalcular y mostrar el grado de cada nodo de un grafo.\n"); printf("2.\tDeterminar si un grafo dado es conexo. \n"); printf("3.\tReportar el numero de nodos con grado par e impar \n\t\tde un grafo G para determinar si es o no un grafo euleriano. (Ver propiedad)\n"); printf("4.\tReportar si un grafo G es susceptible de ser recorrido (traversable).\n"); printf("5.\tMuestre si dos grafos dados son o no isomorfos. (Ver propiedad)\n"); printf("6.\tSALIR\n"); scanf("%d",&i_op); bool IsConvex; ii gn; if(i_op==6) break; switch (i_op){ case 1: AdjLgraph.PrintGradeNodes(); break; case 2: AdjLgraph.IsConvex(1) ? printf("Es convexo\n") : printf("No es convexo\n"); break; case 3: IsConvex = AdjLgraph.IsConvex(1); gn = AdjLgraph.GetGradeNodes(); printf("El grafo tiene: %d Nodos Impares\n",gn.first); printf("El grafo tiene: %d Nodos Pares\n",gn.second); printf("POR LO TANTO: "); if(IsConvex && !gn.first) printf("El grafo es Euleriano\n"); else printf("El grafo NO es Eucleriano\n"); break; case 4: IsConvex = AdjLgraph.IsConvex(1); gn = AdjLgraph.GetGradeNodes(); printf("El grafo tiene: %d Nodos Impares\n",gn.first); printf("El grafo tiene: %d Nodos Pares\n",gn.second); printf("POR LO TANTO: "); if(IsConvex && !gn.second) printf("El grafo es susceptible de ser recorrido (traversable) \n"); else printf("El grafo NO es susceptible de ser recorrido (traversable)\n"); break; case 5: break; } system("pause"); system("cls"); } return 0; }
33.783133
157
0.514622
[ "vector" ]
7886bfabb8ff6b0c4bb4f7f4e11ef819103f2286
7,890
hpp
C++
orca_base/include/orca_base/base_node.hpp
tsaoyu/orca2
101513efe9168d0d122158b8c26968595ddf28d4
[ "BSD-3-Clause" ]
null
null
null
orca_base/include/orca_base/base_node.hpp
tsaoyu/orca2
101513efe9168d0d122158b8c26968595ddf28d4
[ "BSD-3-Clause" ]
null
null
null
orca_base/include/orca_base/base_node.hpp
tsaoyu/orca2
101513efe9168d0d122158b8c26968595ddf28d4
[ "BSD-3-Clause" ]
null
null
null
#ifndef ORCA_BASE_BASE_NODE_HPP #define ORCA_BASE_BASE_NODE_HPP #include "fiducial_vlam_msgs/msg/map.hpp" #include "sensor_msgs/msg/imu.hpp" #include "sensor_msgs/msg/joy.hpp" #include "visualization_msgs/msg/marker_array.hpp" #include "orca_msgs/msg/barometer.hpp" #include "orca_msgs/msg/battery.hpp" #include "orca_msgs/msg/control.hpp" #include "orca_msgs/msg/leak.hpp" #include "orca_base/base_context.hpp" #include "orca_base/mission.hpp" #include "orca_base/joystick.hpp" #include "orca_base/monotonic.hpp" namespace orca_base { //============================================================================= // Utils //============================================================================= constexpr bool is_yaw_hold_mode(uint8_t mode) { using orca_msgs::msg::Control; return mode == Control::HOLD_H || mode == Control::HOLD_HD; } constexpr bool is_z_hold_mode(uint8_t mode) { using orca_msgs::msg::Control; return mode == Control::HOLD_D || mode == Control::HOLD_HD; } constexpr bool is_rov_mode(uint8_t mode) { using orca_msgs::msg::Control; return mode == Control::MANUAL || mode == Control::HOLD_H || mode == Control::HOLD_D || mode == Control::HOLD_HD; } constexpr bool is_auv_mode(uint8_t mode) { using orca_msgs::msg::Control; return mode >= Control::KEEP_STATION; } //============================================================================= // Constants //============================================================================= const rclcpp::Duration JOY_TIMEOUT{RCL_S_TO_NS(1)}; // ROV: disarm if we lose communication const rclcpp::Duration ODOM_TIMEOUT{RCL_S_TO_NS(1)}; // AUV: disarm if we lose odometry const rclcpp::Duration BARO_TIMEOUT{RCL_S_TO_NS(1)}; // Holding z: disarm if we lose barometer const rclcpp::Duration IMU_TIMEOUT{RCL_S_TO_NS(1)}; // Holding yaw: disarm if we lose IMU //============================================================================= // BaseNode provides basic ROV and AUV functions, including joystick operation and waypoint navigation. //============================================================================= class BaseNode : public rclcpp::Node { private: // Joystick assignments const int joy_axis_yaw_ = JOY_AXIS_LEFT_LR; const int joy_axis_forward_ = JOY_AXIS_LEFT_FB; const int joy_axis_strafe_ = JOY_AXIS_RIGHT_LR; const int joy_axis_vertical_ = JOY_AXIS_RIGHT_FB; const int joy_axis_yaw_trim_ = JOY_AXIS_TRIM_LR; const int joy_axis_z_trim_ = JOY_AXIS_TRIM_FB; const int joy_button_disarm_ = JOY_BUTTON_VIEW; const int joy_button_arm_ = JOY_BUTTON_MENU; const int joy_button_manual_ = JOY_BUTTON_A; const int joy_button_hold_hd_ = JOY_BUTTON_X; const int joy_button_hold_d_ = JOY_BUTTON_B; const int joy_button_keep_station_ = JOY_BUTTON_Y; const int joy_button_random_ = JOY_BUTTON_LOGO; const int joy_button_tilt_down_ = JOY_BUTTON_LEFT_BUMPER; const int joy_button_tilt_up_ = JOY_BUTTON_RIGHT_BUMPER; const int joy_button_bright_ = JOY_BUTTON_LEFT_STICK; const int joy_button_dim_ = JOY_BUTTON_RIGHT_STICK; // Parameters BaseContext cxt_; // General state uint8_t mode_; // Operating mode // Barometer state double z_initial_; // First z value, used to adjust barometer double z_; // Z from barometer // IMU state //tf2::Matrix3x3 t_imu_base_; // Static transform from the base frame to the imu frame double yaw_; // Yaw from IMU double stability_; // Roll and pitch stability, 1.0 (flat) to 0.0 (>90 degree tilt) // Joystick state sensor_msgs::msg::Joy joy_msg_; // Most recent message // Odometry state PoseStamped filtered_pose_; // Estimated pose double odom_lag_; // Difference between header.stamp and now(), in seconds // ROV operation std::shared_ptr<pid::Controller> rov_yaw_pid_; std::shared_ptr<pid::Controller> rov_z_pid_; // AUV operation std::shared_ptr<Mission> mission_; // The mission we're running fiducial_vlam_msgs::msg::Map map_; // Map of fiducial markers nav_msgs::msg::Path filtered_path_; // Estimate of the actual path (from filtered_pose_) // Outputs Efforts efforts_; // Thruster forces int tilt_; // Camera tilt int brightness_; // Lights // Subscriptions rclcpp::Subscription<orca_msgs::msg::Barometer>::SharedPtr baro_sub_; rclcpp::Subscription<orca_msgs::msg::Battery>::SharedPtr battery_sub_; rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub_; rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub_; rclcpp::Subscription<orca_msgs::msg::Leak>::SharedPtr leak_sub_; rclcpp::Subscription<fiducial_vlam_msgs::msg::Map>::SharedPtr map_sub_; rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr odom_sub_; // Timer rclcpp::TimerBase::SharedPtr spin_timer_; // Validate parameters void validate_parameters(); // Callbacks void baro_callback(const orca_msgs::msg::Barometer::SharedPtr msg, bool first); void battery_callback(const orca_msgs::msg::Battery::SharedPtr msg); void imu_callback(const sensor_msgs::msg::Imu::SharedPtr msg); void joy_callback(const sensor_msgs::msg::Joy::SharedPtr msg, bool first); void leak_callback(const orca_msgs::msg::Leak::SharedPtr msg); void map_callback(const fiducial_vlam_msgs::msg::Map::SharedPtr msg); void odom_callback(const nav_msgs::msg::Odometry::SharedPtr msg, bool first); // Callback wrappers Monotonic<BaseNode *, const orca_msgs::msg::Barometer::SharedPtr> baro_cb_{this, &BaseNode::baro_callback}; Valid<BaseNode *, const sensor_msgs::msg::Imu::SharedPtr> imu_cb_{this, &BaseNode::imu_callback}; Monotonic<BaseNode *, sensor_msgs::msg::Joy::SharedPtr> joy_cb_{this, &BaseNode::joy_callback}; Valid<BaseNode *, fiducial_vlam_msgs::msg::Map::SharedPtr> map_cb_{this, &BaseNode::map_callback}; Monotonic<BaseNode *, nav_msgs::msg::Odometry::SharedPtr> odom_cb_{this, &BaseNode::odom_callback}; // Publications rclcpp::Publisher<orca_msgs::msg::Control>::SharedPtr control_pub_; rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr thrust_marker_pub_; rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr planned_path_pub_; rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr filtered_path_pub_; rclcpp::Publisher<orca_msgs::msg::PoseError>::SharedPtr error_pub_; void rov_advance(float forward, float strafe, float yaw, float vertical); void publish_control(const rclcpp::Time &msg_time); void set_mode(uint8_t new_mode); bool holding_yaw() { return is_yaw_hold_mode(mode_); } bool holding_z() { return is_z_hold_mode(mode_); } bool rov_mode() { return is_rov_mode(mode_); } bool auv_mode() { return is_auv_mode(mode_); } bool baro_ok(const rclcpp::Time &t) { return baro_cb_.receiving() && t - baro_cb_.prev() < BARO_TIMEOUT; } bool imu_ok(const rclcpp::Time &t) { return imu_cb_.receiving() && t - imu_cb_.prev() < IMU_TIMEOUT; } bool joy_ok(const rclcpp::Time &t) { return joy_cb_.receiving() && t - joy_cb_.prev() < JOY_TIMEOUT; } bool odom_ok(const rclcpp::Time &t) { return odom_cb_.receiving() && t - odom_cb_.prev() < ODOM_TIMEOUT; } public: explicit BaseNode(); ~BaseNode() {}; // Suppress default copy and move constructors void spin_once(); }; } // namespace orca_base #endif // ORCA_BASE_BASE_NODE_HPP
37.932692
117
0.648416
[ "transform" ]
78887f127598bbd0f33b8c65b195654d6ce73251
33,682
cpp
C++
graphics/applications/view-points.cpp
jackiecx/snark
492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6
[ "BSD-3-Clause" ]
1
2019-06-14T15:21:24.000Z
2019-06-14T15:21:24.000Z
graphics/applications/view-points.cpp
jackiecx/snark
492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6
[ "BSD-3-Clause" ]
null
null
null
graphics/applications/view-points.cpp
jackiecx/snark
492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6
[ "BSD-3-Clause" ]
null
null
null
// This file is part of snark, a generic and flexible library for robotics research // Copyright (c) 2011 The University of Sydney // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <comma/application/command_line_options.h> #include <comma/base/types.h> #include <comma/csv/options.h> #include <comma/csv/stream.h> #include <comma/csv/traits.h> #include <comma/name_value/parser.h> #include <comma/string/string.h> #include <snark/graphics/applications/view_points/MainWindow.h> #include <snark/graphics/applications/view_points/Viewer.h> #include <snark/graphics/applications/view_points/ShapeReader.h> #include <snark/graphics/applications/view_points/ModelReader.h> #include <snark/graphics/applications/view_points/TextureReader.h> #include <QApplication> void usage() { std::cerr << std::endl; std::cerr << "view 3D point clouds:" << std::endl; std::cerr << "view points from given files/streams and stdin" << std::endl; std::cerr << "(see examples below for a quick start)" << std::endl; std::cerr << std::endl; std::cerr << "note: scene radius, centre and point of view will be decided" << std::endl; std::cerr << " depending on the extents of the first data source" << std::endl; std::cerr << " (if you want it to be stdin, specify \"-\" as the" << std::endl; std::cerr << " explicitly as the first data source); see also" << std::endl; std::cerr << " --scene-radius option and examples" << std::endl; std::cerr << std::endl; std::cerr << "usage: view-points [<options>] [<filenames>]" << std::endl; std::cerr << std::endl; std::cerr << "input data options" << std::endl; std::cerr << " --colour,--color,-c <how>: how to colour points" << std::endl; std::cerr << " <how>:" << std::endl; std::cerr << " colour maps" << std::endl; std::cerr << " <min>:<max>: if scalar field present, stretch by scalar (see section <fields>)" << std::endl; std::cerr << " <min>:<max>,<from-colour>:<to-colour>: if scalar field present, stretch by scalar (see section <fields>)" << std::endl; std::cerr << " <min>:<max>,<colourmap>: if scalar field present, stretch by scalar (see section <fields>)" << std::endl; std::cerr << " <colourmap>: jet, hot, red, green" << std::endl; std::cerr << std::endl; std::cerr << " fixed colour" << std::endl; std::cerr << " white, black, red, green, blue, yellow, cyan, magenta, grey, pink, sky, salad: fixed colour" << std::endl; std::cerr << std::endl; std::cerr << " colour by id" << std::endl; std::cerr << " if there is \"id\" field in --fields, colour by id, with or without scalar (see section <fields>)" << std::endl; std::cerr << std::endl; std::cerr << " colour by elevation" << std::endl; std::cerr << " [<min>:<max>][,<from-colour>:<to-colour>][,cyclic][,sharp][,quadratic] (in any order)" << std::endl; std::cerr << " stretch colours by elevation" << std::endl; std::cerr << " <min>:<max>: from-to in metres, e.g. -3:10" << std::endl; std::cerr << " <from-colour>:<to-colour>: from which to which colour" << std::endl; std::cerr << " cyclic: if present, colour cyclically with <min> and <max>" << std::endl; std::cerr << " meaning the height of the corresponding stip" << std::endl; std::cerr << " sharp: if present (for cyclic only), do not make smooth borders" << std::endl; std::cerr << " between the colours" << std::endl; std::cerr << " quadratic: if present (for cyclic only), parabolic stretching, quick and dirty" << std::endl; std::cerr << " default: stretch colours linearly" << std::endl; std::cerr << " e.g.: cat data.csv | view-points --colour=blue:yellow,1:2,cyclic" << std::endl; std::cerr << std::endl; std::cerr << " default: stretched by elevation from cyan to magenta from 0:1" << std::endl; std::cerr << std::endl; std::cerr << " hide: e.g. \"test.csv;hide\": hide the source, when shown first time (useful, when there are very many inputs" << std::endl; std::cerr << " --label <label>: text label displayed next to the latest point" << std::endl; std::cerr << " --no-stdin: do not read from stdin" << std::endl; std::cerr << " --point-size,--weight <point size>: default: 1" << std::endl; std::cerr << " --shape <shape>: \"point\", \"extents\", \"line\", \"label\"; default \"point\"" << std::endl; std::cerr << " \"arc\": e.g: --shape=arc --fields=,,begin,end,centre," << std::endl; std::cerr << " or: --shape=arc --fields=,,begin,middle,end,,," << std::endl; std::cerr << " where 'begin' and 'end' are x,y,z points" << std::endl; std::cerr << " and 'middle' is a point between begin and end on the arc" << std::endl; std::cerr << " default: 'begin,end', with centre 0,0,0" << std::endl; std::cerr << " \"ellipse\": e.g. --shape=ellipse --fields=,,center,orientation,minor,major," << std::endl; std::cerr << " orientation: roll,pitch,yaw; default: in x,y plane" << std::endl; std::cerr << " \"extents\": e.g. --shape=extents --fields=,,min,max,,," << std::endl; std::cerr << " \"line\": e.g. --shape=line --fields=,,first,second,,," << std::endl; std::cerr << " \"lines\": connect all points of a block from first to the last; fields same as for 'point'" << std::endl; std::cerr << " \"loop\": connect all points of a block; fields same as for 'point'" << std::endl; std::cerr << " \"label\": e.g. --shape=label --fields=,x,y,z,,,label" << std::endl; std::cerr << " \"<model file ( obj, ply... )>[;<options>]\": e.g. --shape=vehicle.obj" << std::endl; std::cerr << " \" <options>" << std::endl; std::cerr << " \" flip\": flip the model around the x-axis" << std::endl; std::cerr << " \" scale=<value>\": resize model (ply only, todo), e.g. show model half-size: scale=0.5" << std::endl; std::cerr << " \"<image file>[,<image options>]:<image file>[,<image options>]\": show image, e.g. --shape=\"vehicle-lights-on.jpg,vehicle-lights-off.jpg\"" << std::endl; std::cerr << " <image options>: <width>,<height> or <pixel-size>" << std::endl; std::cerr << " <width>,<height>: image width and height in meters when displaying images in the scene; default: 1,1" << std::endl; std::cerr << " <pixel size>: single pixel size in metres" << std::endl; std::cerr << " note 1: just like for the cad models, the images will be pinned to the latest point in the stream" << std::endl; std::cerr << " note 2: specify id in fields to switch between multiple images, see examples below" << std::endl; std::cerr << " --size <size> : render last <size> points (or other shapes)" << std::endl; std::cerr << " default 2000000 for points, for 200000 for other shapes" << std::endl; std::cerr << std::endl; std::cerr << "camera options" << std::endl; std::cerr << " --camera=\"<options>\"" << std::endl; std::cerr << " <options>: [<fov>];[<type>]" << std::endl; std::cerr << " <fov>: field of view in degrees, default 45 degrees" << std::endl; std::cerr << " <type>: orthographic | perspective" << std::endl; std::cerr << " default: perspective" << std::endl; std::cerr << " --fov=<fov>: set camera field of view in degrees" << std::endl; std::cerr << " --camera-config=<filename>: camera config in json; to see an example, run --output-camera-config" << std::endl; std::cerr << " --camera-position=\"<options>\"" << std::endl; std::cerr << " <options>: <position>|<stream>" << std::endl; std::cerr << " <position>: <x>,<y>,<z>,<roll>,<pitch>,<yaw>" << std::endl; std::cerr << " <stream>: position csv stream with options; default fields: x,y,z,roll,pitch,yaw" << std::endl; std::cerr << " --orthographic: use orthographic projection instead of perspective" << std::endl; std::cerr << std::endl; std::cerr << "more options" << std::endl; std::cerr << " --background-colour <colour> : default: black" << std::endl; std::cerr << " --output-camera-config,--output-camera: output camera position as t,x,y,z,r,p,y to stdout" << std::endl; std::cerr << " --scene-center,--center=<value>: fixed scene center as \"x,y,z\"" << std::endl; std::cerr << " --scene-radius,--radius=<value>: fixed scene radius in metres, since sometimes it is hard to imply" << std::endl; std::cerr << " scene size from the dataset (e.g. for streams)" << std::endl; std::cerr << " --z-is-up : z-axis is pointing up, default: pointing down ( north-east-down system )" << std::endl; std::cerr << std::endl; std::cerr << "csv options" << std::endl; std::cerr << comma::csv::options::usage() << std::endl; std::cerr << std::endl; std::cerr << " fields:" << std::endl; std::cerr << " default: x,y,z" << std::endl; std::cerr << " x,y,z: coordinates (%d in binary)" << std::endl; std::cerr << " id: if present, colour by id (%ui in binary)" << std::endl; std::cerr << " block: if present, clear screen once block id changes (%ui in binary)" << std::endl; std::cerr << " r,g,b: if present, specify RGB colour (0-255; %uc in binary)" << std::endl; std::cerr << " a: if present, specifies colour transparency (0-255, %uc in binary); default 255" << std::endl; std::cerr << " scalar: if present, colour by scalar" << std::endl; std::cerr << " use --colour=<from>:<to>[,<from colour>:<to colour>]" << std::endl; std::cerr << " default: 0:1,red:blue" << std::endl; std::cerr << " todo: implement for shapes (currently works only for points)" << std::endl; std::cerr << " label: text label (currenly implemented for ascii only)" << std::endl; std::cerr << " roll,pitch,yaw: if present, show orientation" << std::endl; std::cerr << std::endl; std::cerr << " most of the options can be set for individual files (see examples)" << std::endl; std::cerr << std::endl; std::cerr << "mouse clicks:" << std::endl; std::cerr << " left press and hold: rotate the scene around the centre" << std::endl; std::cerr << " right press and hold: translate the scene" << std::endl; std::cerr << " double left click: change the centre of the scene" << std::endl; std::cerr << " double right click: output to stdout approximate coordinates of the clicked point" << std::endl; std::cerr << std::endl; std::cerr << "examples" << std::endl; std::cerr << std::endl; std::cerr << "basics" << std::endl; std::cerr << " view points from file:" << std::endl; std::cerr << " view-points xyz.csv" << std::endl; std::cerr << std::endl; std::cerr << " hint that the file contains not more than 200000 points" << std::endl; std::cerr << " cat $(ls *.csv) | view-points --size=200000" << std::endl; std::cerr << std::endl; std::cerr << " view points from all the binary files in the directory" << std::endl; std::cerr << " cat $(ls *.bin) | view-points --size=200000 --binary \"%d%d%d\"" << std::endl; std::cerr << std::endl; std::cerr << " colour points" << std::endl; std::cerr << " view-points --colour blue $(ls labeled.*.csv)" << std::endl; std::cerr << std::endl; std::cerr << " each point has an individual color:" << std::endl; std::cerr << " cat xyzrgb.csv | view-points --fields=\"x,y,z,r,g,b\"" << std::endl; std::cerr << std::endl; std::cerr << " view multiple files" << std::endl; std::cerr << " view-points \"raw.csv;colour=0:20\" \"partitioned.csv;fields=x,y,z,id\";point-size=2" << std::endl; std::cerr << std::endl; std::cerr << " view a cad model" << std::endl; std::cerr << " echo \"0,0,0\" | view-points --shape /usr/local/etc/segway.shrimp.obj --z-is-up --orthographic" << std::endl; std::cerr << std::endl; std::cerr << " use stdin as the primary source for scene radius:" << std::endl; std::cerr << " cat xyz.csv | view-points \"-\" scan.csv" << std::endl; std::cerr << std::endl; std::cerr << " specify fixed scene radius explicitly:" << std::endl; std::cerr << " cat xyz.csv | view-points --scene-radius=100" << std::endl; std::cerr << std::endl; std::cerr << "using images" << std::endl; std::cerr << " show image with given position" << std::endl; std::cerr << " echo 0,0,0 | view-points \"-;shape=image.jpg\"" << std::endl; std::cerr << std::endl; std::cerr << " show resized image" << std::endl; std::cerr << " echo 0,0,0 | view-points \"-;shape=image.jpg,3,4\"" << std::endl; std::cerr << std::endl; std::cerr << " specify pixel size instead of image size" << std::endl; std::cerr << " echo 0,0,0 | view-points \"-;shape=image.jpg,0.1\"" << std::endl; std::cerr << std::endl; std::cerr << " show image with given position and orientation" << std::endl; std::cerr << " echo 0,0,0,0,0,0 | view-points \"-;shape=image.jpg;fields=x,y,z,roll,pitch,yaw\"" << std::endl; std::cerr << std::endl; std::cerr << " switch between images by their index" << std::endl; std::cerr << " echo 0,0,0,0 > points.csv" << std::endl; std::cerr << " echo 0,0,0,1 >> points.csv" << std::endl; std::cerr << " echo 0,0,0,2 >> points.csv" << std::endl; std::cerr << " echo points.csv | view-points \"-;shape=image1.jpg,image2.jpg,image3.jpg;fields=x,y,z,id\"" << std::endl; std::cerr << std::endl; std::cerr << " show points selected with a double right click" << std::endl; std::cerr << " rm -rf pipe && mkfifo pipe && cat pipe | view-points \"rose.st.ground.csv;fields=x,y,z,r,g,b\" \"-;colour=sky;weight=10\" > pipe" << std::endl; std::cerr << std::endl; std::cerr << " publish a real time playback of georeferenced velodyne data on port 12345, visualise the data in real time and show points selected with a double right click" << std::endl; std::cerr << " cat velodyne-georeferenced.bin | csv-play --binary t,3d,ui | io-publish --size $( csv-size t,3d,ui ) -m 10000 tcp:12345" << std::endl; std::cerr << " rm -rf pipe && mkfifo pipe && cat pipe | view-points \"tcp:localhost:12345;binary=t,3d,ui;fields=,x,y,z,block\" \"-;fields=x,y,z;colour=sky;weight=10\" > pipe" << std::endl; std::cerr << std::endl; std::cerr << " similar to above but uses different colours for the shown points and adds labels next to the points indicating the click order " << std::endl; std::cerr << " cat velodyne-georeferenced.bin | csv-play --binary t,3d,ui | io-publish --size $( csv-size t,3d,ui ) -m 10000 tcp:12345" << std::endl; std::cerr << " rm -rf pipe && mkfifo pipe && cat pipe | view-points \"tcp:localhost:12345;binary=t,3d,ui;fields=,x,y,z,block\" \"-;fields=x,y,z,id,label;weight=10\" | csv-paste \"-\" line-number line-number > pipe" << std::endl; std::cerr << std::endl; exit( -1 ); } struct model_options { std::string filename; bool flip; double scale; model_options() : flip( false ), scale( 1.0 ) {} }; namespace comma { namespace visiting { template <> struct traits< model_options > { template < typename Key, class Visitor > static void visit( Key, model_options& p, Visitor& v ) { v.apply( "filename", p.filename ); v.apply( "flip", p.flip ); v.apply( "scale", p.scale ); } template < typename Key, class Visitor > static void visit( Key, const model_options& p, Visitor& v ) { v.apply( "filename", p.filename ); v.apply( "flip", p.flip ); v.apply( "scale", p.scale ); } }; } } // namespace comma { namespace visiting { // quick and dirty, todo: a proper structure, as well as a visitor for command line options boost::shared_ptr< snark::graphics::View::Reader > makeReader( QGLView& viewer , const comma::command_line_options& options , const comma::csv::options& csvOptions , const std::string& properties = "" ) { QColor4ub backgroundcolour( QColor( QString( options.value< std::string >( "--background-colour", "#000000" ).c_str() ) ) ); comma::csv::options csv = csvOptions; std::string shape = options.value< std::string >( "--shape", "point" ); std::size_t size = options.value< std::size_t >( "--size", shape == "point" ? 2000000 : 200000 ); unsigned int pointSize = options.value( "--point-size,--weight", 1u ); std::string colour = options.exists( "--colour" ) ? options.value< std::string >( "--colour" ) : options.value< std::string >( "-c", "-10:10" ); std::string label = options.value< std::string >( "--label", "" ); bool show = true; if( properties != "" ) { comma::name_value::parser nameValue( "filename", ';', '=', false ); csv = nameValue.get( properties, csvOptions ); comma::name_value::map m( properties, "filename", ';', '=' ); size = m.value( "size", size ); pointSize = m.value( "point-size", pointSize ); pointSize = m.value( "weight", pointSize ); shape = m.value( "shape", shape ); if( m.exists( "colour" ) ) { colour = m.value( "colour", colour ); } else if( m.exists( "color" ) ) { colour = m.value( "color", colour ); } label = m.value( "label", label ); show = !m.exists( "hide" ); } if( !show ) { std::cerr << "view-points: " << csv.filename << " will be hidden on startup; tick the box next to filename to make it visible" << std::endl; } snark::graphics::View::coloured* coloured = snark::graphics::View::colourFromString( colour, csv.fields, backgroundcolour ); if( shape == "point" ) { if( csv.fields == "" ) { csv.fields="x,y,z"; } std::vector< std::string > v = comma::split( csv.fields, ',' ); bool has_orientation = false; for( unsigned int i = 0; !has_orientation && i < v.size(); ++i ) { has_orientation = v[i] == "roll" || v[i] == "pitch" || v[i] == "yaw"; } boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< Eigen::Vector3d >( viewer, csv, size, coloured, pointSize, label ) ); reader->show( show ); return reader; } if( shape == "loop" ) { if( csv.fields == "" ) { csv.fields="x,y,z"; } boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< Eigen::Vector3d, snark::graphics::View::how_t::loop >( viewer, csv, size, coloured, pointSize, label ) ); reader->show( show ); return reader; } if( shape == "lines" ) // todo: get a better name { if( csv.fields == "" ) { csv.fields="x,y,z"; } boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< Eigen::Vector3d, snark::graphics::View::how_t::connected >( viewer, csv, size, coloured, pointSize, label ) ); reader->show( show ); return reader; } if( shape == "label" ) { if( csv.fields == "" ) { csv.fields="x,y,z,label"; } // TODO } else if( shape == "ellipse" ) { if( csv.fields == "" ) { csv.fields="center,orientation,major,minor"; } std::vector< std::string > v = comma::split( csv.fields, ',' ); for( std::size_t i = 0; i < v.size(); ++i ) { if( v[i] == "x" || v[i] == "y" || v[i] == "z" ) { v[i] = "center/" + v[i]; } else if( v[i] == "roll" || v[i] == "pitch" || v[i] == "yaw" ) { v[i] = "orientation/" + v[i]; } } csv.fields = comma::join( v, ',' ); } else if( shape == "arc" ) { if( csv.fields == "" ) { csv.fields="begin,end"; } std::vector< std::string > v = comma::split( csv.fields, ',' ); } else if( shape == "extents" ) { if( csv.fields == "" ) { csv.fields="min,max"; } } else if( shape == "line" ) { if( csv.fields == "" ) { csv.fields="first,second"; } } else { if( csv.fields == "" ) { csv.fields="point,orientation"; csv.full_xpath = true; } std::vector< snark::graphics::View::TextureReader::image_options > image_options; std::vector< std::string > v = comma::split( shape, ':' ); for( unsigned int i = 0; i < v.size(); ++i ) { std::vector< std::string > w = comma::split( v[i], ',' ); std::string e = comma::split( w[0], '.' ).back(); if( e != "png" && e != "jpg" && e != "jpeg" && e != "bmp" && e != "gif" ) { break; } switch( w.size() ) { case 1: image_options.push_back( snark::graphics::View::TextureReader::image_options( w[0] ) ); break; case 2: image_options.push_back( snark::graphics::View::TextureReader::image_options( w[0], boost::lexical_cast< double >( w[1] ) ) ); break; case 3: image_options.push_back( snark::graphics::View::TextureReader::image_options( w[0], boost::lexical_cast< double >( w[1] ), boost::lexical_cast< double >( w[2] ) ) ); break; default: COMMA_THROW( comma::exception, "expected <image>[,<width>,<height>]; got: " << shape ); } } if( image_options.empty() ) { model_options m = comma::name_value::parser( ';', '=' ).get< model_options >( properties ); m.filename = shape; if( !boost::filesystem::exists( m.filename ) ) { COMMA_THROW( comma::exception, "file does not exist: " << m.filename ); } boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ModelReader( viewer, csv, shape, m.flip, m.scale, coloured, label ) ); reader->show( show ); return reader; } else { boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::TextureReader( viewer, csv, image_options ) ); reader->show( show ); return reader; } } std::vector< std::string > v = comma::split( csv.fields, ',' ); for( std::size_t i = 0; i < v.size(); ++i ) { if( v[i] != "id" && v[i] != "block" && v[i] != "colour" && v[i] != "label" && v[i] != "scalar" && v[i] != "r" && v[i] != "g" && v[i] != "b" && v[i] != "a" && v[i] != "" ) { v[i] = "shape/" + v[i]; } if( v[i] == "r" || v[i] == "g" || v[i] == "b" || v[i] == "a" ) { v[i] = "colour/" + v[i]; } } csv.fields = comma::join( v, ',' ); csv.full_xpath = true; if( shape == "extents" ) { boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< snark::math::closed_interval< double, 3 > >( viewer, csv, size, coloured, pointSize, label, snark::math::closed_interval< double, 3 >( Eigen::Vector3d( 0, 0, 0 ), Eigen::Vector3d( 0, 0, 0 ) ) ) ); reader->show( show ); return reader; } else if( shape == "line" ) { boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< std::pair< Eigen::Vector3d, Eigen::Vector3d > >( viewer, csv, size, coloured, pointSize, label ) ); reader->show( show ); return reader; } else if( shape == "ellipse" ) { boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< snark::graphics::View::Ellipse< 25 > >( viewer, csv, size, coloured, pointSize, label ) ); reader->show( show ); return reader; } else if( shape == "arc" ) { snark::graphics::View::arc< 20 > sample; // quick and dirty if( csv.has_field( "middle" ) || csv.has_field( "middle/x" ) || csv.has_field( "middle/y" ) || csv.has_field( "middle/z" ) ) { sample.middle = Eigen::Vector3d(); } boost::shared_ptr< snark::graphics::View::Reader > reader( new snark::graphics::View::ShapeReader< snark::graphics::View::arc< 20 > >( viewer, csv, size, coloured, pointSize, label, sample ) ); reader->show( show ); return reader; } COMMA_THROW( comma::exception, "expected shape, got \"" << shape << "\"" ); // never here } int main( int argc, char** argv ) { try { comma::command_line_options options( argc, argv ); if( options.exists( "--help" ) || options.exists( "-h" ) ) { usage(); } comma::csv::options csvOptions( argc, argv ); std::vector< std::string > properties = options.unnamed( "--z-is-up,--orthographic,--flush,--no-stdin,--output-camera-config,--output-camera" , "--binary,--bin,-b,--fields,--size,--delimiter,-d,--colour,-c,--point-size,--weight,--background-colour,--scene-center,--center,--scene-radius,--radius,--shape,--label,--camera,--camera-position,--camera-config,--fov,--model,--full-xpath" ); QColor4ub backgroundcolour( QColor( QString( options.value< std::string >( "--background-colour", "#000000" ).c_str() ) ) ); boost::optional< comma::csv::options > camera_csv; boost::optional< Eigen::Vector3d > cameraposition; boost::optional< Eigen::Vector3d > cameraorientation; bool camera_orthographic = options.exists( "--orthographic" ); double fieldOfView = options.value< double >( "--fov" , 45 ); if( options.exists( "--camera" ) ) { std::string camera = options.value< std::string >( "--camera" ); std::vector< std::string > v = comma::split( camera, ';' ); for( std::size_t i = 0; i < v.size(); ++i ) { if( v[i] == "orthographic" ) { camera_orthographic = true; } else if( v[i] == "perspective" ) { camera_orthographic = false; } else { std::vector< std::string > vec = comma::split( v[i], '=' ); if( vec.size() == 2 && vec[0] == "fov" ) { fieldOfView = boost::lexical_cast< double >( vec[1] ); } } } } QApplication application( argc, argv ); bool z_up = options.exists( "--z-is-up" ); if( options.exists( "--camera-position" ) ) { std::string position = options.value< std::string >( "--camera-position" ); comma::name_value::parser parser( "x,y,z,roll,pitch,yaw", ',', '=', false ); snark::graphics::View::point_with_orientation pose; try { pose = parser.get< snark::graphics::View::point_with_orientation >( position ); cameraposition = pose.point; cameraorientation = pose.orientation; } catch( ... ) {} if( !cameraposition ) { comma::name_value::parser parser( "filename", ';', '=', false ); try { std::cerr << " parse " << position << std::endl; camera_csv = parser.get< comma::csv::options >( position ); camera_csv->full_xpath = false; if( camera_csv->fields.empty() ) { camera_csv->fields = "x,y,z,roll,pitch,yaw"; } } catch( ... ) {} } } boost::optional< double > scene_radius = options.optional< double >( "--scene-radius,--radius" ); boost::optional< Eigen::Vector3d > scene_center; boost::optional< std::string > s = options.optional< std::string >( "--scene-center,--center" ); if( s ) { scene_center = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( *s ); } boost::property_tree::ptree camera_config; // quick and dirty if( options.exists( "--camera-config" ) ) { boost::property_tree::read_json( options.value< std::string >( "--camera-config" ), camera_config ); } snark::graphics::View::Viewer* viewer = new snark::graphics::View::Viewer( backgroundcolour , fieldOfView , z_up , camera_orthographic , camera_csv , cameraposition , cameraorientation , options.exists( "--camera-config" ) ? &camera_config : NULL , scene_center , scene_radius , options.exists( "--output-camera-config,--output-camera" ) ); bool stdinAdded = false; for( unsigned int i = 0; i < properties.size(); ++i ) { if( comma::split( properties[i], ';' )[0] == "-" ) { stdinAdded = true; } viewer->readers.push_back( makeReader( *viewer, options, csvOptions, properties[i] ) ); } if( !stdinAdded && !options.exists( "--no-stdin" ) ) { csvOptions.filename = "-"; viewer->readers.push_back( makeReader( *viewer, options, csvOptions ) ); } snark::graphics::View::MainWindow mainWindow( comma::join( argv, argc, ' ' ), viewer ); mainWindow.show(); /*return*/ application.exec(); delete viewer; } catch( std::exception& ex ) { std::cerr << "view-points: " << ex.what() << std::endl; } catch( ... ) { std::cerr << "view-points: unknown exception" << std::endl; } }
63.074906
304
0.531946
[ "cad", "render", "shape", "vector", "model", "3d" ]
7888b7a36b859061e9f1927942e5228a416e8409
40,958
cpp
C++
test/gpu/lif_unit_test.cpp
denniskb/bsim
bfe02148fc2fee7efff68b16173c626c515a49bb
[ "MIT" ]
null
null
null
test/gpu/lif_unit_test.cpp
denniskb/bsim
bfe02148fc2fee7efff68b16173c626c515a49bb
[ "MIT" ]
null
null
null
test/gpu/lif_unit_test.cpp
denniskb/bsim
bfe02148fc2fee7efff68b16173c626c515a49bb
[ "MIT" ]
null
null
null
/* Copyright Kristjan Kongas 2020 Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // See https://github.com/kongaskristjan/fire-hpp for library's documentation and updates #ifndef FIRE_HPP_ #define FIRE_HPP_ #include <algorithm> #include <cassert> #include <cstddef> #include <cstdlib> #include <iostream> #include <limits> #include <map> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> namespace fire { constexpr int _failure_code = 1; template <typename R, typename... Types> constexpr size_t _get_argument_count( R ( * )( Types... ) ) { return sizeof...( Types ); } inline void _instant_assert( bool pass, const std::string & msg, bool programmer_side = true ); inline int count_hyphens( const std::string & s ); inline std::string without_hyphens( const std::string & s ); template <typename T> class optional { T _value = T(); bool _exists = false; public: optional() = default; optional( T value ) : _value( std::move( value ) ) , _exists( true ) { } optional<T> & operator=( const T & value ) { _value = value; _exists = true; return *this; } bool operator==( const optional<T> & other ) { return _exists == other._exists && _value == other._value; } explicit operator bool() const { return _exists; } bool has_value() const { return _exists; } T value_or( const T & def ) const { return _exists ? _value : def; } T value() const { _instant_assert( _exists, "accessing unassigned optional" ); return _value; } }; struct _escape_exception { }; class identifier { optional<int> _pos; optional<std::string> _short_name, _long_name, _pos_name, _descr; bool _variadic = false; bool _optional = false; // Only use for operator< std::string _help, _longer; inline static void _check_name( const std::string & name ); public: inline static std::string prepend_hyphens( const std::string & name ); inline identifier( optional<std::string> descr = optional<std::string>() ); inline identifier( const std::vector<std::string> & names, optional<int> pos, bool is_variadic = false ); inline optional<std::string> short_name() const { return _short_name; } inline optional<std::string> long_name() const { return _long_name; } inline bool operator<( const identifier & other ) const; inline bool overlaps( const identifier & other ) const; inline bool contains( const std::string & name ) const; inline bool contains( int pos ) const; inline std::string help() const { return _help; } inline std::string longer() const { return _longer; } inline optional<int> get_pos() const { return _pos; } inline void set_optional( bool optional ) { _optional = optional; } inline bool variadic() const { return _variadic; } inline std::string get_descr() const { return _descr.value_or( "" ); } }; template <typename ORDER, typename VALUE> class _first { ORDER _order; VALUE _value; bool _empty = true; public: void set( const ORDER & order, const VALUE & value ); const VALUE & get() const; bool empty() const { return _empty; } }; class _matcher { std::string _executable; std::vector<std::string> _positional; std::vector<std::pair<std::string, optional<std::string>>> _named; std::vector<identifier> _queried; _first<identifier, std::string> _deferred_error; int _main_args = 0; bool _introspect = false; bool _strict = false; bool _help_flag = false; public: enum class arg_type { string_t, bool_t, none_t }; inline _matcher() = default; inline _matcher( int argc, const char ** argv, int main_args, bool strict ); inline void check( bool dec_main_args ); inline void check_named(); inline void check_positional(); inline std::pair<std::string, arg_type> get_and_mark_as_queried( const identifier & id ); inline void parse( int argc, const char ** argv ); inline std::vector<std::string> to_vector_string( int n_strings, const char ** strings ); inline std::vector<std::string> equate_assignments( const std::vector<std::string> & raw, const std::vector<std::string> & assigned ); inline std::tuple<std::vector<std::string>, std::vector<std::string>> separate_named_positional( const std::vector<std::string> & eqs ); inline std::vector<std::string> expand_single_hyphen( const std::vector<std::string> & named ); inline std::vector<std::pair<std::string, optional<std::string>>> assign_named_values( const std::vector<std::string> & split ); inline const std::string & get_executable() { return _executable; } inline size_t pos_args() { return _positional.size(); } inline bool deferred_assert( const identifier & id, bool pass, const std::string & msg ); inline void set_introspect( bool introspect ) { _introspect = introspect; } inline bool get_introspect() const { return _introspect; } }; class _arg_logger { // Gathers function argument help info here public: struct elem { enum class type { none, string, integer, real }; std::string descr; type t; std::string def; bool optional; }; private: std::vector<std::pair<identifier, elem>> _params; int _introspect_count = 0; inline std::string _make_printable( const identifier & id, const elem & elem, bool verbose ); inline void _add_to_help( std::string & usage, std::string & options, const identifier & id, const elem & elem, size_t margin ); public: inline void print_help(); inline std::vector<std::string> get_assignment_arguments() const; inline void log( const identifier & name, const elem & elem ); inline void set_introspect_count( int count ); inline int decrease_introspect_count(); inline int get_introspect_count() const { return _introspect_count; } }; template <typename T_VOID = void> struct _storage { static _matcher matcher; static _arg_logger logger; }; template <typename T_VOID> _matcher _storage<T_VOID>::matcher; template <typename T_VOID> _arg_logger _storage<T_VOID>::logger; using _ = _storage<void>; struct variadic { }; class arg { identifier _id; // No identifier implies vector positional arguments optional<long long> _int_value; optional<long double> _float_value; optional<std::string> _string_value; template <typename T> optional<T> _get() { T::unimplemented_function; } // no default function template < typename T, typename std::enable_if< std::is_integral<T>::value && !std::is_same<T, bool>::value>::type * = nullptr> optional<T> _get_with_precision(); template < typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr> optional<T> _get_with_precision(); template < typename T, typename std::enable_if< std::is_same<T, bool>::value || std::is_same<T, std::string>::value, bool>::type * = nullptr> optional<T> _get_with_precision() { return _get<T>(); } template <typename T> optional<T> _convert_optional( bool dec_main_args = true ); template <typename T> T _convert( bool dec_main_args = true ); inline void _log( _arg_logger::elem::type t, bool optional ); template <typename T, typename std::enable_if<std::is_integral<T>::value>::type * = nullptr> inline void init_default( T value ) { _int_value = value; } template < typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr> inline void init_default( T value ) { _float_value = value; } inline void init_default( const std::string & value ) { _string_value = value; } inline void init_default( std::nullptr_t ) {} inline arg() = default; struct convertible { optional<int> _int_value; optional<const char *> _char_value; bool is_variadic = false; convertible( int value ) : _int_value( value ) { } convertible( const char * value ) : _char_value( value ) { } convertible( variadic ) : is_variadic( true ) { } }; public: template <typename T = std::nullptr_t> inline arg( std::initializer_list<convertible> init, T value = T() ) { optional<int> int_value; std::vector<std::string> string_values; bool is_variadic = false; for( const convertible & val : init ) { if( val.is_variadic ) is_variadic = true; else if( val._int_value.has_value() ) int_value = val._int_value.value(); else string_values.push_back( val._char_value.value() ); } _id = identifier( string_values, int_value, is_variadic ); init_default( value ); } template <typename T = std::nullptr_t> inline arg( convertible _id, T value = T() ) : arg( { _id }, value ) { } template <typename T, typename std::enable_if<std::is_integral<T>::value>::type * = nullptr> inline operator optional<T>() { _log( _arg_logger::elem::type::integer, true ); return _convert_optional<T>(); } template < typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr> inline operator optional<T>() { _log( _arg_logger::elem::type::real, true ); return _convert_optional<T>(); } inline operator optional<std::string>() { _log( _arg_logger::elem::type::string, true ); return _convert_optional<std::string>(); } template <typename T, typename std::enable_if<std::is_integral<T>::value>::type * = nullptr> inline operator T() { _log( _arg_logger::elem::type::integer, false ); return _convert<T>(); } template < typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr> inline operator T() { _log( _arg_logger::elem::type::real, false ); return _convert<T>(); } inline operator std::string() { _log( _arg_logger::elem::type::string, false ); return _convert<std::string>(); } inline operator bool(); template <typename T> inline operator std::vector<T>(); }; void _instant_assert( bool pass, const std::string & msg, bool programmer_side ) { if( pass ) return; if( !msg.empty() ) { std::cerr << "Error"; if( programmer_side ) std::cerr << " (programmer side)"; std::cerr << ": " << msg << std::endl; } exit( _failure_code ); } int count_hyphens( const std::string & s ) { int hyphens; for( hyphens = 0; hyphens < (int)s.size() && s[hyphens] == '-'; ++hyphens ) ; return hyphens; } std::string without_hyphens( const std::string & s ) { int hyphens = count_hyphens( s ); std::string wo_hyphens = s.substr( hyphens ); return wo_hyphens; } std::string identifier::prepend_hyphens( const std::string & name ) { if( name.size() == 1 ) return "-" + name; if( name.size() >= 2 ) return "--" + name; return name; } void identifier::_check_name( const std::string & name ) { _instant_assert( count_hyphens( name ) == 0, "argument " + name + " has hyphens prefixed in declaration" ); _instant_assert( name.size() >= 1, "name must contain at least one character" ); _instant_assert( name.size() >= 2 || !isdigit( name[0] ), "single character name must not be a digit (" + name + ")" ); } inline identifier::identifier( optional<std::string> descr ) : _descr( descr ) , _variadic( true ) , _help( "..." ) , _longer( "..." ) { } inline identifier::identifier( const std::vector<std::string> & names, optional<int> pos, bool is_variadic ) { // Find description, shorthand and long name for( const std::string & name : names ) { if( name.size() >= 2 && name.front() == '<' && name.back() == '>' ) { _pos_name = name; continue; } int hyphens = count_hyphens( name ); _instant_assert( hyphens <= 2, "Identifier entry " + name + " must prefix either:" " 0 hyphens for description," " 1 hyphen for short-hand name" " 2 hyphens for long name" ); if( hyphens == 0 ) { _instant_assert( !_descr.has_value(), "Can't specify descriptions twice: " + _descr.value_or( "" ) + " and " + name ); _descr = name; } else if( hyphens == 1 ) { _instant_assert( !_short_name.has_value(), "Can't specify shorthands twice: " + _short_name.value_or( "" ) + " and " + name ); _instant_assert( name.size() == 2, "Single hyphen shorthand " + name + " must be one character" ); _instant_assert( !isdigit( name[1] ), "Argument " + name + " can't start with a number" ); _short_name = name; } else if( hyphens == 2 ) { _instant_assert( !_long_name.has_value(), "Can't specify long names twice: " + _long_name.value_or( "" ) + " and " + name ); _instant_assert( name.size() >= 4, "Two hyphen name " + name + " must have at least two characters" ); _long_name = name; } } // Variadic argument if( is_variadic ) { _instant_assert( !_short_name.has_value() && !_long_name.has_value() && !_pos.has_value() && !_pos_name.has_value(), "Can't assign a name or position to variadic arguments" ); return; } // Set help and longer variant if( _long_name.has_value() && _short_name.has_value() ) { _help = _short_name.value() + "|" + _long_name.value(); _longer = _long_name.value(); } else if( _long_name.has_value() && !_short_name.has_value() ) _help = _longer = _long_name.value(); else if( !_long_name.has_value() && _short_name.has_value() ) _help = _longer = _short_name.value(); // Set position if( pos.has_value() ) { _instant_assert( !_short_name.has_value(), "Can't specify both name " + _short_name.value_or( "" ) + " and index " + std::to_string( pos.value() ) ); _instant_assert( !_long_name.has_value(), "Can't specify both name " + _long_name.value_or( "" ) + " and index " + std::to_string( pos.value() ) ); _pos = pos; if( _pos_name.has_value() ) _longer = _help = _pos_name.value(); else _longer = _help = "<" + std::to_string( pos.value() ) + ">"; } _instant_assert( _short_name.has_value() || _long_name.has_value() || _pos.has_value(), "Argument must be specified with at least on of the following: shorthand, long name or " "index" ); if( _pos_name.has_value() ) _instant_assert( _pos.has_value(), "Positional name " + _pos_name.value_or( "" ) + " requires the argument to be positional" ); } bool identifier::operator<( const identifier & other ) const { std::string name = _long_name.value_or( _short_name.value_or( "" ) ); std::string other_name = other._long_name.value_or( other._short_name.value_or( "" ) ); name = without_hyphens( name ); other_name = without_hyphens( other_name ); std::transform( name.begin(), name.end(), name.begin(), []( char c ) { return (char)tolower( c ); } ); std::transform( other_name.begin(), other_name.end(), other_name.begin(), []( char c ) { return (char)tolower( c ); } ); if( name != other_name ) { if( !name.empty() && !other_name.empty() && _optional != other._optional ) return _optional < other._optional; return name < other_name; } return _pos.value_or( 1000000 ) < other._pos.value_or( 1000000 ); } bool identifier::overlaps( const identifier & other ) const { if( _long_name.has_value() && other._long_name.has_value() ) if( _long_name.value() == other._long_name.value() ) return true; if( _short_name.has_value() && other._short_name.has_value() ) if( _short_name.value() == other._short_name.value() ) return true; if( _pos.has_value() && other._pos.has_value() ) if( _pos.value() == other._pos.value() ) return true; return false; } bool identifier::contains( const std::string & name ) const { if( _short_name.has_value() && name == _short_name.value() ) return true; if( _long_name.has_value() && name == _long_name.value() ) return true; return false; } bool identifier::contains( int pos ) const { return _pos.has_value() && pos == _pos.value(); } template <typename ORDER, typename VALUE> void _first<ORDER, VALUE>::set( const ORDER & order, const VALUE & value ) { if( _empty || order < _order ) { _order = order; _value = value; _empty = false; } } template <typename ORDER, typename VALUE> const VALUE & _first<ORDER, VALUE>::get() const { return _value; } _matcher::_matcher( int argc, const char ** argv, int main_args, bool strict ) { _main_args = main_args; _strict = strict; parse( argc, argv ); identifier help( { "-h", "--help", "Print the help message" }, optional<int>() ); _help_flag = get_and_mark_as_queried( help ).second != arg_type::none_t; check( false ); } void _matcher::check( bool dec_main_args ) { _main_args -= dec_main_args; if( !_strict || _main_args > 0 ) return; if( _help_flag ) { _::logger.print_help(); exit( 0 ); } check_named(); check_positional(); if( !_deferred_error.empty() ) { std::cerr << "Error: " << _deferred_error.get() << std::endl; exit( _failure_code ); } } void _matcher::check_named() { int invalid_count = 0; std::string invalid; for( const auto & it : _named ) { for( const auto & jt : _queried ) if( jt.contains( it.first ) ) goto VALID; ++invalid_count; invalid += " " + it.first; VALID:; } deferred_assert( identifier(), invalid.empty(), std::string( "invalid argument" ) + ( invalid_count > 1 ? "s" : "" ) + invalid ); } void _matcher::check_positional() { int invalid_count = 0; std::string invalid; for( size_t i = 0; i < _positional.size(); ++i ) { for( const auto & it : _queried ) if( it.contains( (int)i ) ) goto VALID; ++invalid_count; invalid += " " + _positional[i]; VALID:; } deferred_assert( identifier(), invalid.empty(), std::string( "invalid positional argument" ) + ( invalid_count > 1 ? "s" : "" ) + invalid ); } std::pair<std::string, _matcher::arg_type> _matcher::get_and_mark_as_queried( const identifier & id ) { for( const auto & it : _queried ) _instant_assert( !it.overlaps( id ), "double query for argument " + id.longer() ); if( _strict ) _queried.push_back( id ); for( auto it = _named.begin(); it != _named.end(); ++it ) { if( id.contains( it->first ) ) { optional<std::string> result = it->second; if( result.has_value() ) return { result.value(), arg_type::string_t }; return { "", arg_type::bool_t }; } } if( id.get_pos().has_value() ) { size_t pos = id.get_pos().value(); if( pos >= _positional.size() ) return { "", arg_type::none_t }; return { _positional[pos], arg_type::string_t }; } return { "", arg_type::none_t }; } void _matcher::parse( int argc, const char ** argv ) { _executable = argv[0]; std::vector<std::string> raw = to_vector_string( argc - 1, argv + 1 ); std::vector<std::string> eqs = equate_assignments( raw, _::logger.get_assignment_arguments() ); std::vector<std::string> named; tie( named, _positional ) = separate_named_positional( eqs ); named = expand_single_hyphen( named ); _named = assign_named_values( named ); for( size_t i = 0; i < _named.size(); ++i ) for( size_t j = 0; j < i; ++j ) deferred_assert( identifier(), _named[i].first != _named[j].first, "multiple occurrences of argument " + identifier::prepend_hyphens( _named[i].first ) ); } std::vector<std::string> _matcher::to_vector_string( int n_strings, const char ** strings ) { std::vector<std::string> raw( n_strings ); for( int i = 0; i < n_strings; ++i ) raw[i] = strings[i]; return raw; } std::vector<std::string> _matcher::equate_assignments( const std::vector<std::string> & raw, const std::vector<std::string> & assigned ) { std::vector<std::string> eqs; size_t i = 0; while( i < raw.size() ) { if( raw[i] == "--" || ( i + 1 < raw.size() && raw[i + 1] == "--" ) ) { eqs.insert( eqs.end(), raw.begin() + i, raw.end() ); break; } if( i == raw.size() - 1 || std::find( assigned.begin(), assigned.end(), raw[i] ) == assigned.end() ) { eqs.push_back( raw[i] ); ++i; } else { eqs.push_back( raw[i] + "=" + raw[i + 1] ); i += 2; } } return eqs; } std::tuple<std::vector<std::string>, std::vector<std::string>> _matcher::separate_named_positional( const std::vector<std::string> & eqs ) { std::vector<std::string> named, positional; for( size_t i = 0; i < eqs.size(); ++i ) { const std::string & s = eqs[i]; int hyphens = count_hyphens( s ); if( s == "--" ) { // Double dash indicates that upcoming arguments are positional only positional.insert( positional.end(), eqs.begin() + i + 1, eqs.end() ); break; } deferred_assert( identifier(), hyphens <= 2, "too many hyphens: " + s ); if( ( hyphens == 1 && !isdigit( s[1] ) ) || hyphens == 2 ) named.push_back( s ); else positional.push_back( s ); } return std::tuple<std::vector<std::string>, std::vector<std::string>>( named, positional ); } std::vector<std::string> _matcher::expand_single_hyphen( const std::vector<std::string> & named ) { std::vector<std::string> new_named; for( const std::string & s : named ) { int hyphens = count_hyphens( s ); if( hyphens == 1 && s.find( '=' ) != std::string::npos && s.find( '=' ) >= 3 ) { deferred_assert( identifier(), false, "expanding single-hyphen arguments can't have value (" + s + ")" ); continue; } if( hyphens == 1 && s.find( '=' ) == std::string::npos ) for( size_t i = 1; i < s.size(); ++i ) { new_named.push_back( std::string( "-" ) + s[i] ); } else new_named.push_back( s ); } return new_named; } std::vector<std::pair<std::string, optional<std::string>>> _matcher::assign_named_values( const std::vector<std::string> & named ) { std::vector<std::pair<std::string, optional<std::string>>> args; for( const std::string & eq : named ) { size_t index = eq.find( '=' ); size_t hyphens = count_hyphens( eq ); std::string name = eq; if( index == std::string::npos ) { args.emplace_back( eq, optional<std::string>() ); } else { name = eq.substr( 0, index ); std::string value = eq.substr( index + 1 ); args.emplace_back( name, value ); } size_t name_size = eq.size() - hyphens; deferred_assert( identifier(), hyphens <= 2, name + " must have at most two hyphens" ); if( hyphens == 2 ) deferred_assert( identifier(), name_size >= 2, "multi-character name " + name + " must have at least two hyphens" ); } return args; } bool _matcher::deferred_assert( const identifier & id, bool pass, const std::string & msg ) { if( !_strict ) { _instant_assert( pass, msg, false ); return pass; } if( !pass ) _deferred_error.set( id, msg ); return pass; } std::string _arg_logger::_make_printable( const identifier & id, const elem & elem, bool verbose ) { std::string printable; if( elem.optional || elem.t == elem::type::none ) printable += "["; printable += verbose ? id.help() : id.longer(); if( elem.t != elem::type::none && !( !verbose && id.get_pos().has_value() ) ) { printable += id.get_pos().has_value() ? " " : "="; if( elem.t == elem::type::string ) printable += "STRING"; if( elem.t == elem::type::integer ) printable += "INTEGER"; if( elem.t == elem::type::real ) printable += "REAL NUMBER"; } if( elem.optional || elem.t == elem::type::none ) printable += "]"; return printable; } void _arg_logger::_add_to_help( std::string & usage, std::string & options, const identifier & id, const elem & elem, size_t margin ) { usage += " "; usage += _make_printable( id, elem, false ); std::string printable = _make_printable( id, elem, true ); options += " " + printable + std::string( 2 + margin - printable.size(), ' ' ) + elem.descr; if( !elem.def.empty() ) options += " [default: " + elem.def + "]"; options += "\n"; } void _arg_logger::print_help() { using id2elem = std::pair<identifier, elem>; std::string usage = " Usage:\n " + _::matcher.get_executable(); std::string options = " Options:\n"; std::vector<id2elem> printed( _params ); for( id2elem & elem : printed ) elem.first.set_optional( elem.second.optional ); std::sort( printed.begin(), printed.end(), []( const id2elem & a, const id2elem & b ) { return a.first < b.first; } ); size_t margin = 0; for( const auto & it : printed ) margin = std::max( margin, _make_printable( it.first, it.second, true ).size() ); for( const auto & it : printed ) _add_to_help( usage, options, it.first, it.second, margin ); std::cerr << std::endl << usage << std::endl << std::endl << std::endl << options << std::endl; } std::vector<std::string> _arg_logger::get_assignment_arguments() const { // Returns arguments expecting a value std::vector<std::string> args; for( const std::pair<identifier, elem> & p : _params ) if( p.second.t != elem::type::none ) { optional<std::string> short_name = p.first.short_name(); if( short_name.has_value() ) args.push_back( short_name.value() ); optional<std::string> long_name = p.first.long_name(); if( long_name.has_value() ) args.push_back( long_name.value() ); } return args; } void _arg_logger::log( const identifier & name, const elem & _elem ) { elem elem = _elem; elem.optional |= !elem.def.empty(); _params.emplace_back( name, elem ); } void _arg_logger::set_introspect_count( int count ) { _introspect_count = count; _::matcher.set_introspect( _introspect_count > 0 ); } int _arg_logger::decrease_introspect_count() { --_introspect_count; _::matcher.set_introspect( _introspect_count > 0 ); return _introspect_count; } template <> inline optional<long long> arg::_get<long long>() { auto elem = _::matcher.get_and_mark_as_queried( _id ); _::matcher.deferred_assert( _id, elem.second != _matcher::arg_type::bool_t, "argument " + _id.help() + " must have value" ); if( elem.second == _matcher::arg_type::string_t ) { char * end_ptr; errno = 0; long long converted = std::strtoll( elem.first.data(), &end_ptr, 10 ); if( errno == ERANGE ) _::matcher.deferred_assert( _id, false, "value " + elem.first + " out of range" ); _::matcher.deferred_assert( _id, end_ptr == elem.first.data() + elem.first.size(), "value " + elem.first + " is not an integer" ); return converted; } return _int_value; } template <> inline optional<long double> arg::_get<long double>() { auto elem = _::matcher.get_and_mark_as_queried( _id ); _::matcher.deferred_assert( _id, elem.second != _matcher::arg_type::bool_t, "argument " + _id.help() + " must have value" ); if( elem.second == _matcher::arg_type::string_t ) { char * end_ptr; errno = 0; long double converted = std::strtold( elem.first.data(), &end_ptr ); if( errno == ERANGE ) _::matcher.deferred_assert( _id, false, "value " + elem.first + " out of range" ); _::matcher.deferred_assert( _id, end_ptr == elem.first.data() + elem.first.size(), "value " + elem.first + " is not a real number" ); return converted; } if( _float_value.has_value() ) return _float_value; if( _int_value.has_value() ) return (long double)_int_value.value(); return {}; } template <> inline optional<std::string> arg::_get<std::string>() { auto elem = _::matcher.get_and_mark_as_queried( _id ); _::matcher.deferred_assert( _id, elem.second != _matcher::arg_type::bool_t, "argument " + _id.help() + " must have value" ); if( elem.second == _matcher::arg_type::string_t ) return elem.first; return _string_value; } template < typename T, typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value>::type *> optional<T> arg::_get_with_precision() { optional<long long> opt_value = _get<long long>(); if( !opt_value.has_value() ) return optional<T>(); long long value = opt_value.value(); bool is_signed = std::numeric_limits<T>::is_signed; T min = std::numeric_limits<T>::lowest(); T max = std::numeric_limits<T>::max(); _::matcher.deferred_assert( _id, is_signed || value >= 0, "argument " + _id.help() + " must be positive" ); _::matcher.deferred_assert( _id, min <= value && value <= max, "value " + std::to_string( value ) + " out of range" ); return (T)value; } template <typename T, typename std::enable_if<std::is_floating_point<T>::value>::type *> optional<T> arg::_get_with_precision() { optional<long double> opt_value = _get<long double>(); if( !opt_value.has_value() ) return optional<T>(); long double value = opt_value.value(); T min = std::numeric_limits<T>::lowest(); T max = std::numeric_limits<T>::max(); _::matcher.deferred_assert( _id, min <= value && value <= max, "value " + std::to_string( value ) + " out of range" ); return (T)value; } template <typename T> optional<T> arg::_convert_optional( bool dec_main_args ) { if( _::matcher.get_introspect() ) return optional<T>(); _instant_assert( !( _int_value.has_value() || _float_value.has_value() || _string_value.has_value() ), "optional argument has default value" ); optional<T> val = _get_with_precision<T>(); _::matcher.check( dec_main_args ); return val; } template <typename T> T arg::_convert( bool dec_main_args ) { if( _::matcher.get_introspect() ) return T(); optional<T> val = _get_with_precision<T>(); _::matcher.deferred_assert( _id, val.has_value(), "required argument " + _id.longer() + " not provided" ); _::matcher.check( dec_main_args ); return val.value_or( T() ); } void arg::_log( _arg_logger::elem::type t, bool optional ) { std::string def; if( _int_value.has_value() ) def = std::to_string( _int_value.value() ); if( _float_value.has_value() ) def = std::to_string( _float_value.value() ); if( _string_value.has_value() ) def = _string_value.value(); _::logger.log( _id, { _id.get_descr(), t, def, optional } ); int count = _::logger.get_introspect_count(); if( count > 0 ) { // introspection is active count = _::logger.decrease_introspect_count(); if( count == 0 ) { // introspection ends #if defined( __EXCEPTIONS ) || defined( _CPPUNWIND ) throw _escape_exception(); #endif } } } arg::operator bool() { _instant_assert( !_int_value.has_value() && !_float_value.has_value() && !_string_value.has_value(), _id.longer() + " flag parameter must not have default value" ); _log( _arg_logger::elem::type::none, true ); // User sees this as flag, not boolean option auto elem = _::matcher.get_and_mark_as_queried( _id ); _::matcher.deferred_assert( _id, elem.second != _matcher::arg_type::string_t, "flag " + _id.help() + " must not have value" ); _::matcher.check( true ); return elem.second == _matcher::arg_type::bool_t; } template <typename T> arg::operator std::vector<T>() { std::vector<T> ret; for( size_t i = 0; i < _::matcher.pos_args(); ++i ) ret.push_back( arg( (int)i )._convert<T>( false ) ); _log( _arg_logger::elem::type::none, true ); _::matcher.check( true ); return ret; } } // namespace fire #define PREPARE_FIRE_( fired_main, argc, argv ) \ int main_args = (int)fire::_get_argument_count( fired_main ); \ \ fire::_::logger = fire::_arg_logger(); \ fire::_::matcher = fire::_matcher(); \ fire::_::logger.set_introspect_count( main_args ); \ if( main_args > 0 ) \ { \ try \ { \ fired_main(); /* fired_main() isn't actually executed, the last default argument will \ always throw */ \ } \ catch( fire::_escape_exception e ) \ { \ } \ } \ \ fire::_::matcher = fire::_matcher( argc, argv, main_args, true ); \ fire::_::logger = fire::_arg_logger() #define FIRE( fired_main ) \ int main( int argc, const char ** argv ) \ { \ PREPARE_FIRE_( fired_main, argc, argv ); \ return fired_main(); \ } #define FIRE_NO_SPACE_ASSIGNMENT( fired_main ) \ int main( int argc, const char ** argv ) \ { \ int main_args = (int)fire::_get_argument_count( fired_main ); \ fire::_::matcher = fire::_matcher( argc, argv, main_args, true ); \ return fired_main(); \ } #endif #include <cmath> #include <cuda_runtime.h> enum class model { vogels, brunel, brunel_plus, // "brunel+" synth }; model str2model( std::string s ) { if( !s.compare( "vogels" ) ) return model::vogels; else if( !s.compare( "brunel" ) ) return model::brunel; else if( !s.compare( "brunel+" ) ) return model::brunel_plus; else if( !s.compare( "synth" ) ) return model::synth; else throw std::invalid_argument( "invalid model" ); } enum class gpu { single, multi }; gpu str2gpu( std::string s ) { if( !s.compare( "single" ) ) return gpu::single; else if( !s.compare( "multi" ) ) return gpu::multi; else throw std::invalid_argument( "invalid gpu" ); } enum class bench { setup, sim }; bench str2bench( std::string s ) { if( !s.compare( "setup" ) ) return bench::setup; else if( !s.compare( "sim" ) ) return bench::sim; else throw std::invalid_argument( "invalid benchmark" ); } void benchfun( model m, gpu g, int nneuron, double pconnect, int delay, double pfire ); std::string rtz( std::string s ) { while( s.back() == '0' ) s.erase( s.length() - 1 ); return s; } int _main( std::string model = fire::arg( "--model" ), fire::optional<double> pconnect = fire::arg( "--pconnect" ), fire::optional<double> pfire = fire::arg( "--pfire" ), fire::optional<int> delay = fire::arg( "--delay" ), std::size_t nsyn = fire::arg( "--nsyn" ), std::string gpu = fire::arg( "--gpu" ), std::string bench = fire::arg( "--bench" ) ) { std::string m = model; double pc = -1; double pf = -1; int d = -1; int nneuron = -1; switch( str2model( model ) ) { case model::vogels: pc = 0.02; d = 8; nneuron = static_cast<int>( std::sqrt( nsyn / pc ) ); break; case model::brunel: case model::brunel_plus: pc = 0.1; d = 15; nneuron = static_cast<int>( std::sqrt( nsyn / 0.05 ) ); break; case model::synth: pc = pconnect.value(); pf = pfire.value(); d = delay.value(); nneuron = static_cast<int>( std::sqrt( nsyn / pc ) ); m = model + "_" + rtz( std::to_string( pc ) ) + "_" + rtz( std::to_string( pf ) ) + "_" + std::to_string( d ); break; } std::string sim = fire::_storage<>::matcher.get_executable(); sim = sim.substr( sim.find_last_of( "/" ) + 1, sim.length() - sim.find_last_of( "/" ) - 1 ); int ngpus = -1; cudaGetDeviceCount(&ngpus); std::cout << "{" << std::endl << "\t\"sim\": \"" << sim << "\"," << std::endl << "\t\"model\": \"" << m << "\"," << std::endl << "\t\"#syn\": " << nsyn << "," << std::endl << "\t\"#gpus\": " << ngpus << "," << std::endl; benchfun( str2model( model ), str2gpu( gpu ), nneuron, pc, d, pf ); std::cout << "}" << std::endl; return 0; } FIRE( _main ) #include "../../include/BSim.h" #include "../../src/utils/random.h" #include "../../src/utils/timer.h" #include <memory> using namespace std; using namespace spice::util; static ulong_ seed = 1337; void connect(Network & net, int const src_pop, int const dst_pop, int const src_sz, int const dst_sz, float const p, float const w, float const d) { xoroshiro128p gen(seed++); std::vector<float> neighbors(dst_sz); for (int src = 0; src < src_sz; src++) { int const degree = binornd(gen, dst_sz, p); float total = exprnd(gen); for (int i = 0; i < degree; i++) { neighbors[i] = total; total += exprnd(gen); } float const scale = (dst_sz - degree) / total; for (int i = 0; i < degree; i++) net.connect(src_pop, src, dst_pop, static_cast<int>(neighbors[i] * scale) + i, w, d); } } void make_brunel(Network & c, int const n) { auto P = c.createPopulation(n*5/10, CompositeNeuron<PoissonNeuron, StaticSynapse>(PoissonNeuron(0.002f, 0), 1, 1)); auto E = c.createPopulation(n*4/10, CompositeNeuron<LIFEBNeuron, StaticSynapse>(LIFEBNeuron(0, 0, 0, 0, 0, 0.002f, 0, 0, 0.02f, 0), 1, 1)); auto I = c.createPopulation(n*1/10, CompositeNeuron<LIFEBNeuron, StaticSynapse>(LIFEBNeuron(0, 0, 0, 0, 0, 0.002f, 0, 0, 0.02f, 0), 1, 1)); float const Wex = 0.0001 * 20000 / n; float const Win = -0.0005 * 20000 / n; connect(c, 0, 1, P->getNum(), E->getNum(), 0.1f, Wex, 0.0015f); // P->E connect(c, 0, 2, P->getNum(), I->getNum(), 0.1f, Wex, 0.0015f); // P->I connect(c, 1, 1, E->getNum(), E->getNum(), 0.1f, Wex, 0.0015f); // E->E connect(c, 1, 2, E->getNum(), I->getNum(), 0.1f, Wex, 0.0015f); // E->I connect(c, 2, 1, I->getNum(), E->getNum(), 0.1f, Win, 0.0015f); // I->E connect(c, 2, 2, I->getNum(), I->getNum(), 0.1f, Win, 0.0015f); // I->I } void make_vogels(Network & c, int const n) { auto E = c.createPopulation(n*8/10, CompositeNeuron<LIFENeuron, StaticSynapse>(LIFENeuron(-0.06f, -0.06f, -0.06f, 0, 0, 0.005f, 0, 0, -0.05f, 0), 1, 1)); auto I = c.createPopulation(n*2/10, CompositeNeuron<LIFENeuron, StaticSynapse>(LIFENeuron(-0.06f, -0.06f, -0.06f, 0, 0, 0.005f, 0, 0, -0.05f, 0), 1, 1)); float const Wex = 0.4 * 16000000 / n / n; float const Win = -5.1 * 16000000 / n / n; connect(c, 0, 0, E->getNum(), E->getNum(), 0.02f, Wex, 0.0008f); // E->E connect(c, 0, 1, E->getNum(), I->getNum(), 0.02f, Wex, 0.0008f); // E->I connect(c, 1, 0, I->getNum(), E->getNum(), 0.02f, Win, 0.0008f); // I->E connect(c, 1, 1, I->getNum(), I->getNum(), 0.02f, Win, 0.0008f); // I->I } void make_synth(Network & c, int const n, float const p_fire, float const p_connect, int const delay) { auto P = c.createPopulation(n, CompositeNeuron<PoissonNeuron, StaticSynapse>(PoissonNeuron(p_fire, 0), 1, 1)); connect(c, 0, 0, P->getNum(), P->getNum(), p_connect, 1, delay * 0.0001); // E->E } void benchfun( model m, gpu g, int nneuron, double pconnect, int delay, double pfire ) { timer t; try { Network c; switch(m) { case model::vogels: make_vogels(c, nneuron); break; case model::brunel: make_brunel(c, nneuron); break; case model::synth: make_synth(c, nneuron, pfire, pconnect, delay); break; default: throw std::runtime_error("not implemented"); } std::unique_ptr<SimulatorBase> sg; switch(g) { case gpu::single: sg.reset(new SGSim(&c, 0.0001f)); break; case gpu::multi: sg.reset(new MGSim(&c, 0.0001f)); break; } double tsetup = t.stop(); tsetup += sg->run(10) * 1e-3; printf("\t\"setuptime\": %f\n", tsetup); } catch (...) { printf("\t\"simtime\": -1,\n"); printf("\t\"setuptime\": -1\n"); } }
29.048227
154
0.62359
[ "object", "vector", "model", "transform" ]
788942b8036d67a304b434c4f9b86fdbe4847076
4,764
cpp
C++
Library/Standard/Primitives/PathNodeEnumerator.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/Standard/Primitives/PathNodeEnumerator.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/Standard/Primitives/PathNodeEnumerator.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
#include "PlatoIncludes.h" #include "Strings.h" #include "ClassTypeInfo.h" #include "Debug.h" #include "Identifier.h" #include "IdentifierRegex.h" #include "PropertyModes.h" #include "PropertyScopes.h" #include "Property.h" #include "ConfigurePhases.h" #include "Container.h" #include "Arguments.h" #include "PropertyEnumerator.h" #include "Filter.h" #include "ScopeEnumerator.h" #include "PathNodeEnumerator.h" #include "PathNode.h" #include "Path.h" #include "Filter.h" #include "IdentifierFilter.h" namespace Plato { PathNodeEnumerator::PathNodeEnumerator(PathNode& currentPathNode, Container* nodeCurrentContainer, const Property* requester, PropertyModesEnum mode) { mPathNode = new PathNode(currentPathNode); mNodeCurrentContainer = nodeCurrentContainer; mRequester = requester; mMode = mode; mNodeEnumerator = NULL; mFilterContainer = NULL; Reset(); } PathNodeEnumerator::~PathNodeEnumerator() { delete mPathNode; delete mNodeEnumerator; delete mFilterContainer; } void PathNodeEnumerator::Reset() { Current = NULL; NodeGroupFilter = NULL; mWorkingContainer = NULL; if(mNodeEnumerator!=NULL) { delete mNodeEnumerator; mNodeEnumerator = NULL; } if(mFilterContainer!=NULL) { delete mFilterContainer; mFilterContainer = NULL; } mIsReset = true; } bool PathNodeEnumerator::MoveNext() { // Working out what is next item from path node: // 0) Move to required container: (e.g. Owner, Parent, etc.), see NodeKind. // 1) Apply match against mNodeIdentifier - which may be a filter. // 2) Apply filter. // 3) Get enumerator for filter. // 4) Return values via enumerator. while (mIsReset) { mIsReset = false; mNodeEnumerator = NULL; // Check if this node refers to a single container or many. switch(mPathNode->NodeKind) { case PathNodeKinds::Wild: // A Wild node acts like a filter that allows all through, in which case skip over filtering. mWorkingContainer = mNodeCurrentContainer; if (mWorkingContainer == NULL) { return false; } mNodeEnumerator = new ScopeEnumerator(*mWorkingContainer,mRequester); break; case PathNodeKinds::Regex: mWorkingContainer = mNodeCurrentContainer; if (mWorkingContainer == NULL) { return false; } // Check if need to set up a filter on the fly. if(mPathNode->AdditionalArguments==NULL) { mPathNode->AdditionalArguments = new IdentifierFilterArguments(*new IdentifierRegex(*(mPathNode->RegexIdentity)),true); mPathNode->mFilterType = IdentifierFilter::TypeInfo; } case PathNodeKinds::Filter: { mWorkingContainer = mNodeCurrentContainer; if (mWorkingContainer == NULL) { return false; } // Apply filter to get final enumeration. FilterArguments* filterArguments = new FilterArguments(mPathNode->ParentPath->Creator,mWorkingContainer,mWorkingContainer, mRequester,mMode,mPathNode->AdditionalArguments); mFilterContainer = mPathNode->CreateFilter(*filterArguments); if (mFilterContainer == NULL) { delete filterArguments; return false; } if(mFilterContainer->Flags.IsGroupFilter) { NodeGroupFilter = (GroupFilter*)mFilterContainer; } mFilterContainer->AccessContents(); mNodeEnumerator = new ScopeEnumerator(*mFilterContainer,mRequester); } break; default: // Node refers to a single object. Current = mPathNode->GetProperty(mNodeCurrentContainer,mRequester,mMode,mWorkingContainer); return Current != NULL; } } if (mNodeEnumerator != NULL && mNodeEnumerator->MoveNext()) { Current = mNodeEnumerator->Current; } else { Current = NULL; } return Current != NULL; } }
39.7
146
0.556255
[ "object" ]
7889d56807edd1980631ab7a7a249d262eda35f8
2,982
cpp
C++
Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroup.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroup.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroup.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <RHI/FrameGraphExecuteGroup.h> #include <RHI/SwapChain.h> namespace AZ { namespace DX12 { void FrameGraphExecuteGroup::Init( Device& device, const Scope& scope, uint32_t commandListCount, RHI::JobPolicy globalJobPolicy) { SetDevice(device); m_scope = &scope; m_hardwareQueueClass = scope.GetHardwareQueueClass(); m_workRequest.m_waitFences = scope.GetWaitFences(); m_workRequest.m_signalFence = scope.GetSignalFenceValue(); m_workRequest.m_commandLists.resize(commandListCount); { auto& fencesToSignal = m_workRequest.m_userFencesToSignal; fencesToSignal.reserve(scope.GetFencesToSignal().size()); for (const RHI::Ptr<RHI::Fence>& fence : scope.GetFencesToSignal()) { fencesToSignal.push_back(&static_cast<FenceImpl&>(*fence).Get()); } } { auto& swapChainsToPresent = m_workRequest.m_swapChainsToPresent; swapChainsToPresent.reserve(scope.GetSwapChainsToPresent().size()); for (RHI::SwapChain* swapChain : scope.GetSwapChainsToPresent()) { swapChainsToPresent.push_back(static_cast<SwapChain*>(swapChain)); } } InitRequest request; request.m_scopeId = scope.GetId(); request.m_commandLists = reinterpret_cast<RHI::CommandList* const*>(m_workRequest.m_commandLists.data()); request.m_commandListCount = commandListCount; request.m_jobPolicy = globalJobPolicy; Base::Init(request); } void FrameGraphExecuteGroup::BeginContextInternal( RHI::FrameGraphExecuteContext& context, uint32_t contextIndex) { CommandList* commandList = AcquireCommandList(); const RHI::ScopeId& scopeId = context.GetScopeId(); commandList->Open(scopeId); m_workRequest.m_commandLists[contextIndex] = commandList; context.SetCommandList(*commandList); m_scope->Begin(*commandList, context.GetCommandListIndex(), context.GetCommandListCount()); } void FrameGraphExecuteGroup::EndContextInternal( RHI::FrameGraphExecuteContext& context, uint32_t contextIndex) { (void)contextIndex; CommandList* commandList = static_cast<CommandList*>(context.GetCommandList()); m_scope->End(*commandList, context.GetCommandListIndex(), context.GetCommandListCount()); commandList->Close(); } } }
36.365854
117
0.612676
[ "3d" ]
788b37a76b1eb796ccf670993a145701e1f1b2a0
13,646
hpp
C++
Vimba_5.0/VimbaCPP/Include/Feature.hpp
dylansnow/vimba_pose_detection
2aeac00cb678f8a7f490f52be3fe5f87573703db
[ "MIT", "Unlicense" ]
null
null
null
Vimba_5.0/VimbaCPP/Include/Feature.hpp
dylansnow/vimba_pose_detection
2aeac00cb678f8a7f490f52be3fe5f87573703db
[ "MIT", "Unlicense" ]
10
2019-05-01T22:33:18.000Z
2019-08-15T19:52:15.000Z
FINIS-Console/include/VimbaCPP/Include/Feature.hpp
FINISinstrument/FINIS-Console
1ae597a40421dc7e22191b852c92c94e96523458
[ "MIT" ]
null
null
null
/*============================================================================= Copyright (C) 2012 Allied Vision Technologies. All Rights Reserved. Redistribution of this file, in original or modified form, without prior written consent of Allied Vision Technologies is prohibited. ------------------------------------------------------------------------------- File: Feature.hpp Description: Inline wrapper functions for class AVT::VmbAPI::Feature. ------------------------------------------------------------------------------- THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================*/ #ifndef AVT_VMBAPI_FEATURE_HPP #define AVT_VMBAPI_FEATURE_HPP // // Inline wrapper functions that allocate memory for STL objects in the application's context // and to pass data across DLL boundaries using arrays // inline VmbErrorType Feature::GetValues( StringVector &rValues ) { VmbErrorType res; VmbUint32_t nSize; res = GetValues( (const char **)NULL, nSize ); if ( VmbErrorSuccess == res ) { if ( 0 != nSize) { try { std::vector<const char*> data( nSize ); res = GetValues( &data[0], nSize ); if ( VmbErrorSuccess == res ) { StringVector tmpValues( data.size() ); std::copy( data.begin(), data.end(), tmpValues.begin() ); rValues.swap( tmpValues); } } catch(...) { return VmbErrorResources; } } else { rValues.clear(); } } return res; } inline VmbErrorType Feature::GetEntries( EnumEntryVector &rEntries ) { VmbErrorType res; VmbUint32_t nSize; res = GetEntries( (EnumEntry*)NULL, nSize ); if ( VmbErrorSuccess == res ) { if( 0 != nSize ) { try { EnumEntryVector tmpEntries( nSize ); res = GetEntries( &tmpEntries[0], nSize ); if( VmbErrorSuccess == res) { rEntries.swap( tmpEntries ); } } catch(...) { return VmbErrorResources; } } else { rEntries.clear(); } } return res; } inline VmbErrorType Feature::GetValues( Int64Vector &rValues ) { VmbErrorType res; VmbUint32_t nSize; res = GetValues( (VmbInt64_t*)NULL, nSize ); if ( VmbErrorSuccess == res ) { if( 0 != nSize) { try { Int64Vector tmpValues( nSize ); res = GetValues( &tmpValues[0], nSize ); if( VmbErrorSuccess == res) { rValues.swap( tmpValues ); } } catch(...) { return VmbErrorResources; } } else { rValues.clear(); } } return res; } inline VmbErrorType Feature::GetValue( std::string &rStrValue ) const { VmbErrorType res; VmbUint32_t nLength; res = GetValue( (char * const)NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpValue( nLength + 1, '\0' ); res = GetValue( &tmpValue[0], nLength ); if ( VmbErrorSuccess == res ) { rStrValue = &*tmpValue.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrValue.clear(); } } return res; } inline VmbErrorType Feature::GetValue( UcharVector &rValue ) const { VmbUint32_t i; return GetValue( rValue, i ); } inline VmbErrorType Feature::GetValue( UcharVector &rValue, VmbUint32_t &rnSizeFilled ) const { VmbErrorType res; VmbUint32_t nSize; res = GetValue( NULL, nSize, rnSizeFilled ); if ( VmbErrorSuccess == res ) { if( 0 != nSize) { try { UcharVector tmpValue( nSize ); res = GetValue( &tmpValue[0], nSize, rnSizeFilled ); if( VmbErrorSuccess == res ) { rValue.swap( tmpValue); } } catch(...) { return VmbErrorResources; } } else { rValue.clear(); } } return res; } inline VmbErrorType Feature::SetValue( const UcharVector &rValue ) { if ( rValue.empty() ) { return VmbErrorBadParameter; } return SetValue( &rValue[0], (VmbUint32_t)rValue.size() ); } inline VmbErrorType Feature::GetName( std::string &rStrName ) const { VmbErrorType res; VmbUint32_t nLength; res = GetName( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpName( nLength + 1, '\0' ); res = GetName( &tmpName[0], nLength ); if( VmbErrorSuccess == res) { rStrName = &*tmpName.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrName.clear(); } } return res; } inline VmbErrorType Feature::GetDisplayName( std::string &rStrDisplayName ) const { VmbErrorType res; VmbUint32_t nLength; res = GetDisplayName( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpDisplayName( nLength + 1, '\0' ); res = GetDisplayName( &tmpDisplayName[0], nLength ); if( VmbErrorSuccess == res ) { rStrDisplayName = &*tmpDisplayName.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrDisplayName.clear(); } } return res; } inline VmbErrorType Feature::GetCategory( std::string &rStrCategory ) const { VmbErrorType res; VmbUint32_t nLength; res = GetCategory( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpCategory( nLength + 1, '\0' ); res = GetCategory( &tmpCategory[0], nLength ); if( VmbErrorSuccess == res ) { rStrCategory = &*tmpCategory.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrCategory.clear(); } } return res; } inline VmbErrorType Feature::GetUnit( std::string &rStrUnit ) const { VmbErrorType res; VmbUint32_t nLength; res = GetUnit( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpUnit( nLength + 1, '\0' ); res = GetUnit( &tmpUnit[0], nLength ); if( VmbErrorSuccess == res ) { rStrUnit = &*tmpUnit.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrUnit.clear(); } } return res; } inline VmbErrorType Feature::GetRepresentation( std::string &rStrRepresentation ) const { VmbErrorType res; VmbUint32_t nLength; res = GetRepresentation( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpRepresentation( nLength + 1, '\0' ); res = GetRepresentation( &tmpRepresentation[0], nLength ); if( VmbErrorSuccess == res ) { rStrRepresentation = &*tmpRepresentation.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrRepresentation.clear(); } } return res; } inline VmbErrorType Feature::GetToolTip( std::string &rStrToolTip ) const { VmbErrorType res; VmbUint32_t nLength; res = GetToolTip( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpToolTip( nLength + 1, '\0'); res = GetToolTip( &tmpToolTip[0], nLength ); if( VmbErrorSuccess == res ) { rStrToolTip = &*tmpToolTip.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrToolTip.clear(); } } return res; } inline VmbErrorType Feature::GetDescription( std::string &rStrDescription ) const { VmbErrorType res; VmbUint32_t nLength; res = GetDescription( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpDescription( nLength + 1, '\0'); res = GetDescription( &tmpDescription[0], nLength ); if( VmbErrorSuccess == res ) { rStrDescription = &*tmpDescription.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrDescription.clear(); } } return res; } inline VmbErrorType Feature::GetSFNCNamespace( std::string &rStrSFNCNamespace ) const { VmbErrorType res; VmbUint32_t nLength; res = GetSFNCNamespace( NULL, nLength ); if ( VmbErrorSuccess == res ) { if ( 0 != nLength ) { try { std::vector<std::string::value_type> tmpSFNCNamespace( nLength + 1, '\0' ); res = GetSFNCNamespace( &tmpSFNCNamespace[0], nLength ); if( VmbErrorSuccess == res ) { rStrSFNCNamespace = &*tmpSFNCNamespace.begin(); } } catch(...) { return VmbErrorResources; } } else { rStrSFNCNamespace.clear(); } } return res; } inline VmbErrorType Feature::GetAffectedFeatures( FeaturePtrVector &rAffectedFeatures ) { VmbErrorType res; VmbUint32_t nSize; res = GetAffectedFeatures( NULL, nSize ); if ( VmbErrorSuccess == res ) { if( 0 != nSize) { try { FeaturePtrVector tmpAffectedFeatures( nSize ); res = GetAffectedFeatures( &tmpAffectedFeatures[0], nSize ); if( VmbErrorSuccess == res ) { rAffectedFeatures.swap( tmpAffectedFeatures ); } } catch(...) { return VmbErrorResources; } } else { rAffectedFeatures.clear(); } } return res; } inline VmbErrorType Feature::GetSelectedFeatures( FeaturePtrVector &rSelectedFeatures ) { VmbErrorType res; VmbUint32_t nSize; res = GetSelectedFeatures( NULL, nSize ); if ( VmbErrorSuccess == res ) { if( 0 != nSize ) { try { FeaturePtrVector tmpSelectedFeatures( nSize ); res = GetSelectedFeatures( &tmpSelectedFeatures[0], nSize ); if( VmbErrorSuccess == res ) { rSelectedFeatures.swap ( tmpSelectedFeatures ); } } catch(...) { return VmbErrorResources; } } else { rSelectedFeatures.clear(); } } return res; } #endif
24.992674
93
0.46717
[ "vector" ]
788c5f0f4ad51bead446a528deae97456213bbd7
1,966
cpp
C++
pass-gen[56]/src/pass.cpp
kondanta/programming-challenges
4fcb7b7fc3a664a79745e6b09a0f58f11402a2a5
[ "MIT" ]
1
2018-06-22T11:58:26.000Z
2018-06-22T11:58:26.000Z
pass-gen[56]/src/pass.cpp
kondanta/programming-challenges
4fcb7b7fc3a664a79745e6b09a0f58f11402a2a5
[ "MIT" ]
null
null
null
pass-gen[56]/src/pass.cpp
kondanta/programming-challenges
4fcb7b7fc3a664a79745e6b09a0f58f11402a2a5
[ "MIT" ]
null
null
null
#include "pass.hpp" #include <vector> #include <cstdlib> #include <ctime> void PassGen::SetDigit(int flag) { digit = flag; } void PassGen::SetSymbol(int flag) { symbols = flag; } int PassGen::GetDigit() { return digit; } int PassGen::GetSymbol(){ return symbols; } void PassGen::HelpMenu(std::string argument){ std::cerr << "Usage for "<<argument<<'\n' << "-d, --digit\t for numbers [0..9]\n" <<"-s, --symbols\t for !@#$%.."; } //FIXME: Add else for 0 0 case.`` std::vector<char> CreateContainer(int dflag, int sflag){ std::vector<char> passContainer; // 3 posibilities for flags~ if(dflag == 1 && sflag == 1){ // between 1 to } all available stuff. for(char i = 33 ; i < 127; i++){ passContainer.push_back(i); } }else if(dflag == 1 && sflag == 0){ for(char i = 48; i < 123; i++){ // Fuck ASCII if(i == 58){ i = 65; }if(i == 91){ i = 97; } passContainer.push_back(i); } }else if(dflag == 0 && sflag == 1){ for(char i = 33; i < 126; i++){ if(i == 47) i = 60; passContainer.push_back(i); } }else{ passContainer.push_back('E'); } return passContainer; } void PassGen::GeneratePassword(int dflag, int sflag){ // std::vector<std::string> passContainer; std::vector<char> passContainer = CreateContainer(dflag, sflag); //Randomizing the generation each time it called! srand(time(NULL)); for(int i = 0; i < 15; i++){ int x = rand() % passContainer.size(); std::cout<<passContainer.at(x); } std::cout << "\nRand generated. Newline inserting\n"; // Printer -> separatable. for(std::vector<char>::const_iterator it = passContainer.begin(); it != passContainer.end(); ++it){ std::cout << *it; } }
23.686747
69
0.525941
[ "vector" ]
78980015f0f2cfce10af781122ead415a7cd877e
19,629
tcc
C++
src/camlsnark_c/libsnark-caml/libsnark/gadgetlib1/gadgets/verifiers/r1cs_se_ppzksnark_verifier_gadget.tcc
gtank/snarky
fad2a6d32ce8d5314c6daafa699f80985b865719
[ "MIT" ]
2
2019-06-27T13:36:19.000Z
2019-06-27T15:12:54.000Z
src/camlsnark_c/libsnark-caml/libsnark/gadgetlib1/gadgets/verifiers/r1cs_se_ppzksnark_verifier_gadget.tcc
gtank/snarky
fad2a6d32ce8d5314c6daafa699f80985b865719
[ "MIT" ]
null
null
null
src/camlsnark_c/libsnark-caml/libsnark/gadgetlib1/gadgets/verifiers/r1cs_se_ppzksnark_verifier_gadget.tcc
gtank/snarky
fad2a6d32ce8d5314c6daafa699f80985b865719
[ "MIT" ]
null
null
null
/** @file ***************************************************************************** Implementation of interfaces for the the R1CS ppzkSNARK verifier gadget. See r1cs_se_ppzksnark_verifier_gadget.hpp . ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef R1CS_SE_PPZKSNARK_VERIFIER_GADGET_TCC_ #define R1CS_SE_PPZKSNARK_VERIFIER_GADGET_TCC_ #include <libsnark/gadgetlib1/constraint_profiling.hpp> namespace libsnark { template<typename ppT> r1cs_se_ppzksnark_proof_variable<ppT>::r1cs_se_ppzksnark_proof_variable(protoboard<FieldT> &pb, const std::string &annotation_prefix) : gadget<FieldT>(pb, annotation_prefix) { const size_t num_G1 = 2; const size_t num_G2 = 1; A.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " A"))); B.reset(new G2_variable<ppT>(pb, FMT(annotation_prefix, " B"))); C.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " C"))); all_G1_vars = { A, C }; all_G2_vars = { B }; all_G1_checkers.resize(all_G1_vars.size()); for (size_t i = 0; i < all_G1_vars.size(); ++i) { all_G1_checkers[i].reset(new G1_checker_gadget<ppT>(pb, *all_G1_vars[i], FMT(annotation_prefix, " all_G1_checkers_%zu", i))); } G2_checker.reset(new G2_checker_gadget<ppT>(pb, *B, FMT(annotation_prefix, " G2_checker"))); assert(all_G1_vars.size() == num_G1); assert(all_G2_vars.size() == num_G2); } template<typename ppT> void r1cs_se_ppzksnark_proof_variable<ppT>::generate_r1cs_constraints() { for (auto &G1_checker : all_G1_checkers) { G1_checker->generate_r1cs_constraints(); } G2_checker->generate_r1cs_constraints(); } template<typename ppT> void r1cs_se_ppzksnark_proof_variable<ppT>::generate_r1cs_witness(const r1cs_se_ppzksnark_proof<other_curve<ppT> > &proof) { std::vector<libff::G1<other_curve<ppT> > > G1_elems; std::vector<libff::G2<other_curve<ppT> > > G2_elems; G1_elems = { proof.A, proof.C }; G2_elems = { proof.B }; assert(G1_elems.size() == all_G1_vars.size()); assert(G2_elems.size() == all_G2_vars.size()); for (size_t i = 0; i < G1_elems.size(); ++i) { all_G1_vars[i]->generate_r1cs_witness(G1_elems[i]); } for (size_t i = 0; i < G2_elems.size(); ++i) { all_G2_vars[i]->generate_r1cs_witness(G2_elems[i]); } for (auto &G1_checker : all_G1_checkers) { G1_checker->generate_r1cs_witness(); } G2_checker->generate_r1cs_witness(); } template<typename ppT> size_t r1cs_se_ppzksnark_proof_variable<ppT>::size() { const size_t num_G1 = 2; const size_t num_G2 = 1; return (num_G1 * G1_variable<ppT>::num_field_elems + num_G2 * G2_variable<ppT>::num_field_elems); } template<typename ppT> r1cs_se_ppzksnark_verification_key_variable<ppT>::r1cs_se_ppzksnark_verification_key_variable(protoboard<FieldT> &pb, const size_t input_size, const std::string &annotation_prefix) : gadget<FieldT>(pb, annotation_prefix), input_size(input_size) { const size_t num_G1 = 2 + (input_size + 1); const size_t num_G2 = 3; const size_t num_GT = 1; this->H.reset(new G2_variable<ppT>(pb, FMT(annotation_prefix, " H"))); this->G_alpha.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " G_alpha"))); this->H_beta.reset(new G2_variable<ppT>(pb, FMT(annotation_prefix, " H_beta"))); this->G_gamma.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " G_gamma"))); this->H_gamma.reset(new G2_variable<ppT>(pb, FMT(annotation_prefix, " H_gamma"))); this->G_alpha_H_beta_inv.reset(new Fqk_variable<ppT>(pb, FMT(annotation_prefix, "G_alpha_H_beta_inv"))); // assert(all_bits.size() == (G1_variable<ppT>::size_in_bits() * num_G1 + G2_variable<ppT>::size_in_bits() * num_G2)); all_G1_vars = { this->G_alpha, this->G_gamma }; all_G2_vars = { this->H, this->H_beta, this->H_gamma }; all_GT_vars = { this->G_alpha_H_beta_inv }; this->query.resize(input_size); this->query_base.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " query_base"))); this->all_G1_vars.emplace_back(this->query_base); for (size_t i = 0; i < input_size; ++i) { this->query[i].reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " query_%zu", i))); all_G1_vars.emplace_back(this->query[i]); } for (auto &G1_var : all_G1_vars) { all_vars.insert(all_vars.end(), G1_var->all_vars.begin(), G1_var->all_vars.end()); } for (auto &G2_var : all_G2_vars) { all_vars.insert(all_vars.end(), G2_var->all_vars.begin(), G2_var->all_vars.end()); } for (auto &GT_var : all_GT_vars) { all_vars.insert(all_vars.end(), GT_var->all_vars.begin(), GT_var->all_vars.end()); } assert(all_G1_vars.size() == num_G1); assert(all_G2_vars.size() == num_G2); assert(all_GT_vars.size() == num_GT); assert(all_vars.size() == (num_G1 * G1_variable<ppT>::num_variables() + num_G2 * G2_variable<ppT>::num_variables() + num_GT * Fqk_variable<ppT>::num_variables())); } template<typename ppT> void r1cs_se_ppzksnark_verification_key_variable<ppT>::generate_r1cs_witness(const r1cs_se_ppzksnark_verification_key<other_curve<ppT> > &vk) { std::vector<libff::G1<other_curve<ppT> > > G1_elems; std::vector<libff::G2<other_curve<ppT> > > G2_elems; std::vector<libff::Fqk<other_curve<ppT>>> GT_elems; G1_elems = { vk.G_alpha, vk.G_gamma }; G2_elems = { vk.H, vk.H_beta, vk.H_gamma }; // TODO: We should really have this take a processed verification key so we don't have // to do a pairing here (or just stick the final exp'd value in the vk, which is probably // better anyway). libff::Fqk< other_curve<ppT> > G_alpha_H_beta_inv = vk.G_alpha_H_beta.unitary_inverse(); GT_elems = { G_alpha_H_beta_inv }; assert(vk.query.size() == input_size + 1); G1_elems.emplace_back(vk.query[0]); for (size_t i = 0; i < input_size; ++i) { G1_elems.emplace_back(vk.query[i+1]); } assert(G1_elems.size() == all_G1_vars.size()); assert(G2_elems.size() == all_G2_vars.size()); assert(GT_elems.size() == all_GT_vars.size()); for (size_t i = 0; i < G1_elems.size(); ++i) { all_G1_vars[i]->generate_r1cs_witness(G1_elems[i]); } for (size_t i = 0; i < G2_elems.size(); ++i) { all_G2_vars[i]->generate_r1cs_witness(G2_elems[i]); } for (size_t i = 0; i < GT_elems.size(); ++i) { all_GT_vars[i]->generate_r1cs_witness(GT_elems[i]); } } template<typename ppT> r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable<ppT>::r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable() { // will be allocated outside } template<typename ppT> r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable<ppT>::r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable(protoboard<FieldT> &pb, const r1cs_se_ppzksnark_verification_key<other_curve<ppT> > &r1cs_vk, const std::string &annotation_prefix) { query_base.reset(new G1_variable<ppT>(pb, r1cs_vk.query[0], FMT(annotation_prefix, " query_base"))); size_t input_size = r1cs_vk.query.size() - 1; query.resize(input_size); for (size_t i = 0; i < input_size; ++i) { query[i].reset(new G1_variable<ppT>(pb, r1cs_vk.query[i + 1], FMT(annotation_prefix, " query"))); } G_alpha.reset(new G1_variable<ppT>(pb, r1cs_vk.G_alpha, FMT(annotation_prefix, " G_alpha"))); H_beta.reset(new G2_variable<ppT>(pb, r1cs_vk.H_beta, FMT(annotation_prefix, " G_alpha"))); G_alpha_H_beta_inv.reset( new Fqk_variable<ppT>(pb, r1cs_vk.G_alpha_H_beta.unitary_inverse(), FMT(annotation_prefix, " G_alpha_H_beta_inv"))); G_gamma_pc.reset( new G1_precomputation<ppT>(pb, r1cs_vk.G_gamma, FMT(annotation_prefix, " G_gamma_pc"))); H_gamma_pc.reset( new G2_precomputation<ppT>(pb, r1cs_vk.H_gamma, FMT(annotation_prefix, " H_gamma_pc"))); H_pc.reset( new G2_precomputation<ppT>(pb, r1cs_vk.H, FMT(annotation_prefix, " H_pc"))); } template<typename ppT> r1cs_se_ppzksnark_verifier_process_vk_gadget<ppT>::r1cs_se_ppzksnark_verifier_process_vk_gadget(protoboard<FieldT> &pb, const r1cs_se_ppzksnark_verification_key_variable<ppT> &vk, r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable<ppT> &pvk, const std::string &annotation_prefix) : gadget<FieldT>(pb, annotation_prefix), vk(vk), pvk(pvk) { pvk.query_base = vk.query_base; pvk.query = vk.query; pvk.G_alpha = vk.G_alpha; pvk.H_beta = vk.H_beta; pvk.G_alpha_H_beta_inv = vk.G_alpha_H_beta_inv; pvk.G_gamma_pc.reset(new G1_precomputation<ppT>()); pvk.H_gamma_pc.reset(new G2_precomputation<ppT>()); pvk.H_pc.reset(new G2_precomputation<ppT>()); compute_G_gamma_pc.reset( new precompute_G1_gadget<ppT>(pb, *vk.G_gamma, *pvk.G_gamma_pc, FMT(annotation_prefix, " compute_G_gamma_pc"))); compute_H_gamma_pc.reset( new precompute_G2_gadget<ppT>(pb, *vk.H_gamma, *pvk.H_gamma_pc, FMT(annotation_prefix, " compute_H_gamma_pc"))); compute_H_pc.reset( new precompute_G2_gadget<ppT>(pb, *vk.H, *pvk.H_pc, FMT(annotation_prefix, " compute_H_pc"))); } template<typename ppT> void r1cs_se_ppzksnark_verifier_process_vk_gadget<ppT>::generate_r1cs_constraints() { compute_G_gamma_pc->generate_r1cs_constraints(); compute_H_gamma_pc->generate_r1cs_constraints(); compute_H_pc->generate_r1cs_constraints(); } template<typename ppT> void r1cs_se_ppzksnark_verifier_process_vk_gadget<ppT>::generate_r1cs_witness() { compute_G_gamma_pc->generate_r1cs_witness(); compute_H_gamma_pc->generate_r1cs_witness(); compute_H_pc->generate_r1cs_witness(); } template<typename ppT> r1cs_se_ppzksnark_online_verifier_gadget<ppT>::r1cs_se_ppzksnark_online_verifier_gadget(protoboard<FieldT> &pb, const r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable<ppT> &pvk, const pb_variable_array<FieldT> &input, const size_t elt_size, const r1cs_se_ppzksnark_proof_variable<ppT> &proof, const pb_variable<FieldT> &result, const std::string &annotation_prefix) : gadget<FieldT>(pb, annotation_prefix), pvk(pvk), input(input), elt_size(elt_size), proof(proof), result(result), input_len(input.size()) { // accumulate input and store base in acc // TODO: Check why base (i.e., pvk.query[0]) goes in this vector acc.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " acc"))); std::vector<G1_variable<ppT> > IC_terms; for (size_t i = 0; i < pvk.query.size(); ++i) { IC_terms.emplace_back(*(pvk.query[i])); } accumulate_input.reset( new G1_multiscalar_mul_gadget<ppT>(pb, *(pvk.query_base), input, elt_size, IC_terms, *acc, FMT(annotation_prefix, " accumulate_input"))); // allocate results for precomputation proof_A_G_alpha_precomp.reset(new G1_precomputation<ppT>()); proof_B_H_beta_precomp.reset(new G2_precomputation<ppT>()); acc_precomp.reset(new G1_precomputation<ppT>()); proof_A_precomp.reset(new G1_precomputation<ppT>()); proof_B_precomp.reset(new G2_precomputation<ppT>()); proof_C_precomp.reset(new G1_precomputation<ppT>()); // do the necessary precomputations proof_A_G_alpha.reset(new G1_variable<ppT>(pb, FMT(annotation_prefix, " proof_A_G_alpha"))); compute_proof_A_G_alpha.reset(new G1_add_gadget<ppT>(pb, *(proof.A), *pvk.G_alpha , *proof_A_G_alpha, FMT(annotation_prefix, " compute_proof_A_G_alpha"))); proof_B_H_beta.reset(new G2_variable<ppT>(pb, FMT(annotation_prefix, " proof_B_H_beta"))); compute_proof_B_H_beta.reset( new G2_add_gadget<ppT>(pb, *(proof.B), *pvk.H_beta, *proof_B_H_beta, FMT(annotation_prefix, " compute_proof_B_H_beta"))); compute_proof_A_G_alpha_precomp.reset( new precompute_G1_gadget<ppT>(pb, *proof_A_G_alpha, *proof_A_G_alpha_precomp, FMT(annotation_prefix, " compute_proof_A_G_alpha_precomp"))); compute_proof_B_H_beta_precomp.reset( new precompute_G2_gadget<ppT>(pb, *proof_B_H_beta, *proof_B_H_beta_precomp, FMT(annotation_prefix, " compute_proof_B_H_beta_precomp"))); compute_acc_precomp.reset( new precompute_G1_gadget<ppT>(pb, *acc, *acc_precomp, FMT(annotation_prefix, " compute_acc_precomp"))); compute_proof_A_precomp.reset( new precompute_G1_gadget<ppT>(pb, *(proof.A), *proof_A_precomp, FMT(annotation_prefix, " compute_proof_A_precomp"))); compute_proof_B_precomp.reset( new precompute_G2_gadget<ppT>(pb, *(proof.B), *proof_B_precomp, FMT(annotation_prefix, " compute_proof_B_precomp"))); compute_proof_C_precomp.reset( new precompute_G1_gadget<ppT>(pb, *(proof.C), *proof_C_precomp, FMT(annotation_prefix, " compute_proof_C_precomp"))); // Now do the pairing checks /** * e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{acc}, H^{gamma}) * e(C, H) * where acc = \sum_{i=0}^l input_i pvk.query[i] * * We check instead (the equivalent condition) * * e(G^{acc}, H^{gamma}) * e(C, H) / e(A*G^{alpha}, B*H^{beta}) = 1 / e(G^{alpha}, H^{beta}) */ first_check_passed.allocate(pb, FMT(annotation_prefix, " first_check_passed")); first_check.reset( new check_e_times_e_over_e_equals_value_gadget<ppT>(pb, *acc_precomp, *(pvk.H_gamma_pc), *proof_C_precomp, *(pvk.H_pc), *proof_A_G_alpha_precomp, *proof_B_H_beta_precomp, *(pvk.G_alpha_H_beta_inv), first_check_passed, FMT(annotation_prefix, " first_check"))); /** * e(A, H^{gamma}) = e(G^{gamma}, B) */ second_check_passed.allocate(pb, FMT(annotation_prefix, " second_check_passed")); second_check.reset( new check_e_equals_e_gadget<ppT>(pb, *proof_A_precomp, *(pvk.H_gamma_pc), *(pvk.G_gamma_pc), *proof_B_precomp, second_check_passed, FMT(annotation_prefix, " second_check"))); // final constraint all_test_results.emplace_back(first_check_passed); all_test_results.emplace_back(second_check_passed); all_tests_pass.reset(new conjunction_gadget<FieldT>(pb, all_test_results, result, FMT(annotation_prefix, " all_tests_pass"))); } template<typename ppT> void r1cs_se_ppzksnark_online_verifier_gadget<ppT>::generate_r1cs_constraints() { PROFILE_CONSTRAINTS(this->pb, "accumulate verifier input") { libff::print_indent(); printf("* Number of bits as an input to verifier gadget: %zu\n", input.size()); accumulate_input->generate_r1cs_constraints(); } PROFILE_CONSTRAINTS(this->pb, "rest of the verifier") { compute_proof_A_G_alpha->generate_r1cs_constraints(); compute_proof_B_H_beta->generate_r1cs_constraints(); compute_proof_A_G_alpha_precomp->generate_r1cs_constraints(); compute_proof_B_H_beta_precomp->generate_r1cs_constraints(); compute_acc_precomp->generate_r1cs_constraints(); compute_proof_A_precomp->generate_r1cs_constraints(); compute_proof_B_precomp->generate_r1cs_constraints(); compute_proof_C_precomp->generate_r1cs_constraints(); first_check->generate_r1cs_constraints(); second_check->generate_r1cs_constraints(); all_tests_pass->generate_r1cs_constraints(); } } template<typename ppT> void r1cs_se_ppzksnark_online_verifier_gadget<ppT>::generate_r1cs_witness() { accumulate_input->generate_r1cs_witness(); compute_proof_A_G_alpha->generate_r1cs_witness(); compute_proof_B_H_beta->generate_r1cs_witness(); compute_proof_A_G_alpha_precomp->generate_r1cs_witness(); compute_proof_B_H_beta_precomp->generate_r1cs_witness(); compute_acc_precomp->generate_r1cs_witness(); compute_proof_A_precomp->generate_r1cs_witness(); compute_proof_B_precomp->generate_r1cs_witness(); compute_proof_C_precomp->generate_r1cs_witness(); first_check->generate_r1cs_witness(); second_check->generate_r1cs_witness(); all_tests_pass->generate_r1cs_witness(); } template<typename ppT> r1cs_se_ppzksnark_verifier_gadget<ppT>::r1cs_se_ppzksnark_verifier_gadget(protoboard<FieldT> &pb, const r1cs_se_ppzksnark_verification_key_variable<ppT> &vk, const pb_variable_array<FieldT> &input, const size_t elt_size, const r1cs_se_ppzksnark_proof_variable<ppT> &proof, const pb_variable<FieldT> &result, const std::string &annotation_prefix) : gadget<FieldT>(pb, annotation_prefix) { pvk.reset(new r1cs_se_ppzksnark_preprocessed_r1cs_se_ppzksnark_verification_key_variable<ppT>()); compute_pvk.reset(new r1cs_se_ppzksnark_verifier_process_vk_gadget<ppT>(pb, vk, *pvk, FMT(annotation_prefix, " compute_pvk"))); online_verifier.reset(new r1cs_se_ppzksnark_online_verifier_gadget<ppT>(pb, *pvk, input, elt_size, proof, result, FMT(annotation_prefix, " online_verifier"))); } template<typename ppT> void r1cs_se_ppzksnark_verifier_gadget<ppT>::generate_r1cs_constraints() { PROFILE_CONSTRAINTS(this->pb, "precompute pvk") { compute_pvk->generate_r1cs_constraints(); } PROFILE_CONSTRAINTS(this->pb, "online verifier") { online_verifier->generate_r1cs_constraints(); } } template<typename ppT> void r1cs_se_ppzksnark_verifier_gadget<ppT>::generate_r1cs_witness() { compute_pvk->generate_r1cs_witness(); online_verifier->generate_r1cs_witness(); } } // libsnark #endif // R1CS_SE_PPZKSNARK_VERIFIER_GADGET_TCC_
41.237395
213
0.642417
[ "vector" ]
789a6d619cb3a137cc470a7cf9104f0dc849be5b
11,542
cpp
C++
httpserver/onion_processing.cpp
ilie1988/italo-storage-server
2560fe7cbdf7fe34b1158bd97280603fd5cfa498
[ "MIT" ]
null
null
null
httpserver/onion_processing.cpp
ilie1988/italo-storage-server
2560fe7cbdf7fe34b1158bd97280603fd5cfa498
[ "MIT" ]
null
null
null
httpserver/onion_processing.cpp
ilie1988/italo-storage-server
2560fe7cbdf7fe34b1158bd97280603fd5cfa498
[ "MIT" ]
null
null
null
#include "channel_encryption.hpp" #include "italo_logger.h" #include "request_handler.h" #include "service_node.h" #include "utils.hpp" /// This is only included because of `parse_combined_payload`, /// in the future it will be moved #include "http_connection.h" #include <charconv> #include <variant> using nlohmann::json; namespace italo { /// The request is to be forwarded to another SS node struct RelayToNodeInfo { /// Inner ciphertext for next node std::string ciphertext; // Key to be forwarded to next node for decryption std::string ephemeral_key; // Next node's ed25519 key std::string next_node; }; /// The request is to be forwarded to some non-SS server /// that supports our protocol (e.g. Session File Server) struct RelayToServerInfo { // Result of decryption (intact) std::string payload; // Server's address std::string host; // Request's target std::string target; }; /// We are the final destination for this request struct FinalDesitnationInfo { std::string body; }; enum class ProcessCiphertextError { INVALID_CIPHERTEXT, INVALID_JSON, }; using ParsedInfo = std::variant<RelayToNodeInfo, RelayToServerInfo, FinalDesitnationInfo, ProcessCiphertextError>; static auto process_ciphertext_v1(const ChannelEncryption<std::string>& decryptor, const std::string& ciphertext, const std::string& ephem_key) -> ParsedInfo { std::string plaintext; try { const std::string ciphertext_bin = util::base64_decode(ciphertext); plaintext = decryptor.decrypt_gcm(ciphertext_bin, ephem_key); } catch (const std::exception& e) { ITALO_LOG(debug, "Error decrypting an onion request: {}", e.what()); return ProcessCiphertextError::INVALID_CIPHERTEXT; } ITALO_LOG(debug, "onion request decrypted: (len: {})", plaintext.size()); try { const json inner_json = json::parse(plaintext, nullptr, true); if (inner_json.find("body") != inner_json.end()) { auto body = inner_json.at("body").get_ref<const std::string&>(); ITALO_LOG(debug, "Found body: <{}>", body); return FinalDesitnationInfo{body}; } else if (inner_json.find("host") != inner_json.end()) { const auto& host = inner_json.at("host").get_ref<const std::string&>(); const auto& target = inner_json.at("target").get_ref<const std::string&>(); return RelayToServerInfo{plaintext, host, target}; } else { // We fall back to forwarding a request to the next node const auto& ciphertext = inner_json.at("ciphertext").get_ref<const std::string&>(); const auto& dest = inner_json.at("destination").get_ref<const std::string&>(); const auto& ekey = inner_json.at("ephemeral_key").get_ref<const std::string&>(); return RelayToNodeInfo{ciphertext, ekey, dest}; } } catch (std::exception& e) { ITALO_LOG(debug, "Error parsing inner JSON in onion request: {}", e.what()); return ProcessCiphertextError::INVALID_JSON; } } static auto process_ciphertext_v2(const ChannelEncryption<std::string>& decryptor, const std::string& ciphertext, const std::string& ephem_key) -> ParsedInfo { std::string plaintext; try { plaintext = decryptor.decrypt_gcm(ciphertext, ephem_key); } catch (const std::exception& e) { ITALO_LOG(debug, "Error decrypting an onion request: {}", e.what()); return ProcessCiphertextError::INVALID_CIPHERTEXT; } ITALO_LOG(debug, "onion request decrypted: (len: {})", plaintext.size()); const auto parsed = parse_combined_payload(plaintext); try { const json inner_json = json::parse(parsed.json, nullptr, true); /// Kind of unfortunate that we use "headers" (which is empty) /// to identify we are the final destination... if (inner_json.find("headers") != inner_json.end()) { ITALO_LOG(trace, "Found body: <{}>", parsed.ciphertext); /// In v2 the body is parsed.ciphertext return FinalDesitnationInfo{parsed.ciphertext}; } else if (inner_json.find("host") != inner_json.end()) { const auto& host = inner_json.at("host").get_ref<const std::string&>(); const auto& target = inner_json.at("target").get_ref<const std::string&>(); return RelayToServerInfo{plaintext, host, target}; } else { // We fall back to forwarding a request to the next node const auto& dest = inner_json.at("destination").get_ref<const std::string&>(); const auto& ekey = inner_json.at("ephemeral_key").get_ref<const std::string&>(); return RelayToNodeInfo{parsed.ciphertext, ekey, dest}; } } catch (std::exception& e) { ITALO_LOG(debug, "Error parsing inner JSON in onion request: {}", e.what()); return ProcessCiphertextError::INVALID_JSON; } } static auto gateway_timeout() -> italo::Response { return italo::Response{Status::GATEWAY_TIMEOUT, "Request time out"}; } static auto make_status(std::string_view status) -> italo::Status { int code; auto res = std::from_chars(status.data(), status.data() + status.size(), code); if (res.ec == std::errc::invalid_argument || res.ec == std::errc::result_out_of_range) { return Status::INTERNAL_SERVER_ERROR; } switch (code) { case 200: return Status::OK; case 400: return Status::BAD_REQUEST; case 403: return Status::FORBIDDEN; case 406: return Status::NOT_ACCEPTABLE; case 421: return Status::MISDIRECTED_REQUEST; case 432: return Status::INVALID_POW; case 500: return Status::INTERNAL_SERVER_ERROR; case 502: return Status::BAD_GATEWAY; case 503: return Status::SERVICE_UNAVAILABLE; case 504: return Status::GATEWAY_TIMEOUT; default: return Status::INTERNAL_SERVER_ERROR; } } static void relay_to_node(const ServiceNode& service_node, const RelayToNodeInfo& info, std::function<void(italo::Response)> cb, int req_idx, bool v2) { const auto& dest = info.next_node; const auto& payload = info.ciphertext; const auto& ekey = info.ephemeral_key; auto dest_node = service_node.find_node_by_ed25519_pk(dest); if (!dest_node) { auto msg = fmt::format("Next node not found: {}", dest); ITALO_LOG(warn, "{}", msg); auto res = italo::Response{Status::BAD_GATEWAY, std::move(msg)}; cb(std::move(res)); return; } nlohmann::json req_body; req_body["ciphertext"] = payload; req_body["ephemeral_key"] = ekey; auto on_response = [cb, &service_node](bool success, std::vector<std::string> data) { // Processing the result we got from upstream if (!success) { ITALO_LOG(debug, "[Onion request] Request time out"); cb(gateway_timeout()); return; } // We only expect a two-part message if (data.size() != 2) { ITALO_LOG(debug, "[Onion request] Incorrect number of messages: {}", data.size()); cb(italo::Response{Status::INTERNAL_SERVER_ERROR, "Incorrect number of messages from gateway"}); return; } /// We use http status codes (for now) if (data[0] != "200") { ITALO_LOG(debug, "Onion request relay failed with: {}", data[1]); } cb(italo::Response{make_status(data[0]), std::move(data[1])}); }; ITALO_LOG(debug, "send_onion_to_sn, sn: {} reqidx: {}", *dest_node, req_idx); if (v2) { service_node.send_onion_to_sn_v2(*dest_node, payload, ekey, on_response); } else { service_node.send_onion_to_sn_v1(*dest_node, payload, ekey, on_response); } } void RequestHandler::process_onion_req(const std::string& ciphertext, const std::string& ephem_key, std::function<void(italo::Response)> cb, bool v2) { if (!service_node_.snode_ready()) { auto msg = fmt::format("Snode not ready: {}", service_node_.own_address().pubkey_ed25519_hex()); cb(italo::Response{Status::SERVICE_UNAVAILABLE, std::move(msg)}); return; } ITALO_LOG(debug, "process_onion_req, v2: {}", v2); static int counter = 0; ParsedInfo res; if (v2) { res = process_ciphertext_v2(this->channel_cipher_, ciphertext, ephem_key); } else { res = process_ciphertext_v1(this->channel_cipher_, ciphertext, ephem_key); } if (const auto info = std::get_if<FinalDesitnationInfo>(&res)) { ITALO_LOG(debug, "We are the final destination in the onion request!"); this->process_onion_exit( ephem_key, info->body, [this, ephem_key, cb = std::move(cb)](italo::Response res) { auto wrapped_res = this->wrap_proxy_response( res, ephem_key, true /* use aes gcm */); cb(std::move(wrapped_res)); }); return; } else if (const auto info = std::get_if<RelayToNodeInfo>(&res)) { relay_to_node(this->service_node_, *info, std::move(cb), counter++, v2); } else if (const auto info = std::get_if<RelayToServerInfo>(&res)) { ITALO_LOG(debug, "We are to forward the request to url: {}{}", info->host, info->target); const auto& target = info->target; // Forward the request to url but only if it ends in `/lsrpc` if ((target.rfind("/lsrpc") == target.size() - 6) && (target.find('?') == std::string::npos)) { this->process_onion_to_url(info->host, target, info->payload, std::move(cb)); } else { auto res = italo::Response{Status::BAD_REQUEST, "Invalid url"}; auto wrapped_res = this->wrap_proxy_response(res, ephem_key, true); cb(std::move(wrapped_res)); } } else if (const auto error = std::get_if<ProcessCiphertextError>(&res)) { switch (*error) { case ProcessCiphertextError::INVALID_CIPHERTEXT: { // Should this error be propagated back to the client? (No, if we // couldn't decrypt, we probably won't be able to encrypt either.) cb(italo::Response{Status::BAD_REQUEST, "Invalid ciphertext"}); break; } case ProcessCiphertextError::INVALID_JSON: { auto res = italo::Response{Status::BAD_REQUEST, "Invalid json"}; auto wrapped_res = this->wrap_proxy_response(res, ephem_key, true); cb(std::move(wrapped_res)); break; } } } else { ITALO_LOG(error, "UNKNOWN VARIANT"); } } } // namespace italo
33.071633
81
0.587073
[ "vector" ]
789c315a34d981e74fbaf7f3d15d12e55c2c850f
2,292
cc
C++
services/ui/ws/event_targeter.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
services/ui/ws/event_targeter.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
services/ui/ws/event_targeter.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/ws/event_targeter.h" #include "base/command_line.h" #include "base/metrics/user_metrics.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "components/viz/common/features.h" #include "components/viz/host/hit_test/hit_test_query.h" #include "services/ui/common/switches.h" #include "services/ui/ws/event_location.h" #include "services/ui/ws/event_targeter_delegate.h" #include "ui/gfx/geometry/point_conversions.h" namespace ui { namespace ws { EventTargeter::EventTargeter(EventTargeterDelegate* event_targeter_delegate) : event_targeter_delegate_(event_targeter_delegate), weak_ptr_factory_(this) {} EventTargeter::~EventTargeter() {} void EventTargeter::FindTargetForLocation(EventSource event_source, const EventLocation& event_location, HitTestCallback callback) { // TODO(riajiang): After the async ask-client part is implemented, the async // part should be moved to after sync viz-hit-test call. if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseAsyncEventTargeting)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&EventTargeter::FindTargetForLocationNow, weak_ptr_factory_.GetWeakPtr(), event_source, event_location, base::Passed(&callback))); } else { FindTargetForLocationNow(event_source, event_location, std::move(callback)); } } void EventTargeter::FindTargetForLocationNow( EventSource event_source, const EventLocation& event_location, HitTestCallback callback) { ServerWindow* root = event_targeter_delegate_->GetRootWindowForDisplay( event_location.display_id); DeepestWindow deepest_window; if (root) { deepest_window = ui::ws::FindDeepestVisibleWindowForLocation( root, event_source, gfx::ToFlooredPoint(event_location.raw_location)); } std::move(callback).Run(event_location, deepest_window); } } // namespace ws } // namespace ui
38.847458
80
0.722077
[ "geometry" ]
789f3dde7a8070d065bece5dfd72e74278f65bce
5,810
cpp
C++
argos3/src/plugins/robots/generic/simulator/radios_default_actuator.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
null
null
null
argos3/src/plugins/robots/generic/simulator/radios_default_actuator.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
1
2021-02-28T23:45:32.000Z
2021-02-28T23:45:32.000Z
argos3/src/plugins/robots/generic/simulator/radios_default_actuator.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
7
2021-02-26T16:41:06.000Z
2022-01-19T21:36:31.000Z
/** * @file <argos3/plugins/robots/generic/simulator/radios_default_actuator.cpp> * * @author Michael Allwright - <allsey87@gmail.com> */ #include "radios_default_actuator.h" #include <argos3/plugins/simulator/media/radio_medium.h> #include <argos3/plugins/simulator/entities/radio_equipped_entity.h> namespace argos { /****************************************/ /****************************************/ CRadiosDefaultActuator::CRadiosDefaultActuator() : m_pcRadioEquippedEntity(nullptr) { } /****************************************/ /****************************************/ void CRadiosDefaultActuator::SetRobot(CComposableEntity& c_entity) { try { /* Get and enable omndirectional radio equipped entity */ m_pcRadioEquippedEntity = &(c_entity.GetComponent<CRadioEquippedEntity>("radios")); /* Create a configuration settings for each radio in the container */ m_vecInterfaces.reserve(m_pcRadioEquippedEntity->GetInstances().size()); /* Populate the descriptors */ for(CRadioEquippedEntity::SInstance& s_instance : m_pcRadioEquippedEntity->GetInstances()) { m_vecInterfaces.emplace_back(s_instance.Radio.GetId()); } } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Can't set robot for the radios default actuator", ex); } } /****************************************/ /****************************************/ void CRadiosDefaultActuator::Init(TConfigurationNode& t_tree) { try { /* Parent class init */ CCI_RadiosActuator::Init(t_tree); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing the radios default actuator", ex); } } /****************************************/ /****************************************/ void CRadiosDefaultActuator::Update() { for(size_t i = 0; i < m_vecInterfaces.size(); ++i) { CRadioEntity& cRadio = m_pcRadioEquippedEntity->GetRadio(i); /* Create operation instance */ CTxOperation cTxOperation(cRadio, m_vecInterfaces[i].Data); /* Calculate the range of the transmitting radio */ CVector3 cTxRange(1.0f,1.0f,1.0f); cTxRange *= (cRadio.GetRange() * 0.5f); /* Get positional index */ CPositionalIndex<CRadioEntity>* pcRadioIndex = &(cRadio.GetMedium().GetIndex()); /* Transmit the data to receiving radios in the space */ pcRadioIndex->ForEntitiesInBoxRange(cRadio.GetPosition(), cTxRange, cTxOperation); /* Flush data from the control interface */ m_vecInterfaces[i].Data.clear(); } } /****************************************/ /****************************************/ void CRadiosDefaultActuator::Reset() { for(SInterface& s_interface : m_vecInterfaces) { /* Clear any data in the interface */ s_interface.Data.clear(); } } /****************************************/ /****************************************/ CRadiosDefaultActuator::CTxOperation::CTxOperation(const CRadioEntity& c_tx_radio, const std::vector<CByteArray>& c_tx_data) : m_cTxRadio(c_tx_radio), m_cTxData(c_tx_data) {} /****************************************/ /****************************************/ bool CRadiosDefaultActuator::CTxOperation::operator()(CRadioEntity& c_rx_radio) { if(&c_rx_radio != &m_cTxRadio) { const CVector3& cRxRadioPosition = c_rx_radio.GetPosition(); const CVector3& cTxRadioPosition = m_cTxRadio.GetPosition(); Real fDistance = (cRxRadioPosition - cTxRadioPosition).Length(); if(fDistance < m_cTxRadio.GetRange()) { for(const CByteArray& c_data : m_cTxData) { c_rx_radio.ReceiveData(cTxRadioPosition, c_data); } } } return true; } /****************************************/ /****************************************/ REGISTER_ACTUATOR(CRadiosDefaultActuator, "radios", "default", "Michael Allwright [allsey87@gmail.com]", "1.0", "A generic radio actuator to send messages to nearby radios.", "This radio actuator implementation allows an arbitary number of messages\n" "containing an arbitary number of bytes to be sent to nearby radios. The\n" "implementation of this actuator is very basic and any concepts such as\n" "throughput, addressing, or formatting of a message's contents is beyond the\n" "scope of this actuator's implementation.\n\n" "REQUIRED XML CONFIGURATION\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <actuators>\n" " ...\n" " <radios implementation=\"default\" medium=\"radios\" />\n" " ...\n" " </actuators>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "The 'medium' attribute sets the id of the radio medium declared in the <media>\n" "XML section.\n\n" "OPTIONAL XML CONFIGURATION\n\n" "None.\n", "Usable" ); /****************************************/ /****************************************/ }
38.223684
103
0.492599
[ "vector" ]
a194a2ba3889385febac108b17502c3bf1663058
7,060
cpp
C++
main.cpp
friedrich12/dokucoin
c3177719303ddd346fd64375ce029203099b4765
[ "MIT" ]
null
null
null
main.cpp
friedrich12/dokucoin
c3177719303ddd346fd64375ce029203099b4765
[ "MIT" ]
null
null
null
main.cpp
friedrich12/dokucoin
c3177719303ddd346fd64375ce029203099b4765
[ "MIT" ]
null
null
null
// author: tko #include <iostream> #include <sstream> #include <string> #include <vector> #include <memory> #include <stdexcept> #include "hash.cpp" #include "Block.cpp" #include "common.cpp" #include "BlockChain.cpp" #include "requests.cpp" #include "json.h" using json = nlohmann::json; using namespace std; #include "client_http.cpp" #include "server_http.cpp" using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>; using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>; /* Hash header: index + prevHash + merkleRoot(data) + nonce */ /* * Main function - sets up server, command line interface */ int main() { printf("Welcome! To quit-> Control c \n"); HttpServer server; // Set up ports int port; printf("Enter port: "); scanf("%d",&port); server.config.port = port; //server port vector<int> listOfNodes; //vector of the ports of nodes in the network // BLOCK CHAIN INITIALIZATION AND ADDING SELF TO NETWORK char ch; printf("Are you the initial Node? (y or n) "); scanf(" %c",&ch); BlockChain bc; if (ch == 'y'){ // Initial Node: setup Blockchain with genesis block bc = BlockChain(0); } else if(ch =='n'){ // New Node - need to add self to network by providing ports bc = BlockChain(0); char otherPorts[50]; // Example input: 8000,3000,3030 printf("Enter ports of nodes in network(with commas in between): "); scanf("%s",otherPorts); stringstream ss(otherPorts); int i; // parse string of nodes and add them to listOfNoes while (ss >> i) { listOfNodes.push_back(i); if (ss.peek() == ',' || ss.peek() == ' ') ss.ignore(); } addSelfToNetwork(&listOfNodes,server.config.port); json chain = getChainFromNodes(&listOfNodes); //skips first block - same genesis block across all nodes for (int a = 1; a <chain["length"].get<int>(); a++ ){ auto block = chain["data"][a]; vector<string> data = block["data"].get<vector<string> >(); bc.addBlock(block["index"],block["previousHash"],block["hash"],block["nonce"],data); } } else { return 0; } // SERVER INITIALIZATION /* POST /addnode - used to add node to network, called by new node to all the nodes in the network * adds node(port) to listOfNodes */ server.resource["^/addnode$"]["POST"] = [&listOfNodes](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) { printf("POST /addnode --- New Node adding to network....\n"); try { json content = json::parse(request->content); int port = content["port"].get<int>(); listOfNodes.push_back(port); // Adds port to listOfNodes printf("----Adding node %d to listOfNodes\n",port); response->write("Added You to our List"); } catch(const exception &e) { *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what(); } }; /* GET /latestchain gets latest blockchain and sends it*/ server.resource["^/latestchain$"]["GET"] = [&bc](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) { printf("GET /latestchain --- Sending BlockChain....\n"); response->write(bc.toJSON()); printf("---Sent current BlockChain\n"); }; /* POST /newchain called by a node when a new block is added to it - * checks whether the length of the blockchain is bigger than our own blockchain * if it is bigger -> replace chain, else don't do anything */ server.resource["^/newchain$"]["POST"] = [&bc](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) { cout << "POST /newchain --- Node in Network sent new chain\n"; try { json content = json::parse(request->content); if (content["length"].get<int>() > bc.getNumOfBlocks()){ bc.replaceChain(content); cout << "----Replaced current chain with new one" << endl; response->write("Replaced Chain\n"); } else { cout << "----Chain was not replaced: sent chain had same size" <<endl; response->write("Same Chain Size -- invalid"); } } catch(const exception &e) { *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what(); } }; // On error lambda function server.on_error = [](shared_ptr<HttpServer::Request> /*request*/, const SimpleWeb::error_code & ec) { if (ec.message() != "End of file") { cout << "SERVER ERROR: " << ec.message() << endl; } }; printf("Starting server at %d",server.config.port); // start server thread server_thread([&server]() { server.start(); }); //COMMAND LINE INTERFACE // loop for 20 inputs - can change for ( int i = 0; i < 20; i++ ) { vector<string> v; int temp; // ask for what to do printf("\n(1) Look at Blocks \n(2) Add block\n"); int valid = scanf("%d",&temp); if ( (valid == 1) && (temp == 1)){ // queue up block if 1 printf("What Block do you want to look at? "); scanf("%d",&temp); try { bc.getBlock(temp).toString(); } catch (const exception& e){ cout << e.what() << endl; } } else if (temp == 2){ // add a new block if 2 char tmp[201]; printf("\nADDING BLOCKS!\nEnter your message: "); scanf("%200s",tmp); string str = tmp; printf("Entered '%s' into block\n",str.c_str()); v.push_back(str); int in; printf("Press any number to add block to blockchain: "); scanf("%d",&in); try { if (bc.getNumOfBlocks() == 0) { printf("----------------------------------\nPlease join the network... Your blockchain doesn't have any blocks "); continue; } // mine for the has auto pair = findHash(bc.getNumOfBlocks(),bc.getLatestBlockHash(),v); // add the block to the blockchain bc.addBlock(bc.getNumOfBlocks(),bc.getLatestBlockHash(),pair.first,pair.second,v ); // send the blockchain to the network sendNewChain(&listOfNodes,bc.toJSON()); } catch (const exception& e) { cout << e.what() << "\n" << endl; } } } // bc.addBlock(0,string("00000000000000"),string("003d9dc40cad6b414d45555e4b83045cfde74bcee6b09fb42536ca2500087fd9"),string("46"),v); printf("\n"); return 0; }
34.607843
144
0.55
[ "vector" ]
a196b5d223cd64f3a58c83931a426154353a547c
8,934
cpp
C++
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImporter.cpp
stickyparticles/lumberyard
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
2
2018-03-29T10:56:36.000Z
2020-12-12T15:28:14.000Z
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImporter.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxImporter.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
3
2019-05-13T09:41:33.000Z
2021-04-09T12:12:38.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <queue> #include <AzCore/Debug/Trace.h> #include <AzCore/Math/Transform.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/std/containers/queue.h> #include <AzCore/std/string/string.h> #include <AzCore/std/smart_ptr/make_shared.h> #include <AzToolsFramework/Debug/TraceContext.h> #include <SceneAPI/FbxSceneBuilder/FbxImporter.h> #include <SceneAPI/FbxSceneBuilder/ImportContexts/FbxImportContexts.h> #include <SceneAPI/FbxSceneBuilder/Importers/FbxImporterUtilities.h> #include <SceneAPI/FbxSDKWrapper/FbxSceneWrapper.h> #include <SceneAPI/FbxSDKWrapper/FbxMeshWrapper.h> #include <SceneAPI/SceneCore/Containers/Scene.h> #include <SceneAPI/SceneCore/Containers/SceneGraph.h> #include <SceneAPI/SceneCore/Utilities/Reporting.h> #include <SceneAPI/SceneData/GraphData/TransformData.h> namespace AZ { namespace SceneAPI { namespace FbxSceneBuilder { struct QueueNode { std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper> m_node; Containers::SceneGraph::NodeIndex m_parent; QueueNode() = default; QueueNode(std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper>&& node, Containers::SceneGraph::NodeIndex parent) : m_node(std::move(node)) , m_parent(parent) { } }; FbxImporter::FbxImporter() : m_sceneWrapper(new FbxSDKWrapper::FbxSceneWrapper()) , m_sceneSystem(new FbxSceneSystem()) { BindToCall(&FbxImporter::ImportProcessing); } void FbxImporter::Reflect(ReflectContext* context) { SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context); if (serializeContext) { serializeContext->Class<FbxImporter, SceneCore::LoadingComponent>()->Version(1); } } Events::ProcessingResult FbxImporter::ImportProcessing(Events::ImportEventContext& context) { m_sceneWrapper->Clear(); if (!m_sceneWrapper->LoadSceneFromFile(context.GetInputDirectory().c_str())) { return Events::ProcessingResult::Failure; } m_sceneSystem->Set(*m_sceneWrapper); if (ConvertFbxSceneContext(context.GetScene())) { return Events::ProcessingResult::Success; } else { return Events::ProcessingResult::Failure; } } bool FbxImporter::ConvertFbxSceneContext(Containers::Scene& scene) const { std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper> fbxRoot = m_sceneWrapper->GetRootNode(); if (!fbxRoot) { return false; } AZStd::queue<FbxSceneBuilder::QueueNode> nodes; nodes.emplace(AZStd::move(fbxRoot), scene.GetGraph().GetRoot()); while (!nodes.empty()) { FbxSceneBuilder::QueueNode& node = nodes.front(); AZ_Assert(node.m_node, "Empty fbx node queued"); AZ_TraceContext("Source Node Name", node.m_node->GetName()); Containers::SceneGraph::NodeIndex newNode = scene.GetGraph().AddChild(node.m_parent, node.m_node->GetName()); AZ_Assert(newNode.IsValid(), "Failed to add node to scene graph"); if (!newNode.IsValid()) { continue; } FbxNodeEncounteredContext sourceNodeEncountered(scene, newNode, *m_sceneWrapper, *m_sceneSystem, *node.m_node); Events::ProcessingResultCombiner nodeResult; nodeResult += Events::Process(sourceNodeEncountered); // If no importer created data, we still create an empty node that may eventually contain a transform if (sourceNodeEncountered.m_createdData.empty()) { AZ_Assert(nodeResult.GetResult() != Events::ProcessingResult::Success, "Importers returned success but no data was created"); AZStd::shared_ptr<DataTypes::IGraphObject> nullData(nullptr); sourceNodeEncountered.m_createdData.emplace_back(nullData); nodeResult += Events::ProcessingResult::Success; } // Create single node since only one piece of graph data was created if (sourceNodeEncountered.m_createdData.size() == 1) { AZ_Assert(nodeResult.GetResult() != Events::ProcessingResult::Ignored, "An importer created data, but did not return success"); if (nodeResult.GetResult() == Events::ProcessingResult::Failure) { AZ_TracePrintf(Utilities::WarningWindow, "One or more importers failed to create data."); } SceneDataPopulatedContext dataProcessed(sourceNodeEncountered, sourceNodeEncountered.m_createdData[0], node.m_node->GetName()); Events::ProcessingResult result = AddDataNodeWithContexts(dataProcessed); if (result != Events::ProcessingResult::Failure) { newNode = dataProcessed.m_currentGraphPosition; } } // Create an empty parent node and place all data under it. The remaining // tree will be built off of this as the logical parent else { AZ_Assert(nodeResult.GetResult() != Events::ProcessingResult::Ignored, "%i importers created data, but did not return success", sourceNodeEncountered.m_createdData.size()); if (nodeResult.GetResult() == Events::ProcessingResult::Failure) { AZ_TracePrintf(Utilities::WarningWindow, "One or more importers failed to create data."); } for (size_t i = 0; i < sourceNodeEncountered.m_createdData.size(); ++i) { AZStd::string nodeName = node.m_node->GetName() + (i + 1); Containers::SceneGraph::NodeIndex subNode = scene.GetGraph().AddChild(newNode, nodeName.c_str()); AZ_Assert(subNode.IsValid(), "Failed to create new scene sub node"); SceneDataPopulatedContext dataProcessed(sourceNodeEncountered, sourceNodeEncountered.m_createdData[i], nodeName); dataProcessed.m_currentGraphPosition = subNode; AddDataNodeWithContexts(dataProcessed); } } AZ_Assert(nodeResult.GetResult() == Events::ProcessingResult::Success, "No importers successfully added processed scene data."); AZ_Assert(newNode != node.m_parent, "Failed to update current graph position during data processing."); int childCount = node.m_node->GetChildCount(); for (int i = 0; i < childCount; ++i) { std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper> child = node.m_node->GetChild(i); if (child) { nodes.emplace(AZStd::move(child), newNode); } } nodes.pop(); } return true; } } // namespace FbxSceneBuilder } // namespace SceneAPI } // namespace AZ
46.051546
131
0.542646
[ "transform" ]
a1a36b926142442ad10b0f35e33a356b306d406c
934
cpp
C++
twoPointers/maxContinousSeriesOf1.cpp
archit-1997/InterviewB
6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7
[ "MIT" ]
1
2021-01-27T16:37:38.000Z
2021-01-27T16:37:38.000Z
twoPointers/maxContinousSeriesOf1.cpp
archit-1997/InterviewBit
6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7
[ "MIT" ]
null
null
null
twoPointers/maxContinousSeriesOf1.cpp
archit-1997/InterviewBit
6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7
[ "MIT" ]
null
null
null
vector<int> Solution::maxone(vector<int> &v, int b) { int n = v.size(); vector<int> zero; int index = -1; int l = 0, r = 0, count = 0; int left = 0, right = 0; vector<int> ans; int len = INT_MIN; while (l <= r && r < n) { while (r < n) { if (v[r] == 0) { zero.push_back(r); count++; } // now we have to exclude this zero if (count > b) break; // move on to the next number r++; } // update the max length which is possible if (r - l > len) { len = r - l; left = l, right = r; } // if we have reached the end, then you can just break from the loop if (r == n && count <= b) break; // take out the leftmost zero index++; while (l != zero[index]) l++; l++, r++; count--; } if (len == INT_MIN) return ans; for (int i = left; i < right; i++) ans.push_back(i); return ans; }
21.72093
72
0.486081
[ "vector" ]
a1a4384e6b2d5c4d423bd3e885daae7bcda28f23
2,501
cpp
C++
src/main/bitbucket/PullRequestFormatter.cpp
TNG/mustard-cli
aa8db4e923271546b46a1f9a71778b3bed1efe3a
[ "Apache-2.0" ]
7
2019-04-12T07:13:32.000Z
2021-09-22T20:53:44.000Z
src/main/bitbucket/PullRequestFormatter.cpp
TNG/mustard-cli
aa8db4e923271546b46a1f9a71778b3bed1efe3a
[ "Apache-2.0" ]
2
2020-07-21T05:01:13.000Z
2020-08-14T15:38:17.000Z
src/main/bitbucket/PullRequestFormatter.cpp
TNG/mustard-cli
aa8db4e923271546b46a1f9a71778b3bed1efe3a
[ "Apache-2.0" ]
1
2020-07-21T05:03:09.000Z
2020-07-21T05:03:09.000Z
#include <sstream> #include "PullRequestFormatter.h" #include "../system/TextTable.h" string PullRequestFormatter::format ( const PullRequest &pullRequest ) { stringstream ss; ss << pullRequest.fromBranch << " → " << pullRequest.toBranch << " *** " << formatBold << pullRequest.title << formatNormal << " *** " << endl; ss << pullRequest.description << endl << endl; ss << "author: " << formatUser ( pullRequest.author ) << endl; ss << "reviewers: "; bool hasReviewers = false; for ( const auto &reviewer : pullRequest.reviewers ) { if ( !hasReviewers ) { hasReviewers = true; } else { ss << " "; } ss << symbol ( reviewer.status ) << " " << formatUser ( reviewer.user ) << endl; } if ( !hasReviewers ) { ss << " <none>"; } ss << endl << endl; ss << "View in BitBucket: " << pullRequest.url << endl << endl; return ss.str(); } std::ostream &PullRequestFormatter::formatBold ( std::ostream &stream ) { return stream << "\e[1m"; } std::ostream &PullRequestFormatter::formatNormal ( std::ostream &stream ) { return stream << "\e[0m"; } string PullRequestFormatter::symbol ( ReviewStatus status ) { switch ( status ) { case UNAPPROVED: return "[ ]"; case APPROVED: return "[\033[0;32m✓\033[0m]"; case NEEDS_WORK: return "[\033[0;31m✗\033[0m]"; } } string PullRequestFormatter::formatUser ( const User &user ) { stringstream ss; ss << formatBold << user.displayName << formatNormal << " <" << user.eMail << ">"; return ss.str(); } string PullRequestFormatter::shortFormat ( const vector<PullRequest> &pullRequests, function<bool ( const PullRequest & ) > highlight ) { TextTable textTable ( 5 ); for ( const auto &pullRequest : pullRequests ) { stringstream hooks, project, title, author, fromTo; for ( const auto &reviewer : pullRequest.reviewers ) { hooks << symbol ( reviewer.status ); } project << ( highlight ( pullRequest ) ? formatBold : formatNormal ) << pullRequest.project << "/" << pullRequest.repoSlug << formatNormal; fromTo << pullRequest.fromBranch << " → " << pullRequest.toBranch; title << pullRequest.title; author << formatUser ( pullRequest.author ); textTable.addRow ( {hooks.str(), project.str(), fromTo.str(), title.str(), author.str() } ); } return textTable.getTable(); }
33.346667
147
0.594562
[ "vector" ]
a1ad67b852a1500732a386723eef8dd89cf2e001
8,597
cpp
C++
4-FinalProduct/src/FinalProduct.cpp
acharroux/Photon-Particle-Workshop
820c25eb290a141f9473d63d9914d683cf078f95
[ "MIT" ]
2
2021-03-09T17:29:56.000Z
2021-08-17T23:09:03.000Z
4-FinalProduct/src/FinalProduct.cpp
acharroux/Photon-Particle-Workshop
820c25eb290a141f9473d63d9914d683cf078f95
[ "MIT" ]
null
null
null
4-FinalProduct/src/FinalProduct.cpp
acharroux/Photon-Particle-Workshop
820c25eb290a141f9473d63d9914d683cf078f95
[ "MIT" ]
null
null
null
/* * Project ShowStatus * Description: Manage a sonar and a display panel. Final product * Author: Alain Charroux * Date: 24/04/2019 */ #include "application.h" #include "Adafruit_SSD1306/Adafruit_SSD1306.h" #include "HC_SR04.h" #include "SoftwareState.h" #include "WifiPanel.h" #include "SoftwarePanel.h" /***************************************************************** * Product identification * these are the only changes to do to activate the product management */ // The product id as given by Particle's admin console // It won't change for the whole lifetime of the product PRODUCT_ID(8925); // the product version. It has to be incremented each time a // new reference version is deployed via Particle's admin console PRODUCT_VERSION(1); /************************************************************************************************* HARDWARE SECTION ************************************************************************************************/ #if (SSD1306_LCDHEIGHT != 64) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif // I2C address used by our hardware #define OLED_I2C_ADDRESS 0x3C // not used but looks like it still has to be provided to adafruit lib // Default is probably D4 but we plan to use this pin for other purpose #define OLED_RESET D3 static Adafruit_SSD1306 gDisplay(OLED_RESET); #define TRIG_PIN D4 #define ECHO_PIN D5 // Our hardware : only a basic HC-SR04 static HC_SR04 gSonar = HC_SR04(TRIG_PIN, ECHO_PIN); /************************************************************************************************* * SOFTWARE STATUS SECTION ************************************************************************************************/ static SoftwareState gSoftwareState; /************************************************************************************************* * PANELS SECTION ************************************************************************************************/ // a little bit risky to be confident on order of init of global variables // but so easy ... /** this will display infos about the wifi connection */ static WifiPanel gWifiPanel(gDisplay); /** this will display infos about the current firmware and internal state */ static SoftwarePanel gSoftwarePanel(gDisplay, gSoftwareState); /** for simplicity we will manage the display of the current panel via a naive pointer */ static Panel *gCurrentPanel = NULL; /************************************************************************************************* CLOUD SECTION ************************************************************************************************/ /**************************************************** * one simple function to force the current panel * for demonstration purpose, forcing the panel * will be signaled by an event */ static bool forcePanel(String iPanelName) { bool lKnownPanel = false; // not very efficient char to string conversion but much clearer if (iPanelName == "Wifi") { lKnownPanel = true; gCurrentPanel = &gWifiPanel; } if (iPanelName == "Software") { lKnownPanel = true; gCurrentPanel = &gSoftwarePanel; } if (lKnownPanel) { gCurrentPanel->refreshValues(); gCurrentPanel->display(); Particle.publish("PanelRequested", iPanelName, PRIVATE); // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackSentEvent(); return true; } else { // unknown panel Particle.publish("UnknownPanelRequested", iPanelName, PRIVATE); // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackSentEvent(); return false; } } // the led pattern we will use to signal a valid range static LEDStatus gValidRangeStatus; /** * be very vocal about the provided probe **/ static void signalValidRange(double iRange) { /** 1 flash the system led with our pattern */ gValidRangeStatus.setActive(true); /** 2 publish our event "InterestingRange" **/ Particle.publish("ValidRange", String::format("%.2f", iRange), PRIVATE); // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackSentEvent(); delay(200); /** 3 get back to standard system led pattern **/ gValidRangeStatus.setActive(false); } /** * various event handlers * subscription will be done to MY_DEVICES : only events explicitely sent to my devices * will be catched */ /**************************************************************** * send infos about us to the cloud */ static void WhoIsConnectedEventHandler(const char *event, const char *data) { // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackEventReceived(); Particle.publish("Connected", gSoftwarePanel.JSONDump(data)); } /****************************************************************/ /* change the display of the Wifi panel data provides the name of the panel to display */ static void ChangePanelEventHandler(const char *event, const char *data) { // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackEventReceived(); forcePanel(data); } /****************************************************************/ static void ForceOTAEventHandler(const char *event, const char *data) { // for demonstration purpose, we try to track every activity related to cloud gSoftwareState.trackEventReceived(); // obviously a true product would make much more checks before accepting to reboot like this // only for demonstration purpose !! Particle.publish("OTARequested", "", PRIVATE); System.reset(); } /** * declare cloud functions. * functions are quite similar to events except it can be called only for one photon at a time * events can target all devices in the world (!), or all of your devices or a specific device */ static int ChangePanelFunction(String iPanelName) { return static_cast<bool>(forcePanel(iPanelName)); } void setup() { // hardware setup // Panels // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) gDisplay.begin(SSD1306_SWITCHCAPVCC, OLED_I2C_ADDRESS); // initialize with the I2C addr (for the 128x64) // there are some init that have to be done AFTER connection // and setup is called after connection gWifiPanel.initAfterConnect(); gSoftwarePanel.initAfterConnect(); // SR104 object has been already setup by ts constructor // but we need to setup a little bit the status led used by our usage of SR104 // our 'interesting range' LEDStatus needs to be tuned before actual usage // Orange, blinking fast gValidRangeStatus.setColor(RGB_COLOR_RED); gValidRangeStatus.setPattern(LED_PATTERN_BLINK); gValidRangeStatus.setSpeed(LED_SPEED_FAST); gValidRangeStatus.setPeriod(50); // Cloud registrations // publish the current range // From now, the last range found by gSonar is permanently accessible via the cloud variable named "cm" Particle.variable("cm", gSoftwareState.getRangeVariable()); // register the event that will switch between the 2 panels Particle.subscribe("ChangePanel", ChangePanelEventHandler, MY_DEVICES); // register an event to see who is connected Particle.subscribe("WhoIsConnected", WhoIsConnectedEventHandler, MY_DEVICES); /* register the function that will force a panel to be displayed */ Particle.function("ChangePanel", ChangePanelFunction); // automatic product OTA is done each time a big cloud handshake is done // such handshake is done on various triggers. Amongst them, there are // -> power off/on // -> a call to System.reset // -> every XXX hours (XXXdepending on platform and other obscure conditions) // // The last one is the smartest one : it will retain current permanent variables // but it is defintely the least immediate. /// We will force a rest when requested via event ForceOTA // Note there is a new feature in beta that will trigger 'immediate' product OTA // register the event that will force an OTA on all devices Particle.subscribe("ForceOTA", ForceOTAEventHandler, MY_DEVICES); // start with the software panel forcePanel("Software"); } // loop() runs over and over again, as quickly as it can execute. void loop() { double lRange = gSonar.getDistanceCM(); gSoftwareState.setRange(lRange); if (gSoftwareState.rangeIsValidForALongTime()) { signalValidRange(gSoftwareState.getRange()); } gCurrentPanel->refreshValues(); gCurrentPanel->display(); delay(100); }
32.812977
107
0.644527
[ "object" ]
a1ae98ff195f52a4638f9531b8b6df6f4cdc9762
1,141
cpp
C++
#0842.split-array-into-fibonacci-sequence.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
#0842.split-array-into-fibonacci-sequence.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
#0842.split-array-into-fibonacci-sequence.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
class Solution { public: vector<int> splitIntoFibonacci(string num) { vector<int> v; isSplitIntoFibonacci(v, num, num.length(), 0, 0, 0); return v; } private: bool isSplitIntoFibonacci( vector<int> &v, string num, int length, int index, long long sum, int prev) { if (index == length) { return v.size() >= 3; } long long cur = 0; for (int i = index; i < length; ++i) { if (i > index && num[index]=='0') { break; } cur = cur * 10 + num[i] - '0'; if (cur > INT_MAX) { break; } if (v.size() >= 2) { if (cur<sum) { continue; } if (cur>sum) { break; } } v.push_back(cur); if (isSplitIntoFibonacci(v, num, length, i + 1, prev + cur, cur)) { return true; } v.pop_back(); } return false; } };
21.528302
79
0.373357
[ "vector" ]
a1afcbf06a389b402b2c7ab1116bcbba1cb38955
8,233
cc
C++
src/sst/elements/merlin/test/simple_patterns/shift.cc
jleidel/sst-elements
ad60d81078a9a1dca0ffc04411858491953c6a73
[ "BSD-3-Clause" ]
null
null
null
src/sst/elements/merlin/test/simple_patterns/shift.cc
jleidel/sst-elements
ad60d81078a9a1dca0ffc04411858491953c6a73
[ "BSD-3-Clause" ]
null
null
null
src/sst/elements/merlin/test/simple_patterns/shift.cc
jleidel/sst-elements
ad60d81078a9a1dca0ffc04411858491953c6a73
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2009-2019 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2019, NTESS // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include <sst_config.h> #include "sst/elements/merlin/test/simple_patterns/shift.h" #include <unistd.h> #include <sst/core/event.h> #include <sst/core/params.h> #include <sst/core/simulation.h> #include <sst/core/timeLord.h> #include <sst/core/unitAlgebra.h> #include <sst/core/interfaces/simpleNetwork.h> namespace SST { using namespace SST::Interfaces; namespace Merlin { shift_nic::shift_nic(ComponentId_t cid, Params& params) : Component(cid), send_seq(0), recv_seq(0), num_ooo(0), packets_sent(0), packets_recd(0), stalled_cycles(0), send_done(false), recv_done(false), initialized(false), output(Simulation::getSimulation()->getSimulationOutput()) { net_id = params.find<int>("id",-1); if ( net_id == -1 ) { } num_peers = params.find<int>("num_peers",-1); if ( num_peers == -1 ) { } shift = params.find<int>("shift",-1); if ( shift == -1 ) { // Abort } target = (net_id + shift) % num_peers; num_msg = params.find<int>("packets_to_send",10); // std::string packet_size_s = params.find<std::string>("packet_size", "64B"); // UnitAlgebra packet_size(packet_size_s); UnitAlgebra packet_size = params.find<UnitAlgebra>("packet_size", UnitAlgebra("64B")); if ( packet_size.hasUnits("B") ) { packet_size *= UnitAlgebra("8b/B"); } size_in_bits = packet_size.getRoundedValue(); std::string link_bw_s = params.find<std::string>("link_bw"); if ( link_bw_s == "" ) { } UnitAlgebra link_bw(link_bw_s); // remap = params.find<int>("remap", 0); // id = (net_id + remap) % num_peers; // Create a LinkControl object // First see if it is defined in the python link_control = loadUserSubComponent<SST::Interfaces::SimpleNetwork> ("networkIF", ComponentInfo::SHARE_NONE, 1 /* vns */); if ( !link_control ) { // Not defined in python code. Just use default (merlin.reorderlinkcontrol) UnitAlgebra buf_size("1kB"); Params if_params; if_params.insert("networkIF","merlin.linkcontrol"); if_params.insert("networkIF::link_bw",params.find<std::string>("link_bw","2GB/s")); if_params.insert("networkIF::input_buf_size","1kB"); if_params.insert("networkIF::output_buf_size","1kB"); if_params.insert("networkIF::port_name","rtr"); link_control = loadAnonymousSubComponent<SST::Interfaces::SimpleNetwork> ("merlin.reorderlinkcontrol", "networkIF", 0, ComponentInfo::SHARE_PORTS | ComponentInfo::INSERT_STATS, if_params, 1 /* vns */); } // Register a clock registerClock( "1GHz", new Clock::Handler<shift_nic>(this,&shift_nic::clock_handler), false); link_control->setNotifyOnReceive(new SST::Interfaces::SimpleNetwork::Handler<shift_nic>(this,&shift_nic::handle_event)); registerAsPrimaryComponent(); primaryComponentDoNotEndSim(); } shift_nic::~shift_nic() { delete link_control; } void shift_nic::finish() { link_control->finish(); if ( num_ooo > 0 ) output.output("Nic %d had %d out of order packets.\n",net_id,num_ooo); } void shift_nic::setup() { link_control->setup(); if ( link_control->getEndpointID() != net_id ) { output.output("NIC ids don't match: parem = %" PRIi32 ", LinkControl = %" PRIi64 "\n",net_id, link_control->getEndpointID()); // output.output("NIC ids don't match: parem = %d, LinkControl = %" PRIi64 "\n",net_id, link_control->getEndpointID()); } // net_map.bind("global"); } void shift_nic::init(unsigned int phase) { link_control->init(phase); // if ( link_control->isNetworkInitialized() ) { // // Put my address into the network mapping // //SST::Interfaces::SimpleNetwork::addMappingEntry("global", id, net_id); // } } class ShiftEvent : public Event { public: int seq; ShiftEvent() {} ShiftEvent(int seq) : seq(seq) {} Event* clone(void) override { return new ShiftEvent(*this); } void serialize_order(SST::Core::Serialization::serializer &ser) override { Event::serialize_order(ser); ser & seq; } private: ImplementSerializable(SST::Merlin::ShiftEvent); }; bool shift_nic::clock_handler(Cycle_t cycle) { int expected_recv_count = num_msg; // if ( !done && (packets_recd >= expected_recv_count) ) { // output.output("%" PRIu64 ": NIC %d received all packets!\n", cycle, net_id); // primaryComponentOKToEndSim(); // done = true; // } // Send packets if ( packets_sent < expected_recv_count ) { if ( link_control->spaceToSend(0,size_in_bits) ) { ShiftEvent* ev = new ShiftEvent(send_seq++); SimpleNetwork::Request* req = new SimpleNetwork::Request(); // req->dest = net_map[last_target]; req->dest = target; req->src = net_id; req->vn = 0; req->size_in_bits = size_in_bits; req->givePayload(ev); // if ( net_id == 3 ) { // req->setTraceType(SST::Interfaces::SimpleNetwork::Request::FULL); // req->setTraceID(net_id*1000 + packets_sent); // } bool sent = link_control->send(req,0); assert( sent ); packets_sent++; if ( packets_sent == expected_recv_count ) { output.output("%" PRIu64 ": %d Finished sending packets (total of %d)\n", cycle, net_id, num_msg); } } else { stalled_cycles++; } } else { send_done = true; if ( recv_done ) { primaryComponentOKToEndSim(); // output.output("%d called primaryComponentOKToEndSim()\n", // net_id); } return true; } // if ( link_control->requestToReceive(0) ) { // SimpleNetwork::Request* req = link_control->recv(0); // ShiftEvent* ev = dynamic_cast<ShiftEvent*>(req->takePayload()); // if ( ev == NULL ) { // Simulation::getSimulation()->getSimulationOutput().fatal(CALL_INFO, -1, "Aieeee!\n"); // } // packets_recd++; // // Check to see if packets were received out of order // if ( ev->seq < recv_seq ) { // num_ooo++; // } // else { // recv_seq = ev->seq; // } // delete ev; // delete req; // } return false; } bool shift_nic::handle_event(int vn) { while ( link_control->requestToReceive(0) ) { SimpleNetwork::Request* req = link_control->recv(0); ShiftEvent* ev = dynamic_cast<ShiftEvent*>(req->takePayload()); if ( ev == NULL ) { Simulation::getSimulation()->getSimulationOutput().fatal(CALL_INFO, -1, "Aieeee!\n"); } packets_recd++; // Check to see if packets were received out of order if ( ev->seq < recv_seq ) { num_ooo++; } else { recv_seq = ev->seq; } delete ev; delete req; } if ( packets_recd == num_msg ) { output.output("%d Received all packets (total of %d)\n", net_id, num_msg); recv_done = true; if ( send_done ) { primaryComponentOKToEndSim(); // output.output("%d called primaryComponentOKToEndSim()\n", // net_id); } return false; } else { return true; } } } // namespace Merlin } // namespace SST
28.003401
133
0.587149
[ "object" ]
a1b38dd66188f4a9d42aeebfbdca5804c37e8174
19,698
cpp
C++
camera/CameraParameters.cpp
rINanDO/android_device_samsung_hero-common
9980739e339d00dcaa1c6f75b79dba8cac1492fb
[ "Apache-2.0" ]
19
2017-05-04T18:28:03.000Z
2020-05-29T12:04:31.000Z
camera/CameraParameters.cpp
rINanDO/android_device_samsung_hero-common
9980739e339d00dcaa1c6f75b79dba8cac1492fb
[ "Apache-2.0" ]
1
2018-01-18T13:48:02.000Z
2018-01-18T13:48:02.000Z
camera/CameraParameters.cpp
rINanDO/android_device_samsung_hero-common
9980739e339d00dcaa1c6f75b79dba8cac1492fb
[ "Apache-2.0" ]
46
2017-05-01T20:54:26.000Z
2019-09-13T12:12:44.000Z
/* ** ** Copyright 2008, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #define LOG_TAG "CameraParams" #include <utils/Log.h> #include <string.h> #include <stdlib.h> #include <system/graphics.h> #include <camera/CameraParameters.h> namespace android { // Parameter keys to communicate between camera application and driver. const char CameraParameters::KEY_PREVIEW_SIZE[] = "preview-size"; const char CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES[] = "preview-size-values"; const char CameraParameters::KEY_PREVIEW_FORMAT[] = "preview-format"; const char CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS[] = "preview-format-values"; const char CameraParameters::KEY_PREVIEW_FRAME_RATE[] = "preview-frame-rate"; const char CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES[] = "preview-frame-rate-values"; const char CameraParameters::KEY_PREVIEW_FPS_RANGE[] = "preview-fps-range"; const char CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE[] = "preview-fps-range-values"; const char CameraParameters::KEY_PICTURE_SIZE[] = "picture-size"; const char CameraParameters::KEY_SUPPORTED_PICTURE_SIZES[] = "picture-size-values"; const char CameraParameters::KEY_PICTURE_FORMAT[] = "picture-format"; const char CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS[] = "picture-format-values"; const char CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH[] = "jpeg-thumbnail-width"; const char CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT[] = "jpeg-thumbnail-height"; const char CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES[] = "jpeg-thumbnail-size-values"; const char CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY[] = "jpeg-thumbnail-quality"; const char CameraParameters::KEY_JPEG_QUALITY[] = "jpeg-quality"; const char CameraParameters::KEY_ROTATION[] = "rotation"; const char CameraParameters::KEY_GPS_LATITUDE[] = "gps-latitude"; const char CameraParameters::KEY_GPS_LONGITUDE[] = "gps-longitude"; const char CameraParameters::KEY_GPS_ALTITUDE[] = "gps-altitude"; const char CameraParameters::KEY_GPS_TIMESTAMP[] = "gps-timestamp"; const char CameraParameters::KEY_GPS_PROCESSING_METHOD[] = "gps-processing-method"; const char CameraParameters::KEY_WHITE_BALANCE[] = "whitebalance"; const char CameraParameters::KEY_SUPPORTED_WHITE_BALANCE[] = "whitebalance-values"; const char CameraParameters::KEY_EFFECT[] = "effect"; const char CameraParameters::KEY_SUPPORTED_EFFECTS[] = "effect-values"; const char CameraParameters::KEY_ANTIBANDING[] = "antibanding"; const char CameraParameters::KEY_SUPPORTED_ANTIBANDING[] = "antibanding-values"; const char CameraParameters::KEY_SCENE_MODE[] = "scene-mode"; const char CameraParameters::KEY_SUPPORTED_SCENE_MODES[] = "scene-mode-values"; const char CameraParameters::KEY_FLASH_MODE[] = "flash-mode"; const char CameraParameters::KEY_SUPPORTED_FLASH_MODES[] = "flash-mode-values"; const char CameraParameters::KEY_FOCUS_MODE[] = "focus-mode"; const char CameraParameters::KEY_SUPPORTED_FOCUS_MODES[] = "focus-mode-values"; const char CameraParameters::KEY_MAX_NUM_FOCUS_AREAS[] = "max-num-focus-areas"; const char CameraParameters::KEY_FOCUS_AREAS[] = "focus-areas"; const char CameraParameters::KEY_FOCAL_LENGTH[] = "focal-length"; const char CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE[] = "horizontal-view-angle"; const char CameraParameters::KEY_VERTICAL_VIEW_ANGLE[] = "vertical-view-angle"; const char CameraParameters::KEY_EXPOSURE_COMPENSATION[] = "exposure-compensation"; const char CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION[] = "max-exposure-compensation"; const char CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION[] = "min-exposure-compensation"; const char CameraParameters::KEY_EXPOSURE_COMPENSATION_STEP[] = "exposure-compensation-step"; const char CameraParameters::KEY_AUTO_EXPOSURE_LOCK[] = "auto-exposure-lock"; const char CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED[] = "auto-exposure-lock-supported"; const char CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK[] = "auto-whitebalance-lock"; const char CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED[] = "auto-whitebalance-lock-supported"; const char CameraParameters::KEY_MAX_NUM_METERING_AREAS[] = "max-num-metering-areas"; const char CameraParameters::KEY_METERING_AREAS[] = "metering-areas"; const char CameraParameters::KEY_ZOOM[] = "zoom"; const char CameraParameters::KEY_MAX_ZOOM[] = "max-zoom"; const char CameraParameters::KEY_ZOOM_RATIOS[] = "zoom-ratios"; const char CameraParameters::KEY_ZOOM_SUPPORTED[] = "zoom-supported"; const char CameraParameters::KEY_SMOOTH_ZOOM_SUPPORTED[] = "smooth-zoom-supported"; const char CameraParameters::KEY_FOCUS_DISTANCES[] = "focus-distances"; const char CameraParameters::KEY_VIDEO_FRAME_FORMAT[] = "video-frame-format"; const char CameraParameters::KEY_VIDEO_SIZE[] = "video-size"; const char CameraParameters::KEY_SUPPORTED_VIDEO_SIZES[] = "video-size-values"; const char CameraParameters::KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO[] = "preferred-preview-size-for-video"; const char CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW[] = "max-num-detected-faces-hw"; const char CameraParameters::KEY_MAX_NUM_DETECTED_FACES_SW[] = "max-num-detected-faces-sw"; const char CameraParameters::KEY_RECORDING_HINT[] = "recording-hint"; const char CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED[] = "video-snapshot-supported"; const char CameraParameters::KEY_VIDEO_STABILIZATION[] = "video-stabilization"; const char CameraParameters::KEY_VIDEO_STABILIZATION_SUPPORTED[] = "video-stabilization-supported"; const char CameraParameters::KEY_LIGHTFX[] = "light-fx"; const char CameraParameters::TRUE[] = "true"; const char CameraParameters::FALSE[] = "false"; const char CameraParameters::FOCUS_DISTANCE_INFINITY[] = "Infinity"; // Values for white balance settings. const char CameraParameters::WHITE_BALANCE_AUTO[] = "auto"; const char CameraParameters::WHITE_BALANCE_INCANDESCENT[] = "incandescent"; const char CameraParameters::WHITE_BALANCE_FLUORESCENT[] = "fluorescent"; const char CameraParameters::WHITE_BALANCE_WARM_FLUORESCENT[] = "warm-fluorescent"; const char CameraParameters::WHITE_BALANCE_DAYLIGHT[] = "daylight"; const char CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT[] = "cloudy-daylight"; const char CameraParameters::WHITE_BALANCE_TWILIGHT[] = "twilight"; const char CameraParameters::WHITE_BALANCE_SHADE[] = "shade"; // Values for effect settings. const char CameraParameters::EFFECT_NONE[] = "none"; const char CameraParameters::EFFECT_MONO[] = "mono"; const char CameraParameters::EFFECT_NEGATIVE[] = "negative"; const char CameraParameters::EFFECT_SOLARIZE[] = "solarize"; const char CameraParameters::EFFECT_SEPIA[] = "sepia"; const char CameraParameters::EFFECT_POSTERIZE[] = "posterize"; const char CameraParameters::EFFECT_WHITEBOARD[] = "whiteboard"; const char CameraParameters::EFFECT_BLACKBOARD[] = "blackboard"; const char CameraParameters::EFFECT_AQUA[] = "aqua"; // Values for antibanding settings. const char CameraParameters::ANTIBANDING_AUTO[] = "auto"; const char CameraParameters::ANTIBANDING_50HZ[] = "50hz"; const char CameraParameters::ANTIBANDING_60HZ[] = "60hz"; const char CameraParameters::ANTIBANDING_OFF[] = "off"; // Values for flash mode settings. const char CameraParameters::FLASH_MODE_OFF[] = "off"; const char CameraParameters::FLASH_MODE_AUTO[] = "auto"; const char CameraParameters::FLASH_MODE_ON[] = "on"; const char CameraParameters::FLASH_MODE_RED_EYE[] = "red-eye"; const char CameraParameters::FLASH_MODE_TORCH[] = "torch"; // Values for scene mode settings. const char CameraParameters::SCENE_MODE_AUTO[] = "auto"; const char CameraParameters::SCENE_MODE_ACTION[] = "action"; const char CameraParameters::SCENE_MODE_PORTRAIT[] = "portrait"; const char CameraParameters::SCENE_MODE_LANDSCAPE[] = "landscape"; const char CameraParameters::SCENE_MODE_NIGHT[] = "night"; const char CameraParameters::SCENE_MODE_NIGHT_PORTRAIT[] = "night-portrait"; const char CameraParameters::SCENE_MODE_THEATRE[] = "theatre"; const char CameraParameters::SCENE_MODE_BEACH[] = "beach"; const char CameraParameters::SCENE_MODE_SNOW[] = "snow"; const char CameraParameters::SCENE_MODE_SUNSET[] = "sunset"; const char CameraParameters::SCENE_MODE_STEADYPHOTO[] = "steadyphoto"; const char CameraParameters::SCENE_MODE_FIREWORKS[] = "fireworks"; const char CameraParameters::SCENE_MODE_SPORTS[] = "sports"; const char CameraParameters::SCENE_MODE_PARTY[] = "party"; const char CameraParameters::SCENE_MODE_CANDLELIGHT[] = "candlelight"; const char CameraParameters::SCENE_MODE_BARCODE[] = "barcode"; const char CameraParameters::SCENE_MODE_HDR[] = "hdr"; const char CameraParameters::PIXEL_FORMAT_YUV422SP[] = "yuv422sp"; const char CameraParameters::PIXEL_FORMAT_YUV420SP[] = "yuv420sp"; const char CameraParameters::PIXEL_FORMAT_YUV420SP_NV21[] = "nv21"; const char CameraParameters::PIXEL_FORMAT_YUV422I[] = "yuv422i-yuyv"; const char CameraParameters::PIXEL_FORMAT_YUV420P[] = "yuv420p"; const char CameraParameters::PIXEL_FORMAT_RGB565[] = "rgb565"; const char CameraParameters::PIXEL_FORMAT_RGBA8888[] = "rgba8888"; const char CameraParameters::PIXEL_FORMAT_JPEG[] = "jpeg"; const char CameraParameters::PIXEL_FORMAT_BAYER_RGGB[] = "bayer-rggb"; const char CameraParameters::PIXEL_FORMAT_ANDROID_OPAQUE[] = "android-opaque"; // Values for focus mode settings. const char CameraParameters::FOCUS_MODE_AUTO[] = "auto"; const char CameraParameters::FOCUS_MODE_INFINITY[] = "infinity"; const char CameraParameters::FOCUS_MODE_MACRO[] = "macro"; const char CameraParameters::FOCUS_MODE_FIXED[] = "fixed"; const char CameraParameters::FOCUS_MODE_EDOF[] = "edof"; const char CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO[] = "continuous-video"; const char CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE[] = "continuous-picture"; // Values for light fx settings const char CameraParameters::LIGHTFX_LOWLIGHT[] = "low-light"; const char CameraParameters::LIGHTFX_HDR[] = "high-dynamic-range"; CameraParameters::CameraParameters() : mMap() { } CameraParameters::~CameraParameters() { } String8 CameraParameters::flatten() const { String8 flattened(""); size_t size = mMap.size(); for (size_t i = 0; i < size; i++) { String8 k, v; k = mMap.keyAt(i); v = mMap.valueAt(i); flattened += k; flattened += "="; flattened += v; if (i != size-1) flattened += ";"; } return flattened; } void CameraParameters::unflatten(const String8 &params) { const char *a = params.string(); const char *b; mMap.clear(); for (;;) { // Find the bounds of the key name. b = strchr(a, '='); if (b == 0) break; // Create the key string. String8 k(a, (size_t)(b-a)); // Find the value. a = b+1; b = strchr(a, ';'); if (b == 0) { // If there's no semicolon, this is the last item. String8 v(a); mMap.add(k, v); break; } String8 v(a, (size_t)(b-a)); mMap.add(k, v); a = b+1; } } void CameraParameters::set(const char *key, const char *value) { if (key == NULL || value == NULL) return; // XXX i think i can do this with strspn() if (strchr(key, '=') || strchr(key, ';')) { //XXX ALOGE("Key \"%s\"contains invalid character (= or ;)", key); return; } if (strchr(value, '=') || strchr(value, ';')) { //XXX ALOGE("Value \"%s\"contains invalid character (= or ;)", value); return; } mMap.replaceValueFor(String8(key), String8(value)); } void CameraParameters::set(const char *key, int value) { char str[16]; sprintf(str, "%d", value); set(key, str); } void CameraParameters::setFloat(const char *key, float value) { char str[16]; // 14 should be enough. We overestimate to be safe. snprintf(str, sizeof(str), "%g", value); set(key, str); } const char *CameraParameters::get(const char *key) const { String8 v = mMap.valueFor(String8(key)); if (v.length() == 0) return 0; return v.string(); } int CameraParameters::getInt(const char *key) const { const char *v = get(key); if (v == 0) return -1; return strtol(v, 0, 0); } float CameraParameters::getFloat(const char *key) const { const char *v = get(key); if (v == 0) return -1; return strtof(v, 0); } void CameraParameters::remove(const char *key) { mMap.removeItem(String8(key)); } // Parse string like "640x480" or "10000,20000" static int parse_pair(const char *str, int *first, int *second, char delim, char **endptr = NULL) { // Find the first integer. char *end; int w = (int)strtol(str, &end, 10); // If a delimeter does not immediately follow, give up. if (*end != delim) { ALOGE("Cannot find delimeter (%c) in str=%s", delim, str); return -1; } // Find the second integer, immediately after the delimeter. int h = (int)strtol(end+1, &end, 10); *first = w; *second = h; if (endptr) { *endptr = end; } return 0; } static void parseSizesList(const char *sizesStr, Vector<Size> &sizes) { if (sizesStr == 0) { return; } char *sizeStartPtr = (char *)sizesStr; while (true) { int width, height; int success = parse_pair(sizeStartPtr, &width, &height, 'x', &sizeStartPtr); if (success == -1 || (*sizeStartPtr != ',' && *sizeStartPtr != '\0')) { ALOGE("Picture sizes string \"%s\" contains invalid character.", sizesStr); return; } sizes.push(Size(width, height)); if (*sizeStartPtr == '\0') { return; } sizeStartPtr++; } } void CameraParameters::setPreviewSize(int width, int height) { char str[32]; sprintf(str, "%dx%d", width, height); set(KEY_PREVIEW_SIZE, str); } void CameraParameters::getPreviewSize(int *width, int *height) const { *width = *height = -1; // Get the current string, if it doesn't exist, leave the -1x-1 const char *p = get(KEY_PREVIEW_SIZE); if (p == 0) return; parse_pair(p, width, height, 'x'); } void CameraParameters::getPreferredPreviewSizeForVideo(int *width, int *height) const { *width = *height = -1; const char *p = get(KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO); if (p == 0) return; parse_pair(p, width, height, 'x'); } void CameraParameters::getSupportedPreviewSizes(Vector<Size> &sizes) const { const char *previewSizesStr = get(KEY_SUPPORTED_PREVIEW_SIZES); parseSizesList(previewSizesStr, sizes); } void CameraParameters::setVideoSize(int width, int height) { char str[32]; sprintf(str, "%dx%d", width, height); set(KEY_VIDEO_SIZE, str); } void CameraParameters::getVideoSize(int *width, int *height) const { *width = *height = -1; const char *p = get(KEY_VIDEO_SIZE); if (p == 0) return; parse_pair(p, width, height, 'x'); } void CameraParameters::getSupportedVideoSizes(Vector<Size> &sizes) const { const char *videoSizesStr = get(KEY_SUPPORTED_VIDEO_SIZES); parseSizesList(videoSizesStr, sizes); } void CameraParameters::setPreviewFrameRate(int fps) { set(KEY_PREVIEW_FRAME_RATE, fps); } int CameraParameters::getPreviewFrameRate() const { return getInt(KEY_PREVIEW_FRAME_RATE); } void CameraParameters::getPreviewFpsRange(int *min_fps, int *max_fps) const { *min_fps = *max_fps = -1; const char *p = get(KEY_PREVIEW_FPS_RANGE); if (p == 0) return; parse_pair(p, min_fps, max_fps, ','); } void CameraParameters::setPreviewFormat(const char *format) { set(KEY_PREVIEW_FORMAT, format); } const char *CameraParameters::getPreviewFormat() const { return get(KEY_PREVIEW_FORMAT); } void CameraParameters::setPictureSize(int width, int height) { char str[32]; sprintf(str, "%dx%d", width, height); set(KEY_PICTURE_SIZE, str); } void CameraParameters::getPictureSize(int *width, int *height) const { *width = *height = -1; // Get the current string, if it doesn't exist, leave the -1x-1 const char *p = get(KEY_PICTURE_SIZE); if (p == 0) return; parse_pair(p, width, height, 'x'); } void CameraParameters::getSupportedPictureSizes(Vector<Size> &sizes) const { const char *pictureSizesStr = get(KEY_SUPPORTED_PICTURE_SIZES); parseSizesList(pictureSizesStr, sizes); } void CameraParameters::setPictureFormat(const char *format) { set(KEY_PICTURE_FORMAT, format); } const char *CameraParameters::getPictureFormat() const { return get(KEY_PICTURE_FORMAT); } void CameraParameters::dump() const { ALOGD("dump: mMap.size = %zu", mMap.size()); for (size_t i = 0; i < mMap.size(); i++) { String8 k, v; k = mMap.keyAt(i); v = mMap.valueAt(i); ALOGD("%s: %s\n", k.string(), v.string()); } } status_t CameraParameters::dump(int fd, const Vector<String16>& /*args*/) const { const size_t SIZE = 256; char buffer[SIZE]; String8 result; snprintf(buffer, 255, "CameraParameters::dump: mMap.size = %zu\n", mMap.size()); result.append(buffer); for (size_t i = 0; i < mMap.size(); i++) { String8 k, v; k = mMap.keyAt(i); v = mMap.valueAt(i); snprintf(buffer, 255, "\t%s: %s\n", k.string(), v.string()); result.append(buffer); } write(fd, result.string(), result.size()); return NO_ERROR; } void CameraParameters::getSupportedPreviewFormats(Vector<int>& formats) const { const char* supportedPreviewFormats = get(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS); if (supportedPreviewFormats == NULL) { ALOGW("%s: No supported preview formats.", __FUNCTION__); return; } String8 fmtStr(supportedPreviewFormats); char* prevFmts = fmtStr.lockBuffer(fmtStr.size()); char* savePtr; char* fmt = strtok_r(prevFmts, ",", &savePtr); while (fmt) { int actual = previewFormatToEnum(fmt); if (actual != -1) { formats.add(actual); } fmt = strtok_r(NULL, ",", &savePtr); } fmtStr.unlockBuffer(fmtStr.size()); } int CameraParameters::previewFormatToEnum(const char* format) { return !format ? HAL_PIXEL_FORMAT_YCrCb_420_SP : !strcmp(format, PIXEL_FORMAT_YUV422SP) ? HAL_PIXEL_FORMAT_YCbCr_422_SP : // NV16 !strcmp(format, PIXEL_FORMAT_YUV420SP) ? HAL_PIXEL_FORMAT_YCrCb_420_SP : // NV21 !strcmp(format, PIXEL_FORMAT_YUV422I) ? HAL_PIXEL_FORMAT_YCbCr_422_I : // YUY2 !strcmp(format, PIXEL_FORMAT_YUV420P) ? HAL_PIXEL_FORMAT_YV12 : // YV12 !strcmp(format, PIXEL_FORMAT_RGB565) ? HAL_PIXEL_FORMAT_RGB_565 : // RGB565 !strcmp(format, PIXEL_FORMAT_RGBA8888) ? HAL_PIXEL_FORMAT_RGBA_8888 : // RGB8888 !strcmp(format, PIXEL_FORMAT_BAYER_RGGB) ? HAL_PIXEL_FORMAT_RAW16 : // Raw sensor data -1; } bool CameraParameters::isEmpty() const { return mMap.isEmpty(); } }; // namespace android
36.276243
105
0.705808
[ "vector" ]
a1b7dd583947db8d57911f9efe364623ecb540e3
14,910
cpp
C++
libextra/source/ExtraMath.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
4
2017-10-04T06:23:11.000Z
2019-05-09T14:39:12.000Z
libextra/source/ExtraMath.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
null
null
null
libextra/source/ExtraMath.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
2
2018-10-11T02:01:42.000Z
2019-02-09T21:30:59.000Z
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include "ExtraMath.h" namespace PRImA { /* * Class CExtraMath * * Helper class with static functions for mathematical problems. */ /* * Calculates the angle between two points */ double CExtraMath::AngleTwoPoints(int X1, int Y1, int X2, int Y2) { int Xd = X2 - X1; int Yd = Y2 - Y1; if(Xd == 0) { if(Yd <= 0) return 0.0; else //if(Yd > 0) return 180.0; //else //{ // fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); // return -1; //} } else if(Xd < 0) { if(Yd == 0) return 270.0; else if(Yd < 0) { if(abs(Xd) > abs(Yd)) return 270.0 + RadiansToDegrees(acos(double(abs(Xd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); else return 360.0 - RadiansToDegrees(acos(double(abs(Yd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else //if(Yd > 0) { if(abs(Xd) > Yd) return 270.0 - RadiansToDegrees(acos(double(abs(Xd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); else return 180.0 + RadiansToDegrees(acos(double(Yd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } //else //{ // fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); // return -1; //} } else //if(Xd > 0) { if(Yd == 0) return 90.0; else if(Yd < 0) { if(abs(Yd) >= Xd) { return 0.0 + RadiansToDegrees(acos(double(abs(Yd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else { return 90.0 - RadiansToDegrees(acos(double(Xd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } } else //if(Yd > 0) { if(Yd >= Xd) { return 90.0 + RadiansToDegrees(acos(double(Xd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else { return 180.0 - RadiansToDegrees(acos(double(Yd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } } //else //{ // fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); // return -1; //} } //else //{ // fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); // return -1; //} } /* * Calculates angle in radians between two points and x-axis. */ double CExtraMath::AngleLineXAxis(int x1, int y1, int x2, int y2) { return atan2(y1-y2, x2- x1); } /* * Calculates the angle between two points */ double CExtraMath::NewAngleTwoPoints(int X1, int Y1, int X2, int Y2) // The angle is horizontal , angle is between 0 --- 360 { int Xd = X2 - X1; int Yd = Y2 - Y1; if(Xd == 0) { if(Yd <= 0) return 90.0; else if(Yd > 0) return 270.0; else { fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); return -1; } } else if(Xd < 0) // the angle is between 90 -- 270 { if(Yd == 0) return 180.0; else if(Yd < 0) // angle is between 90 - 180 { if(abs(Xd) > abs(Yd)) return 90.0 + RadiansToDegrees(asin(double(abs(Xd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); else return 180.0 - RadiansToDegrees(asin(double(abs(Yd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else if(Yd > 0) // angle is between 180 -- 270 { if(abs(Xd) > Yd) return 180.0 + RadiansToDegrees(acos(double(abs(Xd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); else return 270.0 - RadiansToDegrees(acos(double(Yd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else { fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); return -1; } } else if(Xd > 0) // the angle is 0 -- 90 && 270 -- 360 { if(Yd == 0) return 0.0; else if(Yd < 0) // the angle is 0 -- 90 { if(abs(Yd) >= Xd) { return 90.0 - RadiansToDegrees(acos(double(abs(Yd)) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else { return 0.0 + RadiansToDegrees(acos(double(Xd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } } else if(Yd > 0) // the angle is 270 -- 360 { if(Yd >= Xd) { return 270.0 + RadiansToDegrees(asin(double(Xd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } else { return 360.0 - RadiansToDegrees(asin(double(Yd) / double(sqrt(pow((double) Xd,2)+pow((double) Yd,2))))); } } else { fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); return -1; } } else { fprintf(stderr,"AngleTwoPoints(%d,%d , %d,%d): ERROR!\n",X1,Y1,X2,Y2); return -1; } } /* * Computes the distance of a point to a line segment. * 'PX', 'PY' - Coordinates of the point * 'StartX', 'StartY', 'EndX', 'EndY' - Specifies the line */ double CExtraMath::DistancePointLine(const int PX, const int PY, const int StartX, const int StartY, const int EndX, const int EndY) { return DistancePointLine(PX, PY, StartX, StartY, EndX, EndY, NULL, NULL); } /* * Computes the distance of a point to a line segment and also passes the nearest point on the line. * 'PX', 'PY' (in) - Coordinates of the point * 'StartX', 'StartY', 'EndX', 'EndY' (in) - Specifies the line * 'pointOnLineX', 'pointOnLineY' (out) - Will be filled with the coordinates of the nearest point on the line */ double CExtraMath::DistancePointLine(const int PX, const int PY, const int StartX, const int StartY, const int EndX, const int EndY, int * pointOnLineX, int * pointOnLineY) { double LineMag; double U; int XDiff = EndX - StartX; int YDiff = EndY - StartY; LineMag = sqrt((double) (XDiff * XDiff + YDiff * YDiff)); U = (((PX - StartX) * XDiff) + ((PY - StartY) * YDiff)) / (LineMag * LineMag); if(U < 0.0) return DistanceTwoPoints(PX, PY, StartX, StartY); else if(U > 1.0) return DistanceTwoPoints(PX, PY, EndX, EndY); int IntX = (int) ((StartX + U * XDiff)+0.5); //CC 24.05.2010 - added +0.5 to round int IntY = (int) ((StartY + U * YDiff)+0.5); //Return also the intersection point if (pointOnLineX != NULL) { *pointOnLineX = IntX; *pointOnLineY = IntY; } XDiff = PX - IntX; YDiff = PY - IntY; return sqrt((double) (XDiff * XDiff + YDiff * YDiff)); } /* * Computes the distance of a point to a line (infinite, not a line segment). * 'px', 'px' (in) - Coordinates of the point * 'lineX1', 'lineY1', 'lineX2', 'lineY2' (in) - Specifies the line */ double CExtraMath::DistancePointInfiniteLine(const int px, const int py, const int lineX1, const int lineY1, const int lineX2, const int lineY2) { // find the slope /*double slope_of_line = (double)(lineY1 - lineY2) / (double)(lineX1 - lineX2); // find the perpendicular slope double perpendicular_slope = (double)(lineX1 - lineX2) / (double)(lineY1 - lineY2) * -1; // find the y_intercept of line BC double y_intercept = slope_of_line * lineX2 - lineY2; // find the y_intercept of line AX double new_line_y_intercept = perpendicular_slope * -1 * px - py; // get the x_coordinate of point X // equation of BC is y = slope_of_line * x + y_intercept; // equation of AX is y = perpendicular_slope * x + new_line_y_intercept; // perpendicular_slope * x + new_line_y_intercept == slope_of_line * x + y_intercept; // perpendicular_slope * x == slope_of_line * x + y_intercept - new_line_y_intercept; // (perpendicular_slope - slope_of_line) * x == (y_intercept - new_line_y_intercept); intersectX = (y_intercept - new_line_y_intercept) / (perpendicular_slope - slope_of_line); // get the y_coordinate of point X intersectY = slope_of_line * intersectX + y_intercept; // measure the distance between A and X return DistanceTwoPoints((double)px, (double)py, intersectX, intersectY);*/ double A = px - lineX1; double B = py - lineY1; double C = lineX2 - lineX1; double D = lineY2 - lineY1; return abs(A * D - C * B) / sqrt(C * C + D * D); } /* * Converts degrees to radians */ double CExtraMath::DegreesToRadians(double Degrees) { return M_PI * Degrees / 180.0; } /* * Calculates the (Euclidian) distance between two points */ double CExtraMath::DistanceTwoPoints(int X1, int Y1, int X2, int Y2) { return sqrt(pow(double(X2 - X1),2) + pow(double(Y2 - Y1),2)); } /* * Calculates the (Euclidian) distance between two points */ double CExtraMath::DistanceTwoPoints(double X1, double Y1, double X2, double Y2) { return sqrt(pow(X2 - X1,2) + pow(Y2 - Y1,2)); } /* * adapted from Darel Rex Finley, 2006: http://alienryderflex.com/intersect/ * * Determines the intersection point of the line segment defined by points A1 and A2 * with the line segment defined by points B1 and B2. * * CC 01.12.2009 replaced Daves code */ bool CExtraMath::DoLineSegmentsIntersect(double ax1, double ay1, double ax2, double ay2, double bx1, double by1, double bx2, double by2, double tolerance) { double distAB; double theCos; double theSin; double newX; double posAB; // Fail if either line segment is zero-length. if (ax1==ax2 && ay1==ay2 || bx1==bx2 && by1==by2) return false; //NULL; if (ax1 == bx1 && ay1 == by1 || ax2 == bx1 && ay2 == by1) { return true; //new Point(bx1, by1); } if (ax1==bx2 && ay1==by2 || ax2==bx2 && ay2==by2) { return true; //new Point(bx2, by2); } // (1) Translate the system so that point A1 is on the origin. ax2-=ax1; ay2-=ay1; bx1-=ax1; by1-=ay1; bx2-=ax1; by2-=ay1; // Discover the length of segment A1-A2. distAB=sqrt((double)(ax2*ax2+ay2*ay2)); // (2) Rotate the system so that point A2 is on the positive X ax1is. theCos = ax2 / distAB; theSin = ay2 / distAB; newX = bx1 * theCos + by1 * theSin; by1 = by1 * theCos - bx1 * theSin; bx1 = newX; newX = bx2 * theCos + by2 * theSin; by2 = by2 * theCos - bx2 * theSin; bx2 = newX; // Fail if segment B1-B2 doesn't cross line A1-A2. if (by1<0.0 && by2<0.0 || by1>=0.0 && by2>=0.0) return false; //null; // (3) Discover the position of the intersection point along line A1-A2. posAB = bx2+(bx1-bx2)*by2/(by2-by1); // Fail if segment B1-B2 crosses line A1-A2 outside of segment A1-A2. if (posAB < 0.0-tolerance || posAB > distAB + tolerance) return false; //null; // (4) Apply the discovered position to line A1-A2 in the original coordinate system. return true; //new Point(ax1 + posAB * theCos, ay1 + posAB * theSin); } EdgeType CExtraMath::GetEdgeType(int X1, int Y1, int X2, int Y2) { if(X1 == X2) { if(Y1 == Y2) return COLOCATED; else return VERTICAL; } else { if(Y1 == Y2) return HORIZONTAL; else { if(abs(X2-X1) > abs(Y2-Y1)) return DIAGONALH; else return DIAGONALV; } } } /*int CExtraMath::IsGreater(const int A, const int B) { return B - A; } int CExtraMath::IsSmaller(const int A, const int B) { return A - B; } int CExtraMath::IsGreaterP(const int * A, const int * B) { return *B - *A; }*/ /*int CExtraMath::IsLineToRight(const RangeLine * A, const RangeLine * B) { return A->P2->GetX() - B->P1->GetX(); }*/ /*int CExtraMath::IsSmallerP(const int * A, const int * B) { return *A - *B; } bool CExtraMath::IsIn(int SearchFor,int * InArray, int NoArrayMembers) { int i; for(i = 0; i < NoArrayMembers; i++) { if(InArray[i] == SearchFor) return true; } return false; }*/ int CExtraMath::CompareLineSegments(const LineSegment * A, const LineSegment * B) { return B->y1 - A->y1; } double CExtraMath::FMin(double A, double B) { if(A <= B) return A; else return B; } int CExtraMath::Max(int A, int B) { if(A >= B) return A; else return B; } double CExtraMath::Max(double A, double B) { if(A >= B) return A; else return B; } int CExtraMath::Max(int A, int B, int C) { int Ret = A; if(B > Ret) Ret = B; if(C > Ret) Ret = C; return Ret; } int CExtraMath::Min(int A, int B) { if(A <= B) return A; else return B; } long CExtraMath::Min(long A, long B) { if(A <= B) return A; else return B; } /*uint16_t CExtraMath::Min(uint16_t A, uint16_t B) { if(A <= B) return A; else return B; }*/ unsigned CExtraMath::Min(unsigned A, unsigned B) { if(A <= B) return A; else return B; } int CExtraMath::Min(int A, int B, int C) { int Ret = A; if(B < Ret) Ret = B; if(C < Ret) Ret = C; return Ret; } /* * Converts radians to degrees */ double CExtraMath::RadiansToDegrees(double Radians) { return 180.0 * Radians / M_PI; } /* * Traverses the specified line and returns a list containing each visited point. * * CC 29.09.2010 */ list<Point> * CExtraMath::GetPointsOfLine(int x1, int y1, int x2, int y2) { list<Point> * points = new list<Point>(); Point p; //Vertical if (x1 == x2) { p.x = x1; for (p.y=min(y1,y2); p.y<=max(y1,y2); p.y++) points->push_back(p); } //Horizontal else if (y1 == y2) { p.y = y1; for (p.x=min(x1,x2); p.x<=max(x1,x2); p.x++) points->push_back(p); } //Diagonal else { if(abs(x2 - x1) >= abs(y2 - y1)) // Diagonal Line Closer To Horizontal { if(x2 < x1) { //Swap (to guarantee that x1 is always smaller than x2) int temp; temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; } double gradient = double(y2 - y1) / double(x2 - x1); for(p.x = x1; p.x <= x2; p.x++) { p.y = int(double(p.x - x1) * gradient) + y1; points->push_back(p); } } else // Diagonal Line Closer To Vertical { if(y2 < y1) { //Swap (to guarantee that y1 is always smaller than y2) int temp; temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; } double gradient = double(x2 - x1) / double(y2 - y1); for(p.y = y1; p.y <= y2; p.y++) { p.x = int(double(p.y - y1) * gradient) + x1; points->push_back(p); } } } return points; } /* * Calculates the intersection point of the linear functions defined by the 4 given points. * * 'ax1', 'ay1', 'ax2', 'ay2' (in) - Points that define linear function a. * 'bx1', 'by1', 'bx2', 'by2' (in) - Points that define linear function b. * 'intersectX', 'intersectX' (out) - Intersection point. * Returns true, if the functions have an intersection point, false otherwise. * * CC 10.02.2012 * See: http://paulbourke.net/geometry/lineline2d/ */ bool CExtraMath::GetInterceptionPointOfTwoLines(double ax1, double ay1, double ax2, double ay2, double bx1, double by1, double bx2, double by2, double & intersectX, double & intersectY) { double dividend = ((bx2-bx1)*(ay1-by1) - (by2-by1)*(ax1-bx1)); double divisor = ((by2-by1)*(ax2-ax1) - (bx2-bx1)*(ay2-ay1)); if (divisor == 0.0) return false; //Parallel lines double ua = dividend / divisor; intersectX = ax1 + ua*(ax2-ax1); intersectY = ay1 + ua*(ay2-ay1); return true; } } //end namespace
23.480315
144
0.606908
[ "geometry" ]