hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
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
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
200102719300a9f6475e961079b2674f4ca4c645
781
cpp
C++
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
4
2018-03-05T02:27:16.000Z
2021-03-15T14:19:44.000Z
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
null
null
null
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
2
2018-07-22T10:32:10.000Z
2018-10-20T03:14:28.000Z
#include <gtest/gtest.h> extern "C" { #include "max_points_on_a_line.h" } #define ARR_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef struct Point point; static point point_create(int x, int y) { point p; p.x = x; p.y = y; return p; } TEST(max_points_on_a_line_test, maxPoints_149_1) { point points1[] = { point_create(1, 1), point_create(2, 2), point_create(3, 3) }; EXPECT_EQ(maxPoints_149_1(points1, ARR_SIZE(points1)), 3); point points2[] = { point_create(1, 1), point_create(3, 2), point_create(5, 3), point_create(4, 1), point_create(2, 3), point_create(1, 4) }; EXPECT_EQ(maxPoints_149_1(points2, ARR_SIZE(points2)), 4); }
21.694444
62
0.568502
20018b19d78840a26a6af63ad75e218a8eba73cd
5,266
cc
C++
third_party/blink/renderer/modules/mediastream/input_device_info.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/modules/mediastream/input_device_info.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/modules/mediastream/input_device_info.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 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 "third_party/blink/renderer/modules/mediastream/input_device_info.h" #include <algorithm> #include "third_party/blink/renderer/modules/mediastream/media_track_capabilities.h" namespace blink { namespace { // TODO(c.padhi): Merge this method with ToWebFacingMode() in // media_stream_constraints_util_video_device.h, see https://crbug.com/821668. WebMediaStreamTrack::FacingMode ToWebFacingMode(mojom::FacingMode facing_mode) { switch (facing_mode) { case mojom::FacingMode::NONE: return WebMediaStreamTrack::FacingMode::kNone; case mojom::FacingMode::USER: return WebMediaStreamTrack::FacingMode::kUser; case mojom::FacingMode::ENVIRONMENT: return WebMediaStreamTrack::FacingMode::kEnvironment; case mojom::FacingMode::LEFT: return WebMediaStreamTrack::FacingMode::kLeft; case mojom::FacingMode::RIGHT: return WebMediaStreamTrack::FacingMode::kRight; } NOTREACHED(); return WebMediaStreamTrack::FacingMode::kNone; } } // namespace InputDeviceInfo* InputDeviceInfo::Create(const String& device_id, const String& label, const String& group_id, MediaDeviceType device_type) { return new InputDeviceInfo(device_id, label, group_id, device_type); } InputDeviceInfo::InputDeviceInfo(const String& device_id, const String& label, const String& group_id, MediaDeviceType device_type) : MediaDeviceInfo(device_id, label, group_id, device_type) {} void InputDeviceInfo::SetVideoInputCapabilities( mojom::blink::VideoInputDeviceCapabilitiesPtr video_input_capabilities) { DCHECK_EQ(deviceId(), video_input_capabilities->device_id); // TODO(c.padhi): Merge the common logic below with // ComputeCapabilitiesForVideoSource() in media_stream_constraints_util.h, see // https://crbug.com/821668. platform_capabilities_.facing_mode = ToWebFacingMode(video_input_capabilities->facing_mode); if (!video_input_capabilities->formats.IsEmpty()) { int max_width = 1; int max_height = 1; float min_frame_rate = 1.0f; float max_frame_rate = min_frame_rate; for (const auto& format : video_input_capabilities->formats) { max_width = std::max(max_width, format->frame_size.width); max_height = std::max(max_height, format->frame_size.height); max_frame_rate = std::max(max_frame_rate, format->frame_rate); } platform_capabilities_.width = {1, max_width}; platform_capabilities_.height = {1, max_height}; platform_capabilities_.aspect_ratio = {1.0 / max_height, static_cast<double>(max_width)}; platform_capabilities_.frame_rate = {min_frame_rate, max_frame_rate}; } } void InputDeviceInfo::getCapabilities(MediaTrackCapabilities& capabilities) { // If label is null, permissions have not been given and no capabilities // should be returned. if (label().IsEmpty()) return; capabilities.setDeviceId(deviceId()); capabilities.setGroupId(groupId()); if (DeviceType() == MediaDeviceType::MEDIA_AUDIO_INPUT) { capabilities.setEchoCancellation({true, false}); capabilities.setAutoGainControl({true, false}); capabilities.setNoiseSuppression({true, false}); } if (DeviceType() == MediaDeviceType::MEDIA_VIDEO_INPUT) { if (!platform_capabilities_.width.empty()) { LongRange width; width.setMin(platform_capabilities_.width[0]); width.setMax(platform_capabilities_.width[1]); capabilities.setWidth(width); } if (!platform_capabilities_.height.empty()) { LongRange height; height.setMin(platform_capabilities_.height[0]); height.setMax(platform_capabilities_.height[1]); capabilities.setHeight(height); } if (!platform_capabilities_.aspect_ratio.empty()) { DoubleRange aspect_ratio; aspect_ratio.setMin(platform_capabilities_.aspect_ratio[0]); aspect_ratio.setMax(platform_capabilities_.aspect_ratio[1]); capabilities.setAspectRatio(aspect_ratio); } if (!platform_capabilities_.frame_rate.empty()) { DoubleRange frame_rate; frame_rate.setMin(platform_capabilities_.frame_rate[0]); frame_rate.setMax(platform_capabilities_.frame_rate[1]); capabilities.setFrameRate(frame_rate); } Vector<String> facing_mode; switch (platform_capabilities_.facing_mode) { case WebMediaStreamTrack::FacingMode::kUser: facing_mode.push_back("user"); break; case WebMediaStreamTrack::FacingMode::kEnvironment: facing_mode.push_back("environment"); break; case WebMediaStreamTrack::FacingMode::kLeft: facing_mode.push_back("left"); break; case WebMediaStreamTrack::FacingMode::kRight: facing_mode.push_back("right"); break; case WebMediaStreamTrack::FacingMode::kNone: break; } capabilities.setFacingMode(facing_mode); } } } // namespace blink
38.720588
84
0.701101
2002db0faa04c7cbb83a2d9acf6bcb78b4a028bd
2,966
cpp
C++
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
81
2018-11-15T21:23:19.000Z
2022-03-06T09:46:36.000Z
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
null
null
null
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
41
2018-11-15T21:23:24.000Z
2022-02-24T03:02:26.000Z
// TODO: FIX ME! Does not handle delta between dates correctly. // // main.cpp // // This program exercises the Calendar interface exported in calendar.h. // // -------------------------------------------------------------------------- // Attribution: "Programming Abstractions in C++" by Eric Roberts // Chapter 6, Exercise 6 // Stanford University, Autumn Quarter 2012 // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf // -------------------------------------------------------------------------- // // Created by Glenn Streiff on 12/17/15. // Copyright © 2015 Glenn Streiff. All rights reserved. // #include <iostream> #include "calendar.h" const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 6.6\n"; const std::string DETAIL = "Extend the calendar.h interface even more."; const std::string BANNER = HEADER + DETAIL; int main(int argc, char * argv[]) { std::cout << BANNER << std::endl << std::endl; Date moonLanding1(JULY, 20, 1969); Date moonLanding2(20, JULY, 1969); Date earlier(JULY, 20, 1969); Date sameAsEarlier(JULY, 20, 1969); Date later(JULY, 21, 1969); Date later2(AUGUST, 19, 1969); if (earlier < later) { std::cout << "[PASS] " << earlier << " is earlier than " << later << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << later << std::endl; } if (earlier < later2) { std::cout << "[PASS] " << earlier << " is earlier than " << later2 << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << later2 << std::endl; } if (earlier == sameAsEarlier) { std::cout << "[PASS] " << earlier << " is same as " << sameAsEarlier << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << sameAsEarlier << std::endl; } if (later > earlier) { std::cout << "[PASS] " << later << " is later than " << earlier << std::endl; } else { std::cout << "[FAIL] " << later << " is earlier than " << earlier << std::endl; } if (earlier != later) { std::cout << "[PASS] " << earlier << " is not equal to " << later << std::endl; } else { std::cout << "[FAIL] " << earlier << " is equal to " << later << std::endl; } // Add overloaded '<<' operator. std::cout << std::endl << moonLanding1 << std::endl; std::cout << moonLanding2 << std::endl; Date date(DECEMBER, 31, 1898); //Date date(FEBRUARY, 28, 1900); std::cout << toEpochDay(date) << std::endl; std::cout << toDate(1) << std::endl; std::cout << toDate(2) << std::endl; std::cout << toDate(0) << std::endl; std::cout << toDate(-1) << std::endl; return 0; }
31.892473
91
0.50472
200ad447b6ce9a7cbfba11e1533a560bb8b364fc
8,702
cpp
C++
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
28
2017-03-01T04:09:18.000Z
2022-02-01T13:33:50.000Z
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
3
2017-03-09T05:22:49.000Z
2017-08-02T18:38:05.000Z
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
17
2017-03-01T14:00:01.000Z
2022-02-08T06:36:54.000Z
// // Copyright (c) 2016 - 2017 Mesh Consultants Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Geomlib_TriMeshPlaneIntersection.h" #include <assert.h> #include "TriMesh.h" #include "Geomlib_RemoveDuplicates.h" namespace { using Urho3D::Vector; using Urho3D::Vector3; typedef Vector<Vector3> tri_; const double kSmallNum = 0.00000001; // Inputs: // tri: stores 3 vertices of the triangle // point, normal: point and normal defining the plane // Outputs: // num_normal_side: number of vertices on same side of plane as normal (vertices inside plane are counted here) // num_non_normal_side: number of vertices on opposite side of plane as normal void TriVertexSplit( const tri_& tri, const Vector3& point, const Vector3& normal, int& num_normal_side, int& num_non_normal_side ) { if (tri.Size() != 3) { // invalid triangle return; } num_normal_side = 0; num_non_normal_side = 0; for (int i = 0; i < 3; ++i) { Vector3 w = tri[i] - point; float val = w.DotProduct(normal); if (val >= 0) { ++num_normal_side; } else { ++num_non_normal_side; } } //assert(num_normal_side + num_non_normal_side == 3); } // Stores vertices v0, v1, v2 as triangle tri. void PushVertsOntoTri( const Vector3& v0, const Vector3& v1, const Vector3& v2, tri_& tri ) { tri.Push(v0); tri.Push(v1); tri.Push(v2); } // Outputs: // t: If there is a unique intersection, it is: (1 - t) * A + t * B // Returns: // 0: 0 intersection points // 1: 1 intersection point // 2: segment lies inside plane int SegmentPlaneIntersection( const Vector3& A, const Vector3& B, const Vector3& P, const Vector3& N, float& t ) { Vector3 U = B - A; Vector3 W = A - P; float dd = N.DotProduct(U); float nn = -1 * N.DotProduct(W); if (abs(dd) < kSmallNum) { if (abs(nn) < kSmallNum) { return 2; // segment lies in plane } else { return 0; // segment is parallel to plane but outside plane } } float sI = nn / dd; if (sI < 0 || sI > 1) { return 0; // intersection occurs beyond segment } t = sI; return 1; } // Preconditions: // (1) tri has exactly 2 vertices on normal side of plane (normal side includes inside plane) and 1 vertex on non-normal side of plane. // TriVertexSplit (above) can be used to confirm this condition. // Inputs: // tri: triangle being split // P, N: point and normal of plane // Outputs: // w0, w1: Store coordinates of the 2 vertices on normal side of plane. // w2: Stores coordinates of the 1 vertex on non-normal side of plane. // w3: Stores coordinates of edge [w0, w2] intersection with plane. // w4: Stores coordinates of edge [w1, w2] intersection with plane. // Postcondition: // (1) Triangle [w0, w1, w2] has the same orientation as tri. void TriPlaneIntersection_aux( const tri_& tri, const Vector3& P, const Vector3& N, Vector3& w0, Vector3& w1, Vector3& w2, Vector3& w3, Vector3& w4 ) { //assert(tri.Size() == 3); if (tri.Size() != 3) { return; } Vector<int> normal_side_indices, non_normal_side_indices; for (int i = 0; i < 3; ++i) { Vector3 v = tri[i]; Vector3 w = v - P; float val = w.DotProduct(N); if (val >= 0) { normal_side_indices.Push(i); } else { non_normal_side_indices.Push(i); } } if (normal_side_indices.Size() != 2 || non_normal_side_indices.Size() != 1) { // return; } //assert(normal_side_indices.Size() == 2 && non_normal_side_indices.Size() == 1); int ind = non_normal_side_indices[0]; if (ind == 0) { w0 = tri[1]; w1 = tri[2]; w2 = tri[0]; } else if (ind == 1) { w0 = tri[2]; w1 = tri[0]; w2 = tri[1]; } else if (ind == 2) { w0 = tri[0]; w1 = tri[1]; w2 = tri[2]; } float t; int flag = SegmentPlaneIntersection(w0, w2, P, N, t); int num_intersections = 0; if (flag == 1) { w3 = (1 - t) * w0 + t * w2; ++num_intersections; } flag = SegmentPlaneIntersection(w1, w2, P, N, t); if (flag == 1) { w4 = (1 - t) * w1 + t * w2; ++num_intersections; } //assert(num_intersections == 2); } void TriPlaneIntersection( const tri_& tri, const Vector3& P, const Vector3& N, Vector<tri_>& normal_side_tris, Vector<tri_>& non_normal_side_tris ) { int num_normal_side = 0; int num_non_normal_side = 0; TriVertexSplit(tri, P, N, num_normal_side, num_non_normal_side); int total_verts = num_normal_side + num_non_normal_side; if (total_verts != 3) { // intersection failed return; } // 3 verts on one side of plane if (num_normal_side == 3) { normal_side_tris.Push(tri); } else if (num_non_normal_side == 3) { non_normal_side_tris.Push(tri); } // 2 verts on one side, 1 on the other if (num_non_normal_side == 1 || num_non_normal_side == 2) { Vector3 w0, w1, w2, w3, w4; if (num_non_normal_side == 1) { TriPlaneIntersection_aux(tri, P, N, w0, w1, w2, w3, w4); tri_ non_norm, norm_1, norm_2; //tri_ tri_nns_1, tri_nns_2, tri_ns_1; PushVertsOntoTri(w0, w1, w3, norm_1); PushVertsOntoTri(w3, w1, w4, norm_2); PushVertsOntoTri(w3, w4, w2, non_norm); normal_side_tris.Push(norm_1); normal_side_tris.Push(norm_2); non_normal_side_tris.Push(non_norm); } else if (num_non_normal_side == 2) { TriPlaneIntersection_aux(tri, P, -1 * N, w0, w1, w2, w3, w4); tri_ non_norm_1, non_norm_2, norm; //tri_ tri_ns_1, tri_ns_2, tri_nns_1; PushVertsOntoTri(w0, w1, w3, non_norm_1); PushVertsOntoTri(w3, w1, w4, non_norm_2); PushVertsOntoTri(w3, w4, w2, norm); non_normal_side_tris.Push(non_norm_1); non_normal_side_tris.Push(non_norm_2); normal_side_tris.Push(norm); } } } }; // namespace bool Geomlib::TriMeshPlaneIntersection( const Urho3D::Variant& mesh, const Urho3D::Vector3& point, const Urho3D::Vector3& normal, Urho3D::Variant& mesh_normal_side, Urho3D::Variant& mesh_non_normal_side ) { using Urho3D::Variant; using Urho3D::VariantVector; using Urho3D::Vector; // Verify mesh and extract required mesh data if (!TriMesh_Verify(mesh)) { return false; } VariantVector vertex_list = TriMesh_GetVertexList(mesh); VariantVector face_list = TriMesh_GetFaceList(mesh); // Verify normal is not the zero Vector3 if (!(normal.LengthSquared() > 0.0f)) { return false; } // Store two bags of triangles Vector<tri_> normal_side_tris; Vector<tri_> non_normal_side_tris; // Loop over faces, splitting each one for (unsigned i = 0; i < face_list.Size(); i += 3) { tri_ tri; int i0 = face_list[i].GetInt(); int i1 = face_list[i + 1].GetInt(); int i2 = face_list[i + 2].GetInt(); tri.Push(vertex_list[i0].GetVector3()); tri.Push(vertex_list[i1].GetVector3()); tri.Push(vertex_list[i2].GetVector3()); TriPlaneIntersection( tri, point, normal, normal_side_tris, non_normal_side_tris ); } // Reconstruct normal side mesh from normal side bag of triangles Vector<Vector3> ns_vertex_list; for (unsigned i = 0; i < normal_side_tris.Size(); ++i) { tri_ tri = normal_side_tris[i]; ns_vertex_list.Push(tri[0]); ns_vertex_list.Push(tri[1]); ns_vertex_list.Push(tri[2]); } Variant ns_vertices, ns_faces; RemoveDuplicates(ns_vertex_list, ns_vertices, ns_faces); mesh_normal_side = TriMesh_Make(ns_vertices, ns_faces); // Reconstruct non-normal side mesh from non-normal side bag of triangles Vector<Vector3> nns_vertex_list; for (unsigned i = 0; i < non_normal_side_tris.Size(); ++i) { tri_ tri = non_normal_side_tris[i]; nns_vertex_list.Push(tri[0]); nns_vertex_list.Push(tri[1]); nns_vertex_list.Push(tri[2]); } Variant nns_vertices, nns_faces; RemoveDuplicates(nns_vertex_list, nns_vertices, nns_faces); mesh_non_normal_side = TriMesh_Make(nns_vertices, nns_faces); return true; }
25.976119
137
0.688348
200ae272cc1adb37009bf64dc648c03075bdad2c
8,195
cpp
C++
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
47
2016-07-27T07:22:06.000Z
2021-08-17T13:08:19.000Z
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
1
2016-09-24T06:04:39.000Z
2016-09-25T10:34:19.000Z
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
13
2016-07-27T10:44:35.000Z
2020-07-01T21:08:33.000Z
/************************************************************************** ** This file is a part of our work (Siggraph'16 paper, binary, code and dataset): ** ** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds ** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell ** ** w.li AT cs.ucl.ac.uk ** http://visual.cs.ucl.ac.uk/pubs/rotopp ** ** Copyright (c) 2016, Wenbin Li ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** ** -- Redistributions of source code and data 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. ** ** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA 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 "include/rotoSolver/fileUtils.hpp" #include "include/rotoSolver/eigenUtils.hpp" #include <gflags/gflags.h> #include <fstream> DECLARE_bool(use_planar_tracker_weights); // The missing string trim function - v. useful.. // Taken from http://www.codeproject.com/KB/stl/stdstringtrim.aspx void trim( string& str ) { string::size_type pos = str.find_last_not_of(' '); if (pos != string::npos) { str.erase(pos + 1); pos = str.find_first_not_of(' '); if (pos != string::npos) str.erase(0, pos); } else { str.erase(str.begin(), str.end()); } } void removeWhiteSpace(string& str) { trim(str); std::vector<char> charsToRemove({'\t', '\r', '\n'}); //for (const char c : charsToRemove) for (int i = 0; i < charsToRemove.size(); i++) { const char c = charsToRemove[i]; str.erase(std::remove(str.begin(), str.end(), c), str.end()); } trim(str); } string readLineFromFile(FilePtr& fp) { const int maxLen = 2048; char buffer[maxLen]; if(std::fgets(buffer, maxLen, fp)==NULL) cout << ""; buffer[maxLen-1] = '\0'; string line(buffer); removeWhiteSpace(line); return line; } void SaveSolverOutputFile(string textFilename, const Matrix& Data, const int startIdx, const int stopIdx) { const int NUM_VALUES_PER_ROTO_POINT = 6; int D = Data.cols(); nassert (remainder(D, NUM_VALUES_PER_ROTO_POINT) == 0); D /= NUM_VALUES_PER_ROTO_POINT; std::ofstream ofs(textFilename.c_str()); ofs << D << "\n"; ofs << startIdx << " " << stopIdx << "\n"; ofs << Data.transpose(); ofs.close(); std::cout << "Saved output to \"" << textFilename << "\"." << std::endl; } TrackingDataType TrackingDataTypeMapper(string str) { removeWhiteSpace(str); if (str.compare("forward") == 0) return ForwardPlanar; else if (str.compare("backward") == 0) return BackwardPlanar; else if (str.compare("point") == 0) return Point; return Unknown; } string TrackingDataTypeToString(const TrackingDataType& t) { switch (t) { case (ForwardPlanar): return "ForwardPlanar"; break; case (BackwardPlanar): return "BackwardPlanar"; break; case (Point): return "Point"; break; case (Unknown): default: return "Unknown"; break; } } PlanarTrackingData::PlanarTrackingData(string txtFilename) { DataType = Unknown; FilePtr fp(txtFilename.c_str(), "r"); OrigFileName = txtFilename; ShapeName = readLineFromFile(fp); KeyFrames.clear(); std::stringstream keyFramesStr(readLineFromFile(fp)); while (!keyFramesStr.eof()) { try { int i = -1; keyFramesStr >> i; if (i > 0) KeyFrames.push_back(i); } catch (...) {} } std::sort(KeyFrames.begin(), KeyFrames.end()); StartIndex = *(std::min_element(KeyFrames.begin(), KeyFrames.end())); EndIndex = *(std::max_element(KeyFrames.begin(), KeyFrames.end())); NumFrames = EndIndex - StartIndex + 1; //std::vector<int> ptID; std::vector<Eigen::VectorXd> data; std::stringstream sstream; int numFramesOfData = -1; while (!feof(fp)) { Eigen::VectorXd v(NumFrames); int pt = -1; int numRead = 0; std::stringstream s(readLineFromFile(fp)); s.exceptions(std::stringstream::failbit | std::stringstream::badbit); try { if (feof(fp)) { break; } s >> pt; if (pt < 0) { break; } for (int i = 0; i < NumFrames; ++i) { s >> v[i]; ++numRead; } if (s.bad()) { break; } } catch (...) { } if (numFramesOfData < 0) numFramesOfData = numRead; if (numRead == numFramesOfData) { PointIDs.push_back(pt); data.push_back(v.head(numFramesOfData)); } else { break; } } DataType = TrackingDataTypeMapper(sstream.str()); vdbg(DataType); vdbg(numFramesOfData); vdbg(data.size()); TrackingData.resize(numFramesOfData, data.size()); for(int i = 0; i < data.size(); i++){ Eigen::VectorXd v = data[i]; TrackingData.col(i) = v; } FrameWeights = Eigen::VectorXd::Ones(NumFrames); vdbg(FLAGS_use_planar_tracker_weights); if (FLAGS_use_planar_tracker_weights) { SetFrameWeights(); } } void PlanarTrackingData::SaveToOutputFile(const string textFilename) const { SaveSolverOutputFile(textFilename, TrackingData, StartIndex, EndIndex); } void PlanarTrackingData::SetFrameWeights() { typedef Eigen::Matrix<double, 1, 1> Vector1d; double startWeight = 0.0; double stopWeight = 0.0; switch (DataType) { case Unknown: case Point: return; break; case ForwardPlanar: startWeight = 1.0; stopWeight = 0.0; break; case BackwardPlanar: startWeight = 0.0; stopWeight = 1.0; break; } // REMEMBER TO TAKE THE SQUARING OF THE COST INTO ACCOUNT.. for (int i = 0, I = KeyFrames.size() - 1; i < I; ++i) { const int a = KeyFrames[i] - StartIndex; const int b = KeyFrames[i+1] - StartIndex; Interpolator<int> interp(a, b, Vector1d::Constant(startWeight), Vector1d::Constant(stopWeight)); for (int k = a+1; k < b; ++k) { nassert (k < NumFrames); FrameWeights.row(k) = interp.get(k); } } vdbg(FrameWeights.transpose()); } void PlanarTrackingData::Print() const { vdbg(ShapeName); vdbg(NumFrames); vdbg(StartIndex); vdbg(EndIndex); vdbg(TrackingData.rows()); vdbg(TrackingData.cols()); vdbg(TrackingData(0,0)); vdbg(TrackingData(0,1)); vdbg(TrackingData(1,0)); vdbg(TrackingData(TrackingData.rows()-1, TrackingData.cols()-1)); }
25.29321
104
0.587065
200aeed19c847f9e7f6959f2f19a9af7eee99f9e
2,251
cpp
C++
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
302
2017-03-04T00:05:23.000Z
2022-03-28T22:51:29.000Z
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
30
2017-12-02T19:26:43.000Z
2022-03-28T07:40:36.000Z
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
388
2017-07-04T16:53:12.000Z
2022-03-18T22:20:19.000Z
#include "foointerface.h" #include <QDir> #include <QGuiApplication> #include <QPluginLoader> #include <QQmlApplicationEngine> #include <QTimer> #include <QTranslator> int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QTranslator appTranslator; qDebug() << "appTranslator Loaded?:" << appTranslator.load(":/languages/app.qm"); QTranslator pluginTranslator; qDebug() << "pluginTranslator Loaded?:" << pluginTranslator.load(":/languages/plugin.qm"); FooInterface *fooInterface = nullptr; QDir pluginsDir(QCoreApplication::applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif pluginsDir.cd("plugins"); const QStringList entries = pluginsDir.entryList(QDir::Files); for (const QString &fileName : entries) { QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = pluginLoader.instance(); if (plugin) { fooInterface = qobject_cast<FooInterface *>(plugin); if (fooInterface) break; pluginLoader.unload(); } } QTimer timer; QObject::connect(&timer, &QTimer::timeout, [fooInterface](){ qDebug() << fooInterface->print(); }); timer.start(1000); QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); QTimer::singleShot(1000, &engine, [&](){ QCoreApplication::instance()->installTranslator(&appTranslator); QCoreApplication::instance()->installTranslator(&pluginTranslator); engine.retranslate(); }); return app.exec(); }
30.013333
97
0.646379
200d9fcf6cacbb73137ca211017c7b3b49bc9990
54,260
inl
C++
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
struct ezJniModifiers { enum Enum { PUBLIC = 1, PRIVATE = 2, PROTECTED = 4, STATIC = 8, FINAL = 16, SYNCHRONIZED = 32, VOLATILE = 64, TRANSIENT = 128, NATIVE = 256, INTERFACE = 512, ABSTRACT = 1024, STRICT = 2048, }; }; ezJniObject::ezJniObject(jobject object, ezJniOwnerShip ownerShip) : m_class(nullptr) { switch (ownerShip) { case ezJniOwnerShip::OWN: m_object = object; m_own = true; break; case ezJniOwnerShip::COPY: m_object = ezJniAttachment::GetEnv()->NewLocalRef(object); m_own = true; break; case ezJniOwnerShip::BORROW: m_object = object; m_own = false; break; } } ezJniObject::ezJniObject(const ezJniObject& other) : m_class(nullptr) { m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object); m_own = true; } ezJniObject::ezJniObject(ezJniObject&& other) { m_object = other.m_object; m_class = other.m_class; m_own = other.m_own; other.m_object = nullptr; other.m_class = nullptr; other.m_own = false; } ezJniObject& ezJniObject::operator=(const ezJniObject& other) { if (this == &other) return *this; Reset(); m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object); m_own = true; return *this; } ezJniObject& ezJniObject::operator=(ezJniObject&& other) { if (this == &other) return *this; Reset(); m_object = other.m_object; m_class = other.m_class; m_own = other.m_own; other.m_object = nullptr; other.m_class = nullptr; other.m_own = false; return *this; } ezJniObject::~ezJniObject() { Reset(); } void ezJniObject::Reset() { if (m_object && m_own) { ezJniAttachment::GetEnv()->DeleteLocalRef(m_object); m_object = nullptr; m_own = false; } if (m_class) { ezJniAttachment::GetEnv()->DeleteLocalRef(m_class); m_class = nullptr; } } jobject ezJniObject::GetJObject() const { return m_object; } bool ezJniObject::operator==(const ezJniObject& other) const { return ezJniAttachment::GetEnv()->IsSameObject(m_object, other.m_object) == JNI_TRUE; } bool ezJniObject::operator!=(const ezJniObject& other) const { return !operator==(other); } // Template specializations to dispatch to the correct JNI method for each C++ type. template <typename T, bool unused = false> struct ezJniTraits { static_assert(unused, "The passed C++ type is not supported by the JNI wrapper. Arguments and returns types must be one of bool, signed char/jbyte, unsigned short/jchar, short/jshort, int/jint, long long/jlong, float/jfloat, double/jdouble, ezJniObject, ezJniString or ezJniClass."); // Places the argument inside a jvalue union. static jvalue ToValue(T); // Retrieves the Java class static type of the argument. For primitives, this is not the boxed type, but the primitive type. static ezJniClass GetStaticType(); // Retrieves the Java class dynamic type of the argument. For primitives, this is not the boxed type, but the primitive type. static ezJniClass GetRuntimeType(T); // Creates an invalid/null object to return in case of errors. static T GetEmptyObject(); // Call an instance method with the return type. template <typename... Args> static T CallInstanceMethod(jobject self, jmethodID method, const Args&... args); // Call a static method with the return type. template <typename... Args> static T CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); // Sets/gets a field of the type. static void SetField(jobject self, jfieldID field, T); static T GetField(jobject self, jfieldID field); // Sets/gets a static field of the type. static void SetStaticField(jclass clazz, jfieldID field, T); static T GetStaticField(jclass clazz, jfieldID field); // Appends the JNI type signature of this type to the string buf static bool AppendSignature(const T& obj, ezStringBuilder& str); static const char* GetSignatureStatic(); }; template <> struct ezJniTraits<bool> { static inline jvalue ToValue(bool value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(bool); static inline bool GetEmptyObject(); template <typename... Args> static bool CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static bool CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, bool arg); static inline bool GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, bool arg); static inline bool GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(bool, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jbyte> { static inline jvalue ToValue(jbyte value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jbyte); static inline jbyte GetEmptyObject(); template <typename... Args> static jbyte CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jbyte CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jbyte arg); static inline jbyte GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jbyte arg); static inline jbyte GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jbyte, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jchar> { static inline jvalue ToValue(jchar value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jchar); static inline jchar GetEmptyObject(); template <typename... Args> static jchar CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jchar CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jchar arg); static inline jchar GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jchar arg); static inline jchar GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jchar, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jshort> { static inline jvalue ToValue(jshort value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jshort); static inline jshort GetEmptyObject(); template <typename... Args> static jshort CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jshort CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jshort arg); static inline jshort GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jshort arg); static inline jshort GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jshort, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jint> { static inline jvalue ToValue(jint value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jint); static inline jint GetEmptyObject(); template <typename... Args> static jint CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jint CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jint arg); static inline jint GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jint arg); static inline jint GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jint, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jlong> { static inline jvalue ToValue(jlong value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jlong); static inline jlong GetEmptyObject(); template <typename... Args> static jlong CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jlong CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jlong arg); static inline jlong GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jlong arg); static inline jlong GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jlong, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jfloat> { static inline jvalue ToValue(jfloat value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jfloat); static inline jfloat GetEmptyObject(); template <typename... Args> static jfloat CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jfloat CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jfloat arg); static inline jfloat GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jfloat arg); static inline jfloat GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jfloat, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jdouble> { static inline jvalue ToValue(jdouble value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jdouble); static inline jdouble GetEmptyObject(); template <typename... Args> static jdouble CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jdouble CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jdouble arg); static inline jdouble GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jdouble arg); static inline jdouble GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jdouble, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniObject> { static inline jvalue ToValue(const ezJniObject& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniObject& object); static inline ezJniObject GetEmptyObject(); template <typename... Args> static ezJniObject CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniObject CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniObject& arg); static inline ezJniObject GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg); static inline ezJniObject GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniObject& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniClass> { static inline jvalue ToValue(const ezJniClass& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniClass& object); static inline ezJniClass GetEmptyObject(); template <typename... Args> static ezJniClass CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniClass CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniClass& arg); static inline ezJniClass GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg); static inline ezJniClass GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniClass& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniString> { static inline jvalue ToValue(const ezJniString& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniString& object); static inline ezJniString GetEmptyObject(); template <typename... Args> static ezJniString CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniString CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniString& arg); static inline ezJniString GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg); static inline ezJniString GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniString& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<void> { static inline ezJniClass GetStaticType(); static inline void GetEmptyObject(); template <typename... Args> static void CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static void CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline const char* GetSignatureStatic(); }; // Helpers to unpack variadic templates. struct ezJniImpl { static void CollectArgumentTypes(ezJniClass* target) { } template <typename T, typename... Tail> static void CollectArgumentTypes(ezJniClass* target, const T& arg, const Tail&... tail) { *target = ezJniTraits<T>::GetRuntimeType(arg); return ezJniImpl::CollectArgumentTypes(target + 1, tail...); } static void UnpackArgs(jvalue* target) { } template <typename T, typename... Tail> static void UnpackArgs(jvalue* target, const T& arg, const Tail&... tail) { *target = ezJniTraits<T>::ToValue(arg); return UnpackArgs(target + 1, tail...); } template <typename Ret, typename... Args> static bool BuildMethodSignature(ezStringBuilder& signature, const Args&... args) { signature.Append("("); if (!ezJniImpl::AppendSignature(signature, args...)) { return false; } signature.Append(")"); signature.Append(ezJniTraits<Ret>::GetSignatureStatic()); return true; } static bool AppendSignature(ezStringBuilder& signature) { return true; } template <typename T, typename... Tail> static bool AppendSignature(ezStringBuilder& str, const T& arg, const Tail&... tail) { return ezJniTraits<T>::AppendSignature(arg, str) && AppendSignature(str, tail...); } }; jvalue ezJniTraits<bool>::ToValue(bool value) { jvalue result; result.z = value ? JNI_TRUE : JNI_FALSE; return result; } ezJniClass ezJniTraits<bool>::GetStaticType() { return ezJniClass("java/lang/Boolean").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<bool>::GetRuntimeType(bool) { return GetStaticType(); } bool ezJniTraits<bool>::GetEmptyObject() { return false; } template <typename... Args> bool ezJniTraits<bool>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallBooleanMethodA(self, method, array) == JNI_TRUE; } template <typename... Args> bool ezJniTraits<bool>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticBooleanMethodA(clazz, method, array) == JNI_TRUE; } void ezJniTraits<bool>::SetField(jobject self, jfieldID field, bool arg) { return ezJniAttachment::GetEnv()->SetBooleanField(self, field, arg ? JNI_TRUE : JNI_FALSE); } bool ezJniTraits<bool>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetBooleanField(self, field) == JNI_TRUE; } void ezJniTraits<bool>::SetStaticField(jclass clazz, jfieldID field, bool arg) { return ezJniAttachment::GetEnv()->SetStaticBooleanField(clazz, field, arg ? JNI_TRUE : JNI_FALSE); } bool ezJniTraits<bool>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticBooleanField(clazz, field) == JNI_TRUE; } bool ezJniTraits<bool>::AppendSignature(bool, ezStringBuilder& str) { str.Append("Z"); return true; } const char* ezJniTraits<bool>::GetSignatureStatic() { return "Z"; } jvalue ezJniTraits<jbyte>::ToValue(jbyte value) { jvalue result; result.b = value; return result; } ezJniClass ezJniTraits<jbyte>::GetStaticType() { return ezJniClass("java/lang/Byte").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jbyte>::GetRuntimeType(jbyte) { return GetStaticType(); } jbyte ezJniTraits<jbyte>::GetEmptyObject() { return 0; } template <typename... Args> jbyte ezJniTraits<jbyte>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallByteMethodA(self, method, array); } template <typename... Args> jbyte ezJniTraits<jbyte>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticByteMethodA(clazz, method, array); } void ezJniTraits<jbyte>::SetField(jobject self, jfieldID field, jbyte arg) { return ezJniAttachment::GetEnv()->SetByteField(self, field, arg); } jbyte ezJniTraits<jbyte>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetByteField(self, field); } void ezJniTraits<jbyte>::SetStaticField(jclass clazz, jfieldID field, jbyte arg) { return ezJniAttachment::GetEnv()->SetStaticByteField(clazz, field, arg); } jbyte ezJniTraits<jbyte>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticByteField(clazz, field); } bool ezJniTraits<jbyte>::AppendSignature(jbyte, ezStringBuilder& str) { str.Append("B"); return true; } const char* ezJniTraits<jbyte>::GetSignatureStatic() { return "B"; } jvalue ezJniTraits<jchar>::ToValue(jchar value) { jvalue result; result.c = value; return result; } ezJniClass ezJniTraits<jchar>::GetStaticType() { return ezJniClass("java/lang/Character").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jchar>::GetRuntimeType(jchar) { return GetStaticType(); } jchar ezJniTraits<jchar>::GetEmptyObject() { return 0; } template <typename... Args> jchar ezJniTraits<jchar>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallCharMethodA(self, method, array); } template <typename... Args> jchar ezJniTraits<jchar>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticCharMethodA(clazz, method, array); } void ezJniTraits<jchar>::SetField(jobject self, jfieldID field, jchar arg) { return ezJniAttachment::GetEnv()->SetCharField(self, field, arg); } jchar ezJniTraits<jchar>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetCharField(self, field); } void ezJniTraits<jchar>::SetStaticField(jclass clazz, jfieldID field, jchar arg) { return ezJniAttachment::GetEnv()->SetStaticCharField(clazz, field, arg); } jchar ezJniTraits<jchar>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticCharField(clazz, field); } bool ezJniTraits<jchar>::AppendSignature(jchar, ezStringBuilder& str) { str.Append("C"); return true; } const char* ezJniTraits<jchar>::GetSignatureStatic() { return "C"; } jvalue ezJniTraits<jshort>::ToValue(jshort value) { jvalue result; result.s = value; return result; } ezJniClass ezJniTraits<jshort>::GetStaticType() { return ezJniClass("java/lang/Short").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jshort>::GetRuntimeType(jshort) { return GetStaticType(); } jshort ezJniTraits<jshort>::GetEmptyObject() { return 0; } template <typename... Args> jshort ezJniTraits<jshort>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallShortMethodA(self, method, array); } template <typename... Args> jshort ezJniTraits<jshort>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticShortMethodA(clazz, method, array); } void ezJniTraits<jshort>::SetField(jobject self, jfieldID field, jshort arg) { return ezJniAttachment::GetEnv()->SetShortField(self, field, arg); } jshort ezJniTraits<jshort>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetShortField(self, field); } void ezJniTraits<jshort>::SetStaticField(jclass clazz, jfieldID field, jshort arg) { return ezJniAttachment::GetEnv()->SetStaticShortField(clazz, field, arg); } jshort ezJniTraits<jshort>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticShortField(clazz, field); } bool ezJniTraits<jshort>::AppendSignature(jshort, ezStringBuilder& str) { str.Append("S"); return true; } const char* ezJniTraits<jshort>::GetSignatureStatic() { return "S"; } jvalue ezJniTraits<jint>::ToValue(jint value) { jvalue result; result.i = value; return result; } ezJniClass ezJniTraits<jint>::GetStaticType() { return ezJniClass("java/lang/Integer").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jint>::GetRuntimeType(jint) { return GetStaticType(); } jint ezJniTraits<jint>::GetEmptyObject() { return 0; } template <typename... Args> jint ezJniTraits<jint>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallIntMethodA(self, method, array); } template <typename... Args> jint ezJniTraits<jint>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticIntMethodA(clazz, method, array); } void ezJniTraits<jint>::SetField(jobject self, jfieldID field, jint arg) { return ezJniAttachment::GetEnv()->SetIntField(self, field, arg); } jint ezJniTraits<jint>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetIntField(self, field); } void ezJniTraits<jint>::SetStaticField(jclass clazz, jfieldID field, jint arg) { return ezJniAttachment::GetEnv()->SetStaticIntField(clazz, field, arg); } jint ezJniTraits<jint>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticIntField(clazz, field); } bool ezJniTraits<jint>::AppendSignature(jint, ezStringBuilder& str) { str.Append("I"); return true; } const char* ezJniTraits<jint>::GetSignatureStatic() { return "I"; } jvalue ezJniTraits<jlong>::ToValue(jlong value) { jvalue result; result.j = value; return result; } ezJniClass ezJniTraits<jlong>::GetStaticType() { return ezJniClass("java/lang/Long").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jlong>::GetRuntimeType(jlong) { return GetStaticType(); } jlong ezJniTraits<jlong>::GetEmptyObject() { return 0; } template <typename... Args> jlong ezJniTraits<jlong>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallLongMethodA(self, method, array); } template <typename... Args> jlong ezJniTraits<jlong>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticLongMethodA(clazz, method, array); } void ezJniTraits<jlong>::SetField(jobject self, jfieldID field, jlong arg) { return ezJniAttachment::GetEnv()->SetLongField(self, field, arg); } jlong ezJniTraits<jlong>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetLongField(self, field); } void ezJniTraits<jlong>::SetStaticField(jclass clazz, jfieldID field, jlong arg) { return ezJniAttachment::GetEnv()->SetStaticLongField(clazz, field, arg); } jlong ezJniTraits<jlong>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticLongField(clazz, field); } bool ezJniTraits<jlong>::AppendSignature(jlong, ezStringBuilder& str) { str.Append("J"); return true; } const char* ezJniTraits<jlong>::GetSignatureStatic() { return "J"; } jvalue ezJniTraits<jfloat>::ToValue(jfloat value) { jvalue result; result.f = value; return result; } ezJniClass ezJniTraits<jfloat>::GetStaticType() { return ezJniClass("java/lang/Float").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jfloat>::GetRuntimeType(jfloat) { return GetStaticType(); } jfloat ezJniTraits<jfloat>::GetEmptyObject() { return nanf(""); } template <typename... Args> jfloat ezJniTraits<jfloat>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallFloatMethodA(self, method, array); } template <typename... Args> jfloat ezJniTraits<jfloat>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticFloatMethodA(clazz, method, array); } void ezJniTraits<jfloat>::SetField(jobject self, jfieldID field, jfloat arg) { return ezJniAttachment::GetEnv()->SetFloatField(self, field, arg); } jfloat ezJniTraits<jfloat>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetFloatField(self, field); } void ezJniTraits<jfloat>::SetStaticField(jclass clazz, jfieldID field, jfloat arg) { return ezJniAttachment::GetEnv()->SetStaticFloatField(clazz, field, arg); } jfloat ezJniTraits<jfloat>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticFloatField(clazz, field); } bool ezJniTraits<jfloat>::AppendSignature(jfloat, ezStringBuilder& str) { str.Append("F"); return true; } const char* ezJniTraits<jfloat>::GetSignatureStatic() { return "F"; } jvalue ezJniTraits<jdouble>::ToValue(jdouble value) { jvalue result; result.d = value; return result; } ezJniClass ezJniTraits<jdouble>::GetStaticType() { return ezJniClass("java/lang/Double").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jdouble>::GetRuntimeType(jdouble) { return GetStaticType(); } jdouble ezJniTraits<jdouble>::GetEmptyObject() { return nan(""); } template <typename... Args> jdouble ezJniTraits<jdouble>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallDoubleMethodA(self, method, array); } template <typename... Args> jdouble ezJniTraits<jdouble>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticDoubleMethodA(clazz, method, array); } void ezJniTraits<jdouble>::SetField(jobject self, jfieldID field, jdouble arg) { return ezJniAttachment::GetEnv()->SetDoubleField(self, field, arg); } jdouble ezJniTraits<jdouble>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetDoubleField(self, field); } void ezJniTraits<jdouble>::SetStaticField(jclass clazz, jfieldID field, jdouble arg) { return ezJniAttachment::GetEnv()->SetStaticDoubleField(clazz, field, arg); } jdouble ezJniTraits<jdouble>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticDoubleField(clazz, field); } bool ezJniTraits<jdouble>::AppendSignature(jdouble, ezStringBuilder& str) { str.Append("D"); return true; } const char* ezJniTraits<jdouble>::GetSignatureStatic() { return "D"; } jvalue ezJniTraits<ezJniObject>::ToValue(const ezJniObject& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniObject>::GetStaticType() { return ezJniClass("java/lang/Object"); } ezJniClass ezJniTraits<ezJniObject>::GetRuntimeType(const ezJniObject& arg) { return arg.GetClass(); } ezJniObject ezJniTraits<ezJniObject>::GetEmptyObject() { return ezJniObject(); } template <typename... Args> ezJniObject ezJniTraits<ezJniObject>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array), ezJniOwnerShip::OWN); } template <typename... Args> ezJniObject ezJniTraits<ezJniObject>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniObject>::SetField(jobject self, jfieldID field, const ezJniObject& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniObject ezJniTraits<ezJniObject>::GetField(jobject self, jfieldID field) { return ezJniObject(ezJniAttachment::GetEnv()->GetObjectField(self, field), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniObject>::SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniObject ezJniTraits<ezJniObject>::GetStaticField(jclass clazz, jfieldID field) { return ezJniObject(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniObject>::AppendSignature(const ezJniObject& obj, ezStringBuilder& str) { if (obj.IsNull()) { // Ensure null objects never generate valid signatures in order to force using the reflection path return false; } else { str.Append("L"); str.Append(obj.GetClass().UnsafeCall<ezJniString>("getName", "()Ljava/lang/String;").GetData()); str.ReplaceAll(".", "/"); str.Append(";"); return true; } } const char* ezJniTraits<ezJniObject>::GetSignatureStatic() { return "Ljava/lang/Object;"; } jvalue ezJniTraits<ezJniClass>::ToValue(const ezJniClass& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniClass>::GetStaticType() { return ezJniClass("java/lang/Class"); } ezJniClass ezJniTraits<ezJniClass>::GetRuntimeType(const ezJniClass& arg) { // Assume there are no types derived from Class return GetStaticType(); } ezJniClass ezJniTraits<ezJniClass>::GetEmptyObject() { return ezJniClass(); } template <typename... Args> ezJniClass ezJniTraits<ezJniClass>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN); } template <typename... Args> ezJniClass ezJniTraits<ezJniClass>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniClass>::SetField(jobject self, jfieldID field, const ezJniClass& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniClass ezJniTraits<ezJniClass>::GetField(jobject self, jfieldID field) { return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniClass>::SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniClass ezJniTraits<ezJniClass>::GetStaticField(jclass clazz, jfieldID field) { return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniClass>::AppendSignature(const ezJniClass& obj, ezStringBuilder& str) { str.Append("Ljava/lang/Class;"); return true; } const char* ezJniTraits<ezJniClass>::GetSignatureStatic() { return "Ljava/lang/Class;"; } jvalue ezJniTraits<ezJniString>::ToValue(const ezJniString& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniString>::GetStaticType() { return ezJniClass("java/lang/String"); } ezJniClass ezJniTraits<ezJniString>::GetRuntimeType(const ezJniString& arg) { // Assume there are no types derived from String return GetStaticType(); } ezJniString ezJniTraits<ezJniString>::GetEmptyObject() { return ezJniString(); } template <typename... Args> ezJniString ezJniTraits<ezJniString>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniString(jstring(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN); } template <typename... Args> ezJniString ezJniTraits<ezJniString>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniString(jstring(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniString>::SetField(jobject self, jfieldID field, const ezJniString& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniString ezJniTraits<ezJniString>::GetField(jobject self, jfieldID field) { return ezJniString(jstring(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniString>::SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniString ezJniTraits<ezJniString>::GetStaticField(jclass clazz, jfieldID field) { return ezJniString(jstring(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniString>::AppendSignature(const ezJniString& obj, ezStringBuilder& str) { str.Append("Ljava/lang/String;"); return true; } const char* ezJniTraits<ezJniString>::GetSignatureStatic() { return "Ljava/lang/String;"; } ezJniClass ezJniTraits<void>::GetStaticType() { return ezJniClass("java/lang/Void").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } void ezJniTraits<void>::GetEmptyObject() { return; } template <typename... Args> void ezJniTraits<void>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallVoidMethodA(self, method, array); } template <typename... Args> void ezJniTraits<void>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticVoidMethodA(clazz, method, array); } const char* ezJniTraits<void>::GetSignatureStatic() { return "V"; } template <typename... Args> ezJniObject ezJniClass::CreateInstance(const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniObject(); } const size_t N = sizeof...(args); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindConstructor(*this, inputTypes, N); if (foundMethod.IsNull()) { return ezJniObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle()); jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->NewObjectA(GetHandle(), method, array), ezJniOwnerShip::OWN); } template <typename Ret, typename... Args> Ret ezJniClass::CallStatic(const char* name, const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!GetJObject()) { ezLog::Error("Attempting to call static method '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } ezStringBuilder signature; if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...)) { jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature.GetData()); if (method) { return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } } const size_t N = sizeof...(args); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindMethod(true, name, *this, returnType, inputTypes, N); if (foundMethod.IsNull()) { return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle()); return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } template <typename Ret, typename... Args> Ret ezJniClass::UnsafeCallStatic(const char* name, const char* signature, const Args&... args) const { if (!GetJObject()) { ezLog::Error("Attempting to call static method '{}' on null class.", name); ezLog::Error("Attempting to call static method '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature); if (!method) { ezLog::Error("No such static method: '{}' with signature '{}' in class '{}'.", name, signature, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } } template <typename Ret> Ret ezJniClass::GetStaticField(const char* name) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!GetJObject()) { ezLog::Error("Attempting to get static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID fieldID = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic()); if (fieldID) { return ezJniTraits<Ret>::GetStaticField(GetHandle(), fieldID); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) == 0) { ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); if (!returnType.IsAssignableFrom(fieldType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), ToString().GetData(), returnType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } return ezJniTraits<Ret>::GetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle())); } template <typename Ret> Ret ezJniClass::UnsafeGetStaticField(const char* name, const char* signature) const { if (!GetJObject()) { ezLog::Error("Attempting to get static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::GetStaticField(GetHandle(), field); } } template <typename T> void ezJniClass::SetStaticField(const char* name, const T& arg) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return; } if (!GetJObject()) { ezLog::Error("Attempting to set static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass modifierClass("java/lang/reflect/Modifier"); jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I"); if ((modifiers & ezJniModifiers::STATIC) == 0) { ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } if ((modifiers & ezJniModifiers::FINAL) != 0) { ezLog::Error("Field named '{}' in class '{}' is final.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg); if (argType.IsNull()) { if (fieldType.IsPrimitive()) { ezLog::Error("Field '{}' of type '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } else { if (!fieldType.IsAssignableFrom(argType)) { ezLog::Error("Field '{}' of type '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), argType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } return ezJniTraits<T>::SetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg); } template <typename T> void ezJniClass::UnsafeSetStaticField(const char* name, const char* signature, const T& arg) const { if (!GetJObject()) { ezLog::Error("Attempting to set static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<T>::SetStaticField(GetHandle(), field, arg); } } template <typename Ret, typename... Args> Ret ezJniObject::Call(const char* name, const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!m_object) { ezLog::Error("Attempting to call method '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } // Fast path: Lookup method via signature built from parameters. // This only works for exact matches, but is roughly 50 times faster. ezStringBuilder signature; if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...)) { jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(reinterpret_cast<jclass>(GetClass().GetHandle()), name, signature.GetData()); if (method) { return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } } // Fallback to slow path using reflection const size_t N = sizeof...(args); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindMethod(false, name, GetClass(), returnType, inputTypes, N); if (foundMethod.IsNull()) { return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.m_object); return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } template <typename Ret, typename... Args> Ret ezJniObject::UnsafeCall(const char* name, const char* signature, const Args&... args) const { if (!m_object) { ezLog::Error("Attempting to call method '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(jclass(GetClass().m_object), name, signature); if (!method) { ezLog::Error("No such method: '{}' with signature '{}' in class '{}'.", name, signature, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } } template <typename T> void ezJniObject::SetField(const char* name, const T& arg) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return; } if (!m_object) { ezLog::Error("Attempting to set field '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } // No fast path here since we need to be able to report failures when attempting // to set final fields, which we can only do using reflection. ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found.", name); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass modifierClass("java/lang/reflect/Modifier"); jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I"); if ((modifiers & ezJniModifiers::STATIC) != 0) { ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } if ((modifiers & ezJniModifiers::FINAL) != 0) { ezLog::Error("Field named '{}' in class '{}' is final.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg); if (argType.IsNull()) { if (fieldType.IsPrimitive()) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } else { if (!fieldType.IsAssignableFrom(argType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), argType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } return ezJniTraits<T>::SetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg); } template <typename T> void ezJniObject::UnsafeSetField(const char* name, const char* signature, const T& arg) const { if (!m_object) { ezLog::Error("Attempting to set field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(jclass(GetClass().GetHandle()), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<T>::SetField(m_object, field, arg); } } template <typename Ret> Ret ezJniObject::GetField(const char* name) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!m_object) { ezLog::Error("Attempting to get field '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID fieldID = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic()); if (fieldID) { return ezJniTraits<Ret>::GetField(m_object, fieldID); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) != 0) { ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); if (!returnType.IsAssignableFrom(fieldType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), returnType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } return ezJniTraits<Ret>::GetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle())); } template <typename Ret> Ret ezJniObject::UnsafeGetField(const char* name, const char* signature) const { if (!m_object) { ezLog::Error("Attempting to get field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<Ret>::GetField(m_object, field); } }
29.298056
285
0.729414
201039418cb79f69a96c443540e3dd27e909876a
3,458
cpp
C++
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
41
2016-04-09T07:48:10.000Z
2022-03-01T15:46:08.000Z
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
9
2015-09-23T10:54:50.000Z
2020-01-04T21:16:57.000Z
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
29
2015-10-01T14:44:42.000Z
2022-01-05T01:28:43.000Z
// // Coypright (c) 2021 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // #include "stdafx.h" #include "FgSerial.hpp" #include "FgCommand.hpp" using namespace std; namespace Fg { void srlz_(bool v,String & s) { uchar b = v ? 1 : 0; srlz_(b,s); } void dsrlz_(String const & s,size_t & p,bool & v) { uchar b; dsrlz_(s,p,b); v = (b == 1); } void dsrlz_(String const & s,size_t & p,long & v) { int64 t; dsrlzRaw_(s,p,t); FGASSERT(t >= std::numeric_limits<long>::lowest()); FGASSERT(t <= std::numeric_limits<long>::max()); v = static_cast<long>(t); } void dsrlz_(String const & s,size_t & p,unsigned long & v) { uint64 t; dsrlzRaw_(s,p,t); FGASSERT(t <= std::numeric_limits<unsigned long>::max()); v = static_cast<unsigned long>(t); } void srlz_(String const & v,String & s) { srlz_(uint64(v.size()),s); s.append(v); } void dsrlz_(String const & s,size_t & p,String & v) { uint64 sz; dsrlz_(s,p,sz); FGASSERT(p+sz <= s.size()); v.assign(s,p,size_t(sz)); p += sz; } namespace { void test0() { int i = 42; FGASSERT(i == dsrlz<int>(srlz(i))); uint u = 42U; FGASSERT(u == dsrlz<uint>(srlz(u))); long l = 42L; FGASSERT(l == dsrlz<long>(srlz(l))); long long ll = 42LL; FGASSERT(ll == dsrlz<long long>(srlz(ll))); unsigned long long ull = 42ULL; FGASSERT(ull == dsrlz<unsigned long long>(srlz(ull))); String s = "Test String"; FGASSERT(s == dsrlz<String>(srlz(s))); } void test1() { Strings tns; int a = 5; double b = 3.14; typeNames_(tns,a,b); fgout << fgnl << tns; } } struct A { int i; float f; }; FG_SERIAL_2(A,i,f) struct B { A a; double d; }; FG_SERIAL_2(B,a,d) struct Op { double acc {0}; template<typename T> void operator()(T r) {acc += double(r); } }; void traverseMembers_(Op & op,int s) {op(s); } void traverseMembers_(Op & op,float s) {op(s); } void traverseMembers_(Op & op,double s) {op(s); } void test2() { Strings names; reflectNames_<B>(names); fgout << fgnl << names; A a {3,0.1f}; B b {a,2.7}; Op op; traverseMembers_(op,b); fgout << fgnl << "Acc: " << op.acc; } void testSerial(CLArgs const &) { test0(); test1(); test2(); { Svec<string> in {"first","second"}, out = dsrlz<Strings>(srlz(in)); FGASSERT(in == out); } { String8 dd = dataDir() + "base/test/"; String msg = "This is a test", ser = srlz(msg); //saveRaw(ser,dd+"serial32"); //saveRaw(ser,dd+"serial64"); String msg32 = dsrlz<String>(loadRaw(dd+"serial32")), msg64 = dsrlz<String>(loadRaw(dd+"serial64")); FGASSERT(msg32 == msg); FGASSERT(msg64 == msg); } } }
21.214724
79
0.484095
2010aeff4c31c302980dd1eb4e0e5ecc25b2f041
3,544
hpp
C++
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
62
2016-08-02T05:15:16.000Z
2020-02-14T18:02:34.000Z
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
6
2016-12-07T03:00:46.000Z
2018-12-03T22:03:27.000Z
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
6
2016-12-10T18:59:18.000Z
2019-11-05T08:11:11.000Z
// (C) Copyright 2016 - 2018 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <new> #include <strict_variant/mpl/max.hpp> #include <strict_variant/mpl/typelist.hpp> #include <strict_variant/wrapper.hpp> #include <utility> namespace strict_variant { namespace detail { // Implementation note: // Internal visitors need to be able to access the "true" type, the // reference_wrapper<T> when it is within the variant, to implement ctors // and special memeber functions. // External visitors are supposed to have this elided. // The `get_value` function uses tag dispatch to do the right thing. struct true_ {}; struct false_ {}; // Storage for the types in a list of types. // Provides typed access using the index within the list as a template parameter. // And some facilities for piercing recursive_wrapper template <typename First, typename... Types> struct storage { /*** * Determine size and alignment of our storage */ template <typename T> struct Sizeof { static constexpr size_t value = sizeof(T); }; template <typename T> struct Alignof { static constexpr size_t value = alignof(T); }; // size = max of size of each thing static constexpr size_t m_size = mpl::max<Sizeof, First, Types...>::value; // align = max align of each thing static constexpr size_t m_align = mpl::max<Alignof, First, Types...>::value; /*** * Storage */ // alignas(m_align) char m_storage[m_size]; using aligned_storage_t = typename std::aligned_storage<m_size, m_align>::type; aligned_storage_t m_storage; void * address() { return reinterpret_cast<void *>(&m_storage); } const void * address() const { return reinterpret_cast<const void *>(&m_storage); } /*** * Index -> Type */ using my_types = mpl::TypeList<First, Types...>; template <size_t index> using value_t = mpl::Index_At<my_types, index>; /*** * Initialize to the type at a particular value */ template <size_t index, typename... Args> void initialize(Args &&... args) noexcept( noexcept(value_t<index>(std::forward<Args>(std::declval<Args>())...))) { new (this->address()) value_t<index>(std::forward<Args>(args)...); } /*** * Typed access which pierces recursive_wrapper if detail::false_ is passed * "Internal" (non-piercing) access is achieved if detail::true_ is passed */ template <size_t index> value_t<index> & get_value(detail::true_) & { return *reinterpret_cast<value_t<index> *>(this->address()); } template <size_t index> const value_t<index> & get_value(detail::true_) const & { return *reinterpret_cast<const value_t<index> *>(this->address()); } template <size_t index> value_t<index> && get_value(detail::true_) && { return std::move(*reinterpret_cast<value_t<index> *>(this->address())); } template <size_t index> unwrap_type_t<value_t<index>> & get_value(detail::false_) & { return detail::pierce_wrapper(this->get_value<index>(detail::true_{})); } template <size_t index> const unwrap_type_t<value_t<index>> & get_value(detail::false_) const & { return detail::pierce_wrapper(this->get_value<index>(detail::true_{})); } template <size_t index> unwrap_type_t<value_t<index>> && get_value(detail::false_) && { return std::move(detail::pierce_wrapper(this->get_value<index>(detail::true_{}))); } }; } // end namespace detail } // end namespace strict_variant
30.033898
86
0.696106
2011bd7f6599a1e61221fc4920e97ecc36e522d7
25,689
cc
C++
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// WARNING: This file is machine generated by fidlgen. #include <fuchsia/blobfs/llcpp/fidl.h> #include <memory> namespace llcpp { namespace fuchsia { namespace blobfs { namespace { [[maybe_unused]] constexpr uint64_t kCorruptBlobHandler_CorruptBlob_Ordinal = 0x432ee88e00000000lu; [[maybe_unused]] constexpr uint64_t kCorruptBlobHandler_CorruptBlob_GenOrdinal = 0x264e37ffa416cdf1lu; extern "C" const fidl_type_t fuchsia_blobfs_CorruptBlobHandlerCorruptBlobRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_CorruptBlobHandlerCorruptBlobResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_CorruptBlobHandlerCorruptBlobResponseTable; } // namespace template <> CorruptBlobHandler::ResultOf::CorruptBlob_Impl<CorruptBlobHandler::CorruptBlobResponse>::CorruptBlob_Impl(::zx::unowned_channel _client_end, ::fidl::VectorView<uint8_t> merkleroot) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<CorruptBlobRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; CorruptBlobRequest _request = {}; _request.merkleroot = std::move(merkleroot); auto _linearize_result = ::fidl::Linearize(&_request, _write_bytes_array.view()); if (_linearize_result.status != ZX_OK) { Super::SetFailure(std::move(_linearize_result)); return; } ::fidl::DecodedMessage<CorruptBlobRequest> _decoded_request = std::move(_linearize_result.message); Super::SetResult( CorruptBlobHandler::InPlace::CorruptBlob(std::move(_client_end), std::move(_decoded_request), Super::response_buffer())); } CorruptBlobHandler::ResultOf::CorruptBlob CorruptBlobHandler::SyncClient::CorruptBlob(::fidl::VectorView<uint8_t> merkleroot) { return ResultOf::CorruptBlob(::zx::unowned_channel(this->channel_), std::move(merkleroot)); } CorruptBlobHandler::ResultOf::CorruptBlob CorruptBlobHandler::Call::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::VectorView<uint8_t> merkleroot) { return ResultOf::CorruptBlob(std::move(_client_end), std::move(merkleroot)); } template <> CorruptBlobHandler::UnownedResultOf::CorruptBlob_Impl<CorruptBlobHandler::CorruptBlobResponse>::CorruptBlob_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { if (_request_buffer.capacity() < CorruptBlobRequest::PrimarySize) { Super::SetFailure(::fidl::DecodeResult<CorruptBlobResponse>(ZX_ERR_BUFFER_TOO_SMALL, ::fidl::internal::kErrorRequestBufferTooSmall)); return; } CorruptBlobRequest _request = {}; _request.merkleroot = std::move(merkleroot); auto _linearize_result = ::fidl::Linearize(&_request, std::move(_request_buffer)); if (_linearize_result.status != ZX_OK) { Super::SetFailure(std::move(_linearize_result)); return; } ::fidl::DecodedMessage<CorruptBlobRequest> _decoded_request = std::move(_linearize_result.message); Super::SetResult( CorruptBlobHandler::InPlace::CorruptBlob(std::move(_client_end), std::move(_decoded_request), std::move(_response_buffer))); } CorruptBlobHandler::UnownedResultOf::CorruptBlob CorruptBlobHandler::SyncClient::CorruptBlob(::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { return UnownedResultOf::CorruptBlob(::zx::unowned_channel(this->channel_), std::move(_request_buffer), std::move(merkleroot), std::move(_response_buffer)); } CorruptBlobHandler::UnownedResultOf::CorruptBlob CorruptBlobHandler::Call::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { return UnownedResultOf::CorruptBlob(std::move(_client_end), std::move(_request_buffer), std::move(merkleroot), std::move(_response_buffer)); } ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse> CorruptBlobHandler::InPlace::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::DecodedMessage<CorruptBlobRequest> params, ::fidl::BytePart response_buffer) { CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<CorruptBlobRequest, CorruptBlobResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool CorruptBlobHandler::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kCorruptBlobHandler_CorruptBlob_Ordinal: case kCorruptBlobHandler_CorruptBlob_GenOrdinal: { auto result = ::fidl::DecodeAs<CorruptBlobRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } auto message = result.message.message(); impl->CorruptBlob(std::move(message->merkleroot), Interface::CorruptBlobCompleter::Sync(txn)); return true; } default: { return false; } } } bool CorruptBlobHandler::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::llcpp::fuchsia::blobfs::TakeAction action) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<CorruptBlobResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<CorruptBlobResponse*>(_write_bytes); CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse( ::fidl::DecodedMessage<CorruptBlobResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), CorruptBlobResponse::PrimarySize, CorruptBlobResponse::PrimarySize))); _response.action = std::move(action); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(CorruptBlobResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<CorruptBlobResponse>(std::move(_response_bytes))); } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::fidl::BytePart _buffer, ::llcpp::fuchsia::blobfs::TakeAction action) { if (_buffer.capacity() < CorruptBlobResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<CorruptBlobResponse*>(_buffer.data()); CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse( ::fidl::DecodedMessage<CorruptBlobResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), CorruptBlobResponse::PrimarySize, CorruptBlobResponse::PrimarySize))); _response.action = std::move(action); _buffer.set_actual(sizeof(CorruptBlobResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<CorruptBlobResponse>(std::move(_buffer))); } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::fidl::DecodedMessage<CorruptBlobResponse> params) { CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse(params); CompleterBase::SendReply(std::move(params)); } void CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobRequest(const ::fidl::DecodedMessage<CorruptBlobHandler::CorruptBlobRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kCorruptBlobHandler_CorruptBlob_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse(const ::fidl::DecodedMessage<CorruptBlobHandler::CorruptBlobResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kCorruptBlobHandler_CorruptBlob_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } namespace { [[maybe_unused]] constexpr uint64_t kBlobfsAdmin_HandleCorruptBlobs_Ordinal = 0x22c0c04c00000000lu; [[maybe_unused]] constexpr uint64_t kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal = 0x5f405690ad00f87elu; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsResponseTable; } // namespace template <> BlobfsAdmin::ResultOf::HandleCorruptBlobs_Impl<BlobfsAdmin::HandleCorruptBlobsResponse>::HandleCorruptBlobs_Impl(::zx::unowned_channel _client_end, ::zx::channel handler) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<HandleCorruptBlobsRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; uint8_t* _write_bytes = _write_bytes_array.view().data(); memset(_write_bytes, 0, HandleCorruptBlobsRequest::PrimarySize); auto& _request = *reinterpret_cast<HandleCorruptBlobsRequest*>(_write_bytes); _request.handler = std::move(handler); ::fidl::BytePart _request_bytes(_write_bytes, _kWriteAllocSize, sizeof(HandleCorruptBlobsRequest)); ::fidl::DecodedMessage<HandleCorruptBlobsRequest> _decoded_request(std::move(_request_bytes)); Super::SetResult( BlobfsAdmin::InPlace::HandleCorruptBlobs(std::move(_client_end), std::move(_decoded_request), Super::response_buffer())); } BlobfsAdmin::ResultOf::HandleCorruptBlobs BlobfsAdmin::SyncClient::HandleCorruptBlobs(::zx::channel handler) { return ResultOf::HandleCorruptBlobs(::zx::unowned_channel(this->channel_), std::move(handler)); } BlobfsAdmin::ResultOf::HandleCorruptBlobs BlobfsAdmin::Call::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::zx::channel handler) { return ResultOf::HandleCorruptBlobs(std::move(_client_end), std::move(handler)); } template <> BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs_Impl<BlobfsAdmin::HandleCorruptBlobsResponse>::HandleCorruptBlobs_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { if (_request_buffer.capacity() < HandleCorruptBlobsRequest::PrimarySize) { Super::SetFailure(::fidl::DecodeResult<HandleCorruptBlobsResponse>(ZX_ERR_BUFFER_TOO_SMALL, ::fidl::internal::kErrorRequestBufferTooSmall)); return; } memset(_request_buffer.data(), 0, HandleCorruptBlobsRequest::PrimarySize); auto& _request = *reinterpret_cast<HandleCorruptBlobsRequest*>(_request_buffer.data()); _request.handler = std::move(handler); _request_buffer.set_actual(sizeof(HandleCorruptBlobsRequest)); ::fidl::DecodedMessage<HandleCorruptBlobsRequest> _decoded_request(std::move(_request_buffer)); Super::SetResult( BlobfsAdmin::InPlace::HandleCorruptBlobs(std::move(_client_end), std::move(_decoded_request), std::move(_response_buffer))); } BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs BlobfsAdmin::SyncClient::HandleCorruptBlobs(::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { return UnownedResultOf::HandleCorruptBlobs(::zx::unowned_channel(this->channel_), std::move(_request_buffer), std::move(handler), std::move(_response_buffer)); } BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs BlobfsAdmin::Call::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { return UnownedResultOf::HandleCorruptBlobs(std::move(_client_end), std::move(_request_buffer), std::move(handler), std::move(_response_buffer)); } ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse> BlobfsAdmin::InPlace::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::fidl::DecodedMessage<HandleCorruptBlobsRequest> params, ::fidl::BytePart response_buffer) { BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<HandleCorruptBlobsRequest, HandleCorruptBlobsResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool BlobfsAdmin::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kBlobfsAdmin_HandleCorruptBlobs_Ordinal: case kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal: { auto result = ::fidl::DecodeAs<HandleCorruptBlobsRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } auto message = result.message.message(); impl->HandleCorruptBlobs(std::move(message->handler), Interface::HandleCorruptBlobsCompleter::Sync(txn)); return true; } default: { return false; } } } bool BlobfsAdmin::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(int32_t status) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<HandleCorruptBlobsResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<HandleCorruptBlobsResponse*>(_write_bytes); BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse( ::fidl::DecodedMessage<HandleCorruptBlobsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), HandleCorruptBlobsResponse::PrimarySize, HandleCorruptBlobsResponse::PrimarySize))); _response.status = std::move(status); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(HandleCorruptBlobsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<HandleCorruptBlobsResponse>(std::move(_response_bytes))); } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(::fidl::BytePart _buffer, int32_t status) { if (_buffer.capacity() < HandleCorruptBlobsResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<HandleCorruptBlobsResponse*>(_buffer.data()); BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse( ::fidl::DecodedMessage<HandleCorruptBlobsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), HandleCorruptBlobsResponse::PrimarySize, HandleCorruptBlobsResponse::PrimarySize))); _response.status = std::move(status); _buffer.set_actual(sizeof(HandleCorruptBlobsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<HandleCorruptBlobsResponse>(std::move(_buffer))); } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(::fidl::DecodedMessage<HandleCorruptBlobsResponse> params) { BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse(params); CompleterBase::SendReply(std::move(params)); } void BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsRequest(const ::fidl::DecodedMessage<BlobfsAdmin::HandleCorruptBlobsRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse(const ::fidl::DecodedMessage<BlobfsAdmin::HandleCorruptBlobsResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } namespace { [[maybe_unused]] constexpr uint64_t kBlobfs_GetAllocatedRegions_Ordinal = 0xf6a24a800000000lu; [[maybe_unused]] constexpr uint64_t kBlobfs_GetAllocatedRegions_GenOrdinal = 0x3e4b9606dbb8073dlu; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsGetAllocatedRegionsRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsGetAllocatedRegionsResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_BlobfsGetAllocatedRegionsResponseTable; } // namespace template <> Blobfs::ResultOf::GetAllocatedRegions_Impl<Blobfs::GetAllocatedRegionsResponse>::GetAllocatedRegions_Impl(::zx::unowned_channel _client_end) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<GetAllocatedRegionsRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; uint8_t* _write_bytes = _write_bytes_array.view().data(); memset(_write_bytes, 0, GetAllocatedRegionsRequest::PrimarySize); ::fidl::BytePart _request_bytes(_write_bytes, _kWriteAllocSize, sizeof(GetAllocatedRegionsRequest)); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> _decoded_request(std::move(_request_bytes)); Super::SetResult( Blobfs::InPlace::GetAllocatedRegions(std::move(_client_end), Super::response_buffer())); } Blobfs::ResultOf::GetAllocatedRegions Blobfs::SyncClient::GetAllocatedRegions() { return ResultOf::GetAllocatedRegions(::zx::unowned_channel(this->channel_)); } Blobfs::ResultOf::GetAllocatedRegions Blobfs::Call::GetAllocatedRegions(::zx::unowned_channel _client_end) { return ResultOf::GetAllocatedRegions(std::move(_client_end)); } template <> Blobfs::UnownedResultOf::GetAllocatedRegions_Impl<Blobfs::GetAllocatedRegionsResponse>::GetAllocatedRegions_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _response_buffer) { FIDL_ALIGNDECL uint8_t _write_bytes[sizeof(GetAllocatedRegionsRequest)] = {}; ::fidl::BytePart _request_buffer(_write_bytes, sizeof(_write_bytes)); memset(_request_buffer.data(), 0, GetAllocatedRegionsRequest::PrimarySize); _request_buffer.set_actual(sizeof(GetAllocatedRegionsRequest)); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> _decoded_request(std::move(_request_buffer)); Super::SetResult( Blobfs::InPlace::GetAllocatedRegions(std::move(_client_end), std::move(_response_buffer))); } Blobfs::UnownedResultOf::GetAllocatedRegions Blobfs::SyncClient::GetAllocatedRegions(::fidl::BytePart _response_buffer) { return UnownedResultOf::GetAllocatedRegions(::zx::unowned_channel(this->channel_), std::move(_response_buffer)); } Blobfs::UnownedResultOf::GetAllocatedRegions Blobfs::Call::GetAllocatedRegions(::zx::unowned_channel _client_end, ::fidl::BytePart _response_buffer) { return UnownedResultOf::GetAllocatedRegions(std::move(_client_end), std::move(_response_buffer)); } ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse> Blobfs::InPlace::GetAllocatedRegions(::zx::unowned_channel _client_end, ::fidl::BytePart response_buffer) { constexpr uint32_t _write_num_bytes = sizeof(GetAllocatedRegionsRequest); ::fidl::internal::AlignedBuffer<_write_num_bytes> _write_bytes; ::fidl::BytePart _request_buffer = _write_bytes.view(); _request_buffer.set_actual(_write_num_bytes); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> params(std::move(_request_buffer)); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<GetAllocatedRegionsRequest, GetAllocatedRegionsResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool Blobfs::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kBlobfs_GetAllocatedRegions_Ordinal: case kBlobfs_GetAllocatedRegions_GenOrdinal: { auto result = ::fidl::DecodeAs<GetAllocatedRegionsRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } impl->GetAllocatedRegions( Interface::GetAllocatedRegionsCompleter::Sync(txn)); return true; } default: { return false; } } } bool Blobfs::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(int32_t status, ::zx::vmo regions, uint64_t count) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<GetAllocatedRegionsResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<GetAllocatedRegionsResponse*>(_write_bytes); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse( ::fidl::DecodedMessage<GetAllocatedRegionsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), GetAllocatedRegionsResponse::PrimarySize, GetAllocatedRegionsResponse::PrimarySize))); _response.status = std::move(status); _response.regions = std::move(regions); _response.count = std::move(count); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(GetAllocatedRegionsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<GetAllocatedRegionsResponse>(std::move(_response_bytes))); } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(::fidl::BytePart _buffer, int32_t status, ::zx::vmo regions, uint64_t count) { if (_buffer.capacity() < GetAllocatedRegionsResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<GetAllocatedRegionsResponse*>(_buffer.data()); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse( ::fidl::DecodedMessage<GetAllocatedRegionsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), GetAllocatedRegionsResponse::PrimarySize, GetAllocatedRegionsResponse::PrimarySize))); _response.status = std::move(status); _response.regions = std::move(regions); _response.count = std::move(count); _buffer.set_actual(sizeof(GetAllocatedRegionsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<GetAllocatedRegionsResponse>(std::move(_buffer))); } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(::fidl::DecodedMessage<GetAllocatedRegionsResponse> params) { Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse(params); CompleterBase::SendReply(std::move(params)); } void Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsRequest(const ::fidl::DecodedMessage<Blobfs::GetAllocatedRegionsRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfs_GetAllocatedRegions_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse(const ::fidl::DecodedMessage<Blobfs::GetAllocatedRegionsResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfs_GetAllocatedRegions_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } } // namespace blobfs } // namespace fuchsia } // namespace llcpp
50.668639
258
0.774767
2015aff915e56298a3280bbb6ab5fdeccd658cd5
5,772
cxx
C++
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "Ruler.hxx" #include <svl/ptitem.hxx> #include <svx/ruler.hxx> #ifndef _SVXIDS_HXX //autogen #include <svx/svxids.hrc> #endif #include <sfx2/ctrlitem.hxx> #include <sfx2/bindings.hxx> #include "View.hxx" #include "DrawViewShell.hxx" #include "Window.hxx" #include "helpids.h" namespace sd { /************************************************************************* |* |* Controller-Item fuer Ruler |* \************************************************************************/ class RulerCtrlItem : public SfxControllerItem { Ruler &rRuler; protected: virtual void StateChanged( sal_uInt16 nSId, SfxItemState eState, const SfxPoolItem* pItem ); public: RulerCtrlItem(sal_uInt16 nId, Ruler& rRlr, SfxBindings& rBind); }; /************************************************************************* |* \************************************************************************/ RulerCtrlItem::RulerCtrlItem(sal_uInt16 _nId, Ruler& rRlr, SfxBindings& rBind) : SfxControllerItem(_nId, rBind) , rRuler(rRlr) { } /************************************************************************* |* \************************************************************************/ void RulerCtrlItem::StateChanged( sal_uInt16 nSId, SfxItemState, const SfxPoolItem* pState ) { switch( nSId ) { case SID_RULER_NULL_OFFSET: { const SfxPointItem* pItem = dynamic_cast< const SfxPointItem* >(pState); DBG_ASSERT(pState ? pItem != NULL : sal_True, "SfxPointItem erwartet"); if ( pItem ) rRuler.SetNullOffset(pItem->GetValue()); } break; } } /************************************************************************* |* |* Konstruktor |* \************************************************************************/ Ruler::Ruler( DrawViewShell& rViewSh, ::Window* pParent, ::sd::Window* pWin, sal_uInt16 nRulerFlags, SfxBindings& rBindings, WinBits nWinStyle) : SvxRuler(pParent, pWin, nRulerFlags, rBindings, nWinStyle) , pSdWin(pWin) , pDrViewShell(&rViewSh) { rBindings.EnterRegistrations(); pCtrlItem = new RulerCtrlItem(SID_RULER_NULL_OFFSET, *this, rBindings); rBindings.LeaveRegistrations(); if ( nWinStyle & WB_HSCROLL ) { bHorz = sal_True; SetHelpId( HID_SD_RULER_HORIZONTAL ); } else { bHorz = sal_False; SetHelpId( HID_SD_RULER_VERTICAL ); } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ Ruler::~Ruler() { SfxBindings& rBindings = pCtrlItem->GetBindings(); rBindings.EnterRegistrations(); delete pCtrlItem; rBindings.LeaveRegistrations(); } /************************************************************************* |* |* MouseButtonDown-Handler |* \************************************************************************/ void Ruler::MouseButtonDown(const MouseEvent& rMEvt) { Point aMPos = rMEvt.GetPosPixel(); RulerType eType = GetType(aMPos); if ( !pDrViewShell->GetView()->IsTextEdit() && rMEvt.IsLeft() && rMEvt.GetClicks() == 1 && (eType == RULER_TYPE_DONTKNOW || eType == RULER_TYPE_OUTSIDE) ) { pDrViewShell->StartRulerDrag(*this, rMEvt); } else SvxRuler::MouseButtonDown(rMEvt); } /************************************************************************* |* |* MouseMove-Handler |* \************************************************************************/ void Ruler::MouseMove(const MouseEvent& rMEvt) { SvxRuler::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-Handler |* \************************************************************************/ void Ruler::MouseButtonUp(const MouseEvent& rMEvt) { SvxRuler::MouseButtonUp(rMEvt); } /************************************************************************* |* |* NullOffset setzen |* \************************************************************************/ void Ruler::SetNullOffset(const Point& rOffset) { long nOffset; if ( bHorz ) nOffset = rOffset.X(); else nOffset = rOffset.Y(); SetNullOffsetLogic(nOffset); } /************************************************************************* |* |* Command event |* \************************************************************************/ void Ruler::Command(const CommandEvent& rCEvt) { if( rCEvt.GetCommand() == COMMAND_CONTEXTMENU && !pDrViewShell->GetView()->IsTextEdit() ) { SvxRuler::Command( rCEvt ); } } /************************************************************************* |* |* ExtraDown |* \************************************************************************/ void Ruler::ExtraDown() { if( !pDrViewShell->GetView()->IsTextEdit() ) SvxRuler::ExtraDown(); } } // end of namespace sd
25.883408
145
0.495669
2016fc451b4a8820fea9720af0f7d82da85c557c
6,850
cpp
C++
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
4
2015-08-13T08:25:36.000Z
2017-04-07T21:33:10.000Z
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
// // CShaderProgramOGLES1_0.h // OpenJam // // Created by Yevgeniy Logachev // Copyright (c) 2014 yev. All rights reserved. // #if defined(RENDER_OGLES1_0) #include "CShaderProgramOGLES1_0.h" using namespace jam; // ***************************************************************************** // Constants // ***************************************************************************** // ***************************************************************************** // Public Methods // ***************************************************************************** CShaderProgramOGLES1_0::CShaderProgramOGLES1_0() : m_ProectionMatrixHadle(-1u) , m_ModelMatrixHadle(-1u) , m_VertexCoordHandle(-1u) , m_VertexNormalHandle(-1u) , m_TextureCoordHandle(-1u) , m_VertexColorHandle(-1u) , m_ColorHandle(-1u) , m_IsLinked(false) { } CShaderProgramOGLES1_0::~CShaderProgramOGLES1_0() { } void CShaderProgramOGLES1_0::Bind() { } void CShaderProgramOGLES1_0::Unbind() { } void CShaderProgramOGLES1_0::AttachShader(IShaderPtr shader) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shader->Type()); if (it != m_AttachedShaders.end()) { m_AttachedShaders.erase(it); } m_AttachedShaders[shader->Type()] = shader; } void CShaderProgramOGLES1_0::DetachShader(IShader::ShaderType shaderType) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType); if (it != m_AttachedShaders.end()) { m_AttachedShaders.erase(it); } } bool CShaderProgramOGLES1_0::IsShaderAttached(IShader::ShaderType shaderType) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType); return (it != m_AttachedShaders.end()); } bool CShaderProgramOGLES1_0::IsValid() { return (IsShaderAttached(IShader::Vertex) && IsShaderAttached(IShader::Fragment)); } bool CShaderProgramOGLES1_0::Link() { m_VertexCoordHandle = Attribute("MainVertexPosition"); m_TextureCoordHandle = Attribute("MainVertexUV"); m_VertexColorHandle = Attribute("MainVertexColor"); m_TextureDataHadle.resize(6); for (size_t i = 0; i < m_TextureDataHadle.size(); ++i) { m_TextureDataHadle[i] = -1u; } m_TextureDataHadle[0] = Uniform("MainTexture0"); m_TextureDataHadle[1] = Uniform("MainTexture1"); m_TextureDataHadle[2] = Uniform("MainTexture2"); m_TextureDataHadle[3] = Uniform("MainTexture3"); m_TextureDataHadle[4] = Uniform("MainTexture4"); m_TextureDataHadle[5] = Uniform("MainTexture5"); m_ColorHandle = Uniform("MainColor"); m_ProectionMatrixHadle = Uniform("MainProjectionMatrix"); m_ModelMatrixHadle = Uniform("MainModelMatrix"); m_IsLinked = true; return m_IsLinked; } bool CShaderProgramOGLES1_0::IsLinked() const { return m_IsLinked; } uint32_t CShaderProgramOGLES1_0::Attribute(const std::string& name) { static std::unordered_map<std::string, int> attributes = { { "MainVertexPosition", 0 }, { "MainVertexUV", 1 }, { "MainVertexColor", 2 } }; if (attributes.find(name) != attributes.end()) { return attributes[name]; } return -1u; } uint32_t CShaderProgramOGLES1_0::Uniform(const std::string& name) { static std::unordered_map<std::string, int> uniforms = { { "MainTexture0", 0 }, { "MainTexture1", 1 }, { "MainTexture2", 2 }, { "MainTexture3", 3 }, { "MainTexture4", 4 }, { "MainTexture5", 5 }, { "MainColor", 6 }, { "MainProjectionMatrix", 7 }, { "MainModelMatrix", 8 }, }; if (uniforms.find(name) != uniforms.end()) { return uniforms[name]; } return -1u; } uint32_t CShaderProgramOGLES1_0::VertexPosition() { return m_VertexCoordHandle; } uint32_t CShaderProgramOGLES1_0::VertexNormal() { return m_VertexNormalHandle; } uint32_t CShaderProgramOGLES1_0::VertexUV() { return m_TextureCoordHandle; } uint32_t CShaderProgramOGLES1_0::VertexColor() { return m_VertexColorHandle; } uint32_t CShaderProgramOGLES1_0::MainTexture() { return m_TextureDataHadle[0]; } uint32_t CShaderProgramOGLES1_0::MainColor() { return m_ColorHandle; } uint32_t CShaderProgramOGLES1_0::ProjectionMatrix() { return m_ProectionMatrixHadle; } uint32_t CShaderProgramOGLES1_0::ModelMatrix() { return m_ModelMatrixHadle; } uint32_t CShaderProgramOGLES1_0::Texture(uint32_t index) { if (index < 5) { return m_TextureDataHadle[index]; } return -1u; } uint32_t CShaderProgramOGLES1_0::DiffuseTexture() { return m_TextureDataHadle[0]; } uint32_t CShaderProgramOGLES1_0::NormalTexture() { return m_TextureDataHadle[1]; } uint32_t CShaderProgramOGLES1_0::SpecularTexture() { return m_TextureDataHadle[2]; } uint32_t CShaderProgramOGLES1_0::EnvironmentTexture() { return m_TextureDataHadle[3]; } bool CShaderProgramOGLES1_0::BindUniform1i(const std::string& uniform, int value) { m_UniInt[Uniform(uniform)] = { value }; return true; } bool CShaderProgramOGLES1_0::BindUniform1f(const std::string& uniform, float value) { m_UniFloat[Uniform(uniform)] = { value }; return true; } bool CShaderProgramOGLES1_0::BindUniform2i(const std::string& uniform, int value1, int value2) { m_UniInt[Uniform(uniform)] = { value1, value2 }; return true; } bool CShaderProgramOGLES1_0::BindUniform2f(const std::string& uniform, float value1, float value2) { m_UniFloat[Uniform(uniform)] = { value1, value2 }; return true; } bool CShaderProgramOGLES1_0::BindUniformfv(const std::string& uniform, const std::vector<float>& value) { m_UniFloatVec[Uniform(uniform)] = value; return true; } bool CShaderProgramOGLES1_0::BindUniformMatrix4x4f(const std::string& uniform, const glm::mat4x4& value) { m_UniMatrixFloat[Uniform(uniform)] = value; return true; } const IShaderProgram::TUniInt& CShaderProgramOGLES1_0::Uniformsi() const { return m_UniInt; } const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsf() const { return m_UniFloat; } const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsfv() const { return m_UniFloatVec; } const IShaderProgram::TUniMatrix4Float& CShaderProgramOGLES1_0::UniformsMatrix4x4f() const { return m_UniMatrixFloat; } void CShaderProgramOGLES1_0::UpdateUniforms() const { } // ***************************************************************************** // Protected Methods // ***************************************************************************** // ***************************************************************************** // Private Methods // ***************************************************************************** #endif /* defined(RENDER_OGLES1_0) */
24.035088
106
0.643212
2017699eeb176419aca9a82faff09c4c27796912
38,496
cpp
C++
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_geom_ZPP_CutVert #include <hxinc/zpp_nape/geom/ZPP_CutVert.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_CutVert #include <hxinc/zpp_nape/util/ZNPList_ZPP_CutVert.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_CutVert #include <hxinc/zpp_nape/util/ZNPNode_ZPP_CutVert.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_378a7638927e1295_6013_new,"zpp_nape.util.ZNPList_ZPP_CutVert","new",0x362d64b0,"zpp_nape.util.ZNPList_ZPP_CutVert.new","zpp_nape/util/Lists.hx",6013,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6019_begin,"zpp_nape.util.ZNPList_ZPP_CutVert","begin",0x3ef93279,"zpp_nape.util.ZNPList_ZPP_CutVert.begin","zpp_nape/util/Lists.hx",6019,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6026_setbegin,"zpp_nape.util.ZNPList_ZPP_CutVert","setbegin",0xf0d7acf7,"zpp_nape.util.ZNPList_ZPP_CutVert.setbegin","zpp_nape/util/Lists.hx",6026,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6032_add,"zpp_nape.util.ZNPList_ZPP_CutVert","add",0x36238671,"zpp_nape.util.ZNPList_ZPP_CutVert.add","zpp_nape/util/Lists.hx",6032,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6036_inlined_add,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_add",0xb52cb0dd,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_add","zpp_nape/util/Lists.hx",6036,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6082_addAll,"zpp_nape.util.ZNPList_ZPP_CutVert","addAll",0xdf370730,"zpp_nape.util.ZNPList_ZPP_CutVert.addAll","zpp_nape/util/Lists.hx",6082,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6092_insert,"zpp_nape.util.ZNPList_ZPP_CutVert","insert",0xde1940e9,"zpp_nape.util.ZNPList_ZPP_CutVert.insert","zpp_nape/util/Lists.hx",6092,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6096_inlined_insert,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_insert",0xb50961fd,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_insert","zpp_nape/util/Lists.hx",6096,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6140_pop,"zpp_nape.util.ZNPList_ZPP_CutVert","pop",0x362ef1e1,"zpp_nape.util.ZNPList_ZPP_CutVert.pop","zpp_nape/util/Lists.hx",6140,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6144_inlined_pop,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_pop",0xb5381c4d,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_pop","zpp_nape/util/Lists.hx",6144,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6178_pop_unsafe,"zpp_nape.util.ZNPList_ZPP_CutVert","pop_unsafe",0xa6f11204,"zpp_nape.util.ZNPList_ZPP_CutVert.pop_unsafe","zpp_nape/util/Lists.hx",6178,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6182_inlined_pop_unsafe,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_pop_unsafe",0x73094d18,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_pop_unsafe","zpp_nape/util/Lists.hx",6182,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6204_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","remove",0x44c499f4,"zpp_nape.util.ZNPList_ZPP_CutVert.remove","zpp_nape/util/Lists.hx",6204,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6206_try_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","try_remove",0xbe1b47b8,"zpp_nape.util.ZNPList_ZPP_CutVert.try_remove","zpp_nape/util/Lists.hx",6206,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6240_inlined_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_remove",0x1bb4bb08,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_remove","zpp_nape/util/Lists.hx",6240,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6244_inlined_try_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_try_remove",0x8a3382cc,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_try_remove","zpp_nape/util/Lists.hx",6244,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6268_erase,"zpp_nape.util.ZNPList_ZPP_CutVert","erase",0x01c03136,"zpp_nape.util.ZNPList_ZPP_CutVert.erase","zpp_nape/util/Lists.hx",6268,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6272_inlined_erase,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_erase",0x3539cea2,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_erase","zpp_nape/util/Lists.hx",6272,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6318_splice,"zpp_nape.util.ZNPList_ZPP_CutVert","splice",0xffda832c,"zpp_nape.util.ZNPList_ZPP_CutVert.splice","zpp_nape/util/Lists.hx",6318,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6323_clear,"zpp_nape.util.ZNPList_ZPP_CutVert","clear",0xd6feb9dd,"zpp_nape.util.ZNPList_ZPP_CutVert.clear","zpp_nape/util/Lists.hx",6323,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6328_inlined_clear,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_clear",0x0a785749,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_clear","zpp_nape/util/Lists.hx",6328,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6333_reverse,"zpp_nape.util.ZNPList_ZPP_CutVert","reverse",0x0f3e3572,"zpp_nape.util.ZNPList_ZPP_CutVert.reverse","zpp_nape/util/Lists.hx",6333,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6349_empty,"zpp_nape.util.ZNPList_ZPP_CutVert","empty",0xfe7d82dd,"zpp_nape.util.ZNPList_ZPP_CutVert.empty","zpp_nape/util/Lists.hx",6349,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6354_size,"zpp_nape.util.ZNPList_ZPP_CutVert","size",0x34dbd271,"zpp_nape.util.ZNPList_ZPP_CutVert.size","zpp_nape/util/Lists.hx",6354,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6357_has,"zpp_nape.util.ZNPList_ZPP_CutVert","has",0x3628d3aa,"zpp_nape.util.ZNPList_ZPP_CutVert.has","zpp_nape/util/Lists.hx",6357,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6361_inlined_has,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_has",0xb531fe16,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_has","zpp_nape/util/Lists.hx",6361,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6392_front,"zpp_nape.util.ZNPList_ZPP_CutVert","front",0x953160f9,"zpp_nape.util.ZNPList_ZPP_CutVert.front","zpp_nape/util/Lists.hx",6392,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6394_back,"zpp_nape.util.ZNPList_ZPP_CutVert","back",0x29990bd7,"zpp_nape.util.ZNPList_ZPP_CutVert.back","zpp_nape/util/Lists.hx",6394,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6403_iterator_at,"zpp_nape.util.ZNPList_ZPP_CutVert","iterator_at",0xb9d0ee34,"zpp_nape.util.ZNPList_ZPP_CutVert.iterator_at","zpp_nape/util/Lists.hx",6403,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6416_at,"zpp_nape.util.ZNPList_ZPP_CutVert","at",0xb59fbaa3,"zpp_nape.util.ZNPList_ZPP_CutVert.at","zpp_nape/util/Lists.hx",6416,0x9f4e6754) namespace zpp_nape{ namespace util{ void ZNPList_ZPP_CutVert_obj::__construct(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6013_new) HXLINE(6023) this->length = 0; HXLINE(6022) this->pushmod = false; HXLINE(6021) this->modified = false; HXLINE(6014) this->head = null(); } Dynamic ZNPList_ZPP_CutVert_obj::__CreateEmpty() { return new ZNPList_ZPP_CutVert_obj; } void *ZNPList_ZPP_CutVert_obj::_hx_vtable = 0; Dynamic ZNPList_ZPP_CutVert_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > _hx_result = new ZNPList_ZPP_CutVert_obj(); _hx_result->__construct(); return _hx_result; } bool ZNPList_ZPP_CutVert_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1d171732; } ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::begin(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6019_begin) HXDLIN(6019) return this->head; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,begin,return ) void ZNPList_ZPP_CutVert_obj::setbegin( ::zpp_nape::util::ZNPNode_ZPP_CutVert i){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6026_setbegin) HXLINE(6027) this->head = i; HXLINE(6028) this->modified = true; HXLINE(6029) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,setbegin,(void)) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::add( ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6032_add) HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6032) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXDLIN(6032) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXDLIN(6032) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXDLIN(6032) ret->next = null(); } HXDLIN(6032) ret->elt = o; HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXDLIN(6032) temp->next = this->head; HXDLIN(6032) this->head = temp; HXDLIN(6032) this->modified = true; HXDLIN(6032) this->length++; HXDLIN(6032) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,add,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_add( ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6036_inlined_add) HXLINE(6046) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6048) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXLINE(6049) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXLINE(6055) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6056) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXLINE(6057) ret->next = null(); } HXLINE(6064) ret->elt = o; HXLINE(6045) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXLINE(6067) temp->next = this->head; HXLINE(6068) this->head = temp; HXLINE(6069) this->modified = true; HXLINE(6070) this->length++; HXLINE(6071) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_add,return ) void ZNPList_ZPP_CutVert_obj::addAll( ::zpp_nape::util::ZNPList_ZPP_CutVert x){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6082_addAll) HXLINE(6083) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = x->head; HXLINE(6084) while(hx::IsNotNull( cx_ite )){ HXLINE(6085) ::zpp_nape::geom::ZPP_CutVert i = cx_ite->elt; HXLINE(6086) this->add(i); HXLINE(6087) cx_ite = cx_ite->next; } } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,addAll,(void)) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::insert( ::zpp_nape::util::ZNPNode_ZPP_CutVert cur, ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6092_insert) HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6092) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXDLIN(6092) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXDLIN(6092) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXDLIN(6092) ret->next = null(); } HXDLIN(6092) ret->elt = o; HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXDLIN(6092) if (hx::IsNull( cur )) { HXDLIN(6092) temp->next = this->head; HXDLIN(6092) this->head = temp; } else { HXDLIN(6092) temp->next = cur->next; HXDLIN(6092) cur->next = temp; } HXDLIN(6092) this->pushmod = (this->modified = true); HXDLIN(6092) this->length++; HXDLIN(6092) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,insert,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_insert( ::zpp_nape::util::ZNPNode_ZPP_CutVert cur, ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6096_inlined_insert) HXLINE(6106) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6108) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXLINE(6109) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXLINE(6115) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6116) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXLINE(6117) ret->next = null(); } HXLINE(6124) ret->elt = o; HXLINE(6105) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXLINE(6127) if (hx::IsNull( cur )) { HXLINE(6128) temp->next = this->head; HXLINE(6129) this->head = temp; } else { HXLINE(6132) temp->next = cur->next; HXLINE(6133) cur->next = temp; } HXLINE(6135) this->pushmod = (this->modified = true); HXLINE(6136) this->length++; HXLINE(6137) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,inlined_insert,return ) void ZNPList_ZPP_CutVert_obj::pop(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6140_pop) HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6140) this->head = ret->next; HXDLIN(6140) { HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6140) o->elt = null(); HXDLIN(6140) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6140) if (hx::IsNull( this->head )) { HXDLIN(6140) this->pushmod = true; } HXDLIN(6140) this->modified = true; HXDLIN(6140) this->length--; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,pop,(void)) void ZNPList_ZPP_CutVert_obj::inlined_pop(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6144_inlined_pop) HXLINE(6153) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6154) this->head = ret->next; HXLINE(6156) { HXLINE(6157) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXLINE(6166) o->elt = null(); HXLINE(6167) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6168) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXLINE(6173) if (hx::IsNull( this->head )) { HXLINE(6173) this->pushmod = true; } HXLINE(6174) this->modified = true; HXLINE(6175) this->length--; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_pop,(void)) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::pop_unsafe(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6178_pop_unsafe) HXDLIN(6178) ::zpp_nape::geom::ZPP_CutVert ret = this->head->elt; HXDLIN(6178) this->pop(); HXDLIN(6178) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,pop_unsafe,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_pop_unsafe(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6182_inlined_pop_unsafe) HXLINE(6191) ::zpp_nape::geom::ZPP_CutVert ret = this->head->elt; HXLINE(6192) this->pop(); HXLINE(6193) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_pop_unsafe,return ) void ZNPList_ZPP_CutVert_obj::remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6204_remove) HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXDLIN(6204) bool ret = false; HXDLIN(6204) while(hx::IsNotNull( cur )){ HXDLIN(6204) if (hx::IsEq( cur->elt,obj )) { HXDLIN(6204) { HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6204) if (hx::IsNull( pre )) { HXDLIN(6204) old = this->head; HXDLIN(6204) ret1 = old->next; HXDLIN(6204) this->head = ret1; HXDLIN(6204) if (hx::IsNull( this->head )) { HXDLIN(6204) this->pushmod = true; } } else { HXDLIN(6204) old = pre->next; HXDLIN(6204) ret1 = old->next; HXDLIN(6204) pre->next = ret1; HXDLIN(6204) if (hx::IsNull( ret1 )) { HXDLIN(6204) this->pushmod = true; } } HXDLIN(6204) { HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6204) o->elt = null(); HXDLIN(6204) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6204) this->modified = true; HXDLIN(6204) this->length--; HXDLIN(6204) this->pushmod = true; } HXDLIN(6204) ret = true; HXDLIN(6204) goto _hx_goto_13; } HXDLIN(6204) pre = cur; HXDLIN(6204) cur = cur->next; } _hx_goto_13:; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,remove,(void)) bool ZNPList_ZPP_CutVert_obj::try_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6206_try_remove) HXLINE(6215) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6216) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6217) bool ret = false; HXLINE(6218) while(hx::IsNotNull( cur )){ HXLINE(6219) if (hx::IsEq( cur->elt,obj )) { HXLINE(6220) this->erase(pre); HXLINE(6221) ret = true; HXLINE(6222) goto _hx_goto_15; } HXLINE(6224) pre = cur; HXLINE(6225) cur = cur->next; } _hx_goto_15:; HXLINE(6227) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,try_remove,return ) void ZNPList_ZPP_CutVert_obj::inlined_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6240_inlined_remove) HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXDLIN(6240) bool ret = false; HXDLIN(6240) while(hx::IsNotNull( cur )){ HXDLIN(6240) if (hx::IsEq( cur->elt,obj )) { HXDLIN(6240) { HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6240) if (hx::IsNull( pre )) { HXDLIN(6240) old = this->head; HXDLIN(6240) ret1 = old->next; HXDLIN(6240) this->head = ret1; HXDLIN(6240) if (hx::IsNull( this->head )) { HXDLIN(6240) this->pushmod = true; } } else { HXDLIN(6240) old = pre->next; HXDLIN(6240) ret1 = old->next; HXDLIN(6240) pre->next = ret1; HXDLIN(6240) if (hx::IsNull( ret1 )) { HXDLIN(6240) this->pushmod = true; } } HXDLIN(6240) { HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6240) o->elt = null(); HXDLIN(6240) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6240) this->modified = true; HXDLIN(6240) this->length--; HXDLIN(6240) this->pushmod = true; } HXDLIN(6240) ret = true; HXDLIN(6240) goto _hx_goto_17; } HXDLIN(6240) pre = cur; HXDLIN(6240) cur = cur->next; } _hx_goto_17:; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_remove,(void)) bool ZNPList_ZPP_CutVert_obj::inlined_try_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6244_inlined_try_remove) HXLINE(6253) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6254) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6255) bool ret = false; HXLINE(6256) while(hx::IsNotNull( cur )){ HXLINE(6257) if (hx::IsEq( cur->elt,obj )) { HXLINE(6258) { HXLINE(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6258) if (hx::IsNull( pre )) { HXLINE(6258) old = this->head; HXDLIN(6258) ret1 = old->next; HXDLIN(6258) this->head = ret1; HXDLIN(6258) if (hx::IsNull( this->head )) { HXLINE(6258) this->pushmod = true; } } else { HXLINE(6258) old = pre->next; HXDLIN(6258) ret1 = old->next; HXDLIN(6258) pre->next = ret1; HXDLIN(6258) if (hx::IsNull( ret1 )) { HXLINE(6258) this->pushmod = true; } } HXDLIN(6258) { HXLINE(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6258) o->elt = null(); HXDLIN(6258) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6258) this->modified = true; HXDLIN(6258) this->length--; HXDLIN(6258) this->pushmod = true; } HXLINE(6259) ret = true; HXLINE(6260) goto _hx_goto_19; } HXLINE(6262) pre = cur; HXLINE(6263) cur = cur->next; } _hx_goto_19:; HXLINE(6265) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_try_remove,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::erase( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6268_erase) HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6268) if (hx::IsNull( pre )) { HXDLIN(6268) old = this->head; HXDLIN(6268) ret = old->next; HXDLIN(6268) this->head = ret; HXDLIN(6268) if (hx::IsNull( this->head )) { HXDLIN(6268) this->pushmod = true; } } else { HXDLIN(6268) old = pre->next; HXDLIN(6268) ret = old->next; HXDLIN(6268) pre->next = ret; HXDLIN(6268) if (hx::IsNull( ret )) { HXDLIN(6268) this->pushmod = true; } } HXDLIN(6268) { HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6268) o->elt = null(); HXDLIN(6268) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6268) this->modified = true; HXDLIN(6268) this->length--; HXDLIN(6268) this->pushmod = true; HXDLIN(6268) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,erase,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_erase( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6272_inlined_erase) HXLINE(6281) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXLINE(6282) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6283) if (hx::IsNull( pre )) { HXLINE(6284) old = this->head; HXLINE(6285) ret = old->next; HXLINE(6286) this->head = ret; HXLINE(6287) if (hx::IsNull( this->head )) { HXLINE(6287) this->pushmod = true; } } else { HXLINE(6290) old = pre->next; HXLINE(6291) ret = old->next; HXLINE(6292) pre->next = ret; HXLINE(6293) if (hx::IsNull( ret )) { HXLINE(6293) this->pushmod = true; } } HXLINE(6296) { HXLINE(6297) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXLINE(6306) o->elt = null(); HXLINE(6307) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6308) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXLINE(6313) this->modified = true; HXLINE(6314) this->length--; HXLINE(6315) this->pushmod = true; HXLINE(6316) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_erase,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::splice( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre,int n){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6318_splice) HXLINE(6319) while(true){ HXLINE(6319) bool _hx_tmp; HXDLIN(6319) n = (n - 1); HXDLIN(6319) if (((n + 1) > 0)) { HXLINE(6319) _hx_tmp = hx::IsNotNull( pre->next ); } else { HXLINE(6319) _hx_tmp = false; } HXDLIN(6319) if (!(_hx_tmp)) { HXLINE(6319) goto _hx_goto_23; } HXDLIN(6319) this->erase(pre); } _hx_goto_23:; HXLINE(6320) return pre->next; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,splice,return ) void ZNPList_ZPP_CutVert_obj::clear(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6323_clear) HXDLIN(6323) while(hx::IsNotNull( this->head )){ HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6323) this->head = ret->next; HXDLIN(6323) { HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6323) o->elt = null(); HXDLIN(6323) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6323) if (hx::IsNull( this->head )) { HXDLIN(6323) this->pushmod = true; } HXDLIN(6323) this->modified = true; HXDLIN(6323) this->length--; } HXDLIN(6323) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,clear,(void)) void ZNPList_ZPP_CutVert_obj::inlined_clear(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6328_inlined_clear) HXLINE(6329) while(hx::IsNotNull( this->head )){ HXLINE(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6329) this->head = ret->next; HXDLIN(6329) { HXLINE(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6329) o->elt = null(); HXDLIN(6329) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6329) if (hx::IsNull( this->head )) { HXLINE(6329) this->pushmod = true; } HXDLIN(6329) this->modified = true; HXDLIN(6329) this->length--; } HXLINE(6330) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_clear,(void)) void ZNPList_ZPP_CutVert_obj::reverse(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6333_reverse) HXLINE(6334) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6335) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6336) while(hx::IsNotNull( cur )){ HXLINE(6337) ::zpp_nape::util::ZNPNode_ZPP_CutVert nx = cur->next; HXLINE(6338) cur->next = pre; HXLINE(6339) this->head = cur; HXLINE(6340) pre = cur; HXLINE(6341) cur = nx; } HXLINE(6343) this->modified = true; HXLINE(6344) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,reverse,(void)) bool ZNPList_ZPP_CutVert_obj::empty(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6349_empty) HXDLIN(6349) return hx::IsNull( this->head ); } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,empty,return ) int ZNPList_ZPP_CutVert_obj::size(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6354_size) HXDLIN(6354) return this->length; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,size,return ) bool ZNPList_ZPP_CutVert_obj::has( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6357_has) HXDLIN(6357) bool ret; HXDLIN(6357) { HXDLIN(6357) ret = false; HXDLIN(6357) { HXDLIN(6357) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = this->head; HXDLIN(6357) while(hx::IsNotNull( cx_ite )){ HXDLIN(6357) ::zpp_nape::geom::ZPP_CutVert npite = cx_ite->elt; HXDLIN(6357) if (hx::IsEq( npite,obj )) { HXDLIN(6357) ret = true; HXDLIN(6357) goto _hx_goto_33; } HXDLIN(6357) cx_ite = cx_ite->next; } _hx_goto_33:; } } HXDLIN(6357) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,has,return ) bool ZNPList_ZPP_CutVert_obj::inlined_has( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6361_inlined_has) HXLINE(6370) bool ret; HXLINE(6371) { HXLINE(6372) ret = false; HXLINE(6373) { HXLINE(6374) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = this->head; HXLINE(6375) while(hx::IsNotNull( cx_ite )){ HXLINE(6376) ::zpp_nape::geom::ZPP_CutVert npite = cx_ite->elt; HXLINE(6378) if (hx::IsEq( npite,obj )) { HXLINE(6379) ret = true; HXLINE(6380) goto _hx_goto_35; } HXLINE(6383) cx_ite = cx_ite->next; } _hx_goto_35:; } } HXLINE(6387) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_has,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::front(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6392_front) HXDLIN(6392) return this->head->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,front,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::back(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6394_back) HXLINE(6395) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6396) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = ret; HXLINE(6397) while(hx::IsNotNull( cur )){ HXLINE(6398) ret = cur; HXLINE(6399) cur = cur->next; } HXLINE(6401) return ret->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,back,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::iterator_at(int ind){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6403_iterator_at) HXLINE(6412) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6413) while(true){ HXLINE(6413) bool _hx_tmp; HXDLIN(6413) ind = (ind - 1); HXDLIN(6413) if (((ind + 1) > 0)) { HXLINE(6413) _hx_tmp = hx::IsNotNull( ret ); } else { HXLINE(6413) _hx_tmp = false; } HXDLIN(6413) if (!(_hx_tmp)) { HXLINE(6413) goto _hx_goto_40; } HXDLIN(6413) ret = ret->next; } _hx_goto_40:; HXLINE(6414) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,iterator_at,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::at(int ind){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6416_at) HXLINE(6425) ::zpp_nape::util::ZNPNode_ZPP_CutVert it = this->iterator_at(ind); HXLINE(6426) if (hx::IsNotNull( it )) { HXLINE(6426) return it->elt; } else { HXLINE(6426) return null(); } HXDLIN(6426) return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,at,return ) hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > ZNPList_ZPP_CutVert_obj::__new() { hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > __this = new ZNPList_ZPP_CutVert_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > ZNPList_ZPP_CutVert_obj::__alloc(hx::Ctx *_hx_ctx) { ZNPList_ZPP_CutVert_obj *__this = (ZNPList_ZPP_CutVert_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZNPList_ZPP_CutVert_obj), true, "zpp_nape.util.ZNPList_ZPP_CutVert")); *(void **)__this = ZNPList_ZPP_CutVert_obj::_hx_vtable; __this->__construct(); return __this; } ZNPList_ZPP_CutVert_obj::ZNPList_ZPP_CutVert_obj() { } void ZNPList_ZPP_CutVert_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZNPList_ZPP_CutVert); HX_MARK_MEMBER_NAME(head,"head"); HX_MARK_MEMBER_NAME(modified,"modified"); HX_MARK_MEMBER_NAME(pushmod,"pushmod"); HX_MARK_MEMBER_NAME(length,"length"); HX_MARK_END_CLASS(); } void ZNPList_ZPP_CutVert_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(head,"head"); HX_VISIT_MEMBER_NAME(modified,"modified"); HX_VISIT_MEMBER_NAME(pushmod,"pushmod"); HX_VISIT_MEMBER_NAME(length,"length"); } hx::Val ZNPList_ZPP_CutVert_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"at") ) { return hx::Val( at_dyn() ); } break; case 3: if (HX_FIELD_EQ(inName,"add") ) { return hx::Val( add_dyn() ); } if (HX_FIELD_EQ(inName,"pop") ) { return hx::Val( pop_dyn() ); } if (HX_FIELD_EQ(inName,"has") ) { return hx::Val( has_dyn() ); } break; case 4: if (HX_FIELD_EQ(inName,"head") ) { return hx::Val( head ); } if (HX_FIELD_EQ(inName,"size") ) { return hx::Val( size_dyn() ); } if (HX_FIELD_EQ(inName,"back") ) { return hx::Val( back_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"begin") ) { return hx::Val( begin_dyn() ); } if (HX_FIELD_EQ(inName,"erase") ) { return hx::Val( erase_dyn() ); } if (HX_FIELD_EQ(inName,"clear") ) { return hx::Val( clear_dyn() ); } if (HX_FIELD_EQ(inName,"empty") ) { return hx::Val( empty_dyn() ); } if (HX_FIELD_EQ(inName,"front") ) { return hx::Val( front_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"length") ) { return hx::Val( length ); } if (HX_FIELD_EQ(inName,"addAll") ) { return hx::Val( addAll_dyn() ); } if (HX_FIELD_EQ(inName,"insert") ) { return hx::Val( insert_dyn() ); } if (HX_FIELD_EQ(inName,"remove") ) { return hx::Val( remove_dyn() ); } if (HX_FIELD_EQ(inName,"splice") ) { return hx::Val( splice_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"pushmod") ) { return hx::Val( pushmod ); } if (HX_FIELD_EQ(inName,"reverse") ) { return hx::Val( reverse_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"modified") ) { return hx::Val( modified ); } if (HX_FIELD_EQ(inName,"setbegin") ) { return hx::Val( setbegin_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"pop_unsafe") ) { return hx::Val( pop_unsafe_dyn() ); } if (HX_FIELD_EQ(inName,"try_remove") ) { return hx::Val( try_remove_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"inlined_add") ) { return hx::Val( inlined_add_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_pop") ) { return hx::Val( inlined_pop_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_has") ) { return hx::Val( inlined_has_dyn() ); } if (HX_FIELD_EQ(inName,"iterator_at") ) { return hx::Val( iterator_at_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"inlined_erase") ) { return hx::Val( inlined_erase_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_clear") ) { return hx::Val( inlined_clear_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"inlined_insert") ) { return hx::Val( inlined_insert_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_remove") ) { return hx::Val( inlined_remove_dyn() ); } break; case 18: if (HX_FIELD_EQ(inName,"inlined_pop_unsafe") ) { return hx::Val( inlined_pop_unsafe_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_try_remove") ) { return hx::Val( inlined_try_remove_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val ZNPList_ZPP_CutVert_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"head") ) { head=inValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_CutVert >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"length") ) { length=inValue.Cast< int >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"pushmod") ) { pushmod=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"modified") ) { modified=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ZNPList_ZPP_CutVert_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("head",20,29,0b,45)); outFields->push(HX_("modified",49,db,c7,16)); outFields->push(HX_("pushmod",28,29,4b,75)); outFields->push(HX_("length",e6,94,07,9f)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZNPList_ZPP_CutVert_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_CutVert */ ,(int)offsetof(ZNPList_ZPP_CutVert_obj,head),HX_("head",20,29,0b,45)}, {hx::fsBool,(int)offsetof(ZNPList_ZPP_CutVert_obj,modified),HX_("modified",49,db,c7,16)}, {hx::fsBool,(int)offsetof(ZNPList_ZPP_CutVert_obj,pushmod),HX_("pushmod",28,29,4b,75)}, {hx::fsInt,(int)offsetof(ZNPList_ZPP_CutVert_obj,length),HX_("length",e6,94,07,9f)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *ZNPList_ZPP_CutVert_obj_sStaticStorageInfo = 0; #endif static ::String ZNPList_ZPP_CutVert_obj_sMemberFields[] = { HX_("head",20,29,0b,45), HX_("begin",29,ea,55,b0), HX_("modified",49,db,c7,16), HX_("pushmod",28,29,4b,75), HX_("length",e6,94,07,9f), HX_("setbegin",47,e3,5c,2b), HX_("add",21,f2,49,00), HX_("inlined_add",8d,4c,2e,02), HX_("addAll",80,09,fb,9e), HX_("insert",39,43,dd,9d), HX_("inlined_insert",4d,34,10,a7), HX_("pop",91,5d,55,00), HX_("inlined_pop",fd,b7,39,02), HX_("pop_unsafe",54,7c,ec,75), HX_("inlined_pop_unsafe",68,87,ef,15), HX_("remove",44,9c,88,04), HX_("try_remove",08,b2,16,8d), HX_("inlined_remove",58,8d,bb,0d), HX_("inlined_try_remove",1c,bd,19,2d), HX_("erase",e6,e8,1c,73), HX_("inlined_erase",52,b6,9d,fa), HX_("splice",7c,85,9e,bf), HX_("clear",8d,71,5b,48), HX_("inlined_clear",f9,3e,dc,cf), HX_("reverse",22,39,fc,1a), HX_("empty",8d,3a,da,6f), HX_("size",c1,a0,53,4c), HX_("has",5a,3f,4f,00), HX_("inlined_has",c6,99,33,02), HX_("front",a9,18,8e,06), HX_("back",27,da,10,41), HX_("iterator_at",e4,89,d2,06), HX_("at",f3,54,00,00), ::String(null()) }; hx::Class ZNPList_ZPP_CutVert_obj::__mClass; void ZNPList_ZPP_CutVert_obj::__register() { ZNPList_ZPP_CutVert_obj _hx_dummy; ZNPList_ZPP_CutVert_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.util.ZNPList_ZPP_CutVert",be,8c,99,57); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ZNPList_ZPP_CutVert_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZNPList_ZPP_CutVert_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZNPList_ZPP_CutVert_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZNPList_ZPP_CutVert_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace zpp_nape } // end namespace util
42.164294
234
0.699891
2017a1208d51761c56fe70dcbfeb96ec5d0085d4
7,961
hpp
C++
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
null
null
null
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
1
2020-09-10T01:17:13.000Z
2020-09-10T01:17:13.000Z
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
2
2019-11-29T08:00:29.000Z
2019-11-29T08:26:13.000Z
/* Copyright (C) * 2019 - Hu Ren, rh890127a@163.com * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ /** * @file MultiOStream.hpp * @brief class MultiOStream will linked with multiple files, and output * contents to those files simutaneously. * * @author Hu Ren, rh890127a@163.com * @version v0.1 * @date 2019-08-13 */ #include "OStream.hpp" #include <stdlib.h> #ifndef HSF_MULTIOSTREAM_HPP #define HSF_MULTIOSTREAM_HPP namespace HSF { class MultiOStream : public OStream { // core file stream vector<ostream*> files_; // if it is redirected vector<bool> redirected_; // original stream buffer holder in case redirected vector<StrBuf*> buffers_; public: //-------------------------------------------------------------- // construct & deconstruct //-------------------------------------------------------------- // construct empty MultiOStream() : files_(0),redirected_(0), buffers_(0) {} // construct from file name MultiOStream(const string* filename, int num = 1) : files_(num, NULL), redirected_(num, false), buffers_(num, NULL) { for(int i = 0; i < num; i++) files_[i] = new ofstream(filename[i].c_str()); } // construct from file buffer MultiOStream(StrBuf** rbuf, int num = 1) : files_(num, NULL), redirected_(num, true), buffers_(num, NULL) { for(int i = 0; i < num ; i++) { files_[i] = new ofstream(); buffers_[i] = files_[i]->rdbuf(); files_[i]->ostream::rdbuf(rbuf[i]); } } // No clone or operator= (before C++11) for ostream /* // copy constructor MultiOStream( const MultiOStream& ref ) : OStream(ref), files_(0), redirected_(0), buffers_(0) { // copy data size_t size = ref.getFileNum(); for(size_t i = 0; i < size; i++) { this->files_.push_back(ref.getRawStream(i)->clone() ); this->redirected_.push_back(ref.redirected(i) ); this->buffers_.push_back(ref.getStrBuf(i)->clone() ); } } // clone virtual MultiOStream* clone() { return new MultiOStream(*this) }; // assign operator void operator = ( const MultiOStream& ref ) { // deconstruct the older first to close file for(int i = 0; i < files_.size(); i++) { if( redirected_[i] ) files_[i]->ostream::rdbuf(buffers_[i]); if( files_[i]->rdbuf() != cout.rdbuf() && files_[i]->rdbuf() != NULL ) ((ofstream*) files_[i] )->close(); delete files_[i]; } // clear containers files_.resize(0); redirected_.resize(0); buffers_.resize(0); // copy data size_t size = ref.getFileNum(); for(size_t i = 0; i < size; i++) { this->files_.push_back(ref.getRawStream(i)->clone() ); this->redirected_.push_back(ref.redirected(i) ); this->buffers_.push_back(ref.getStrBuf(i)->clone() ); } } */ // deconstruct virtual ~MultiOStream() { for(int i = 0; i < files_.size(); i++) { if( redirected_[i] ) files_[i]->ostream::rdbuf(buffers_[i]); if( files_[i]->rdbuf() != cout.rdbuf() && files_[i]->rdbuf() != NULL ) ((ofstream*) files_[i] )->close(); delete files_[i]; } } //-------------------------------------------------------------- // redirecting & access //-------------------------------------------------------------- virtual int redirect(StrBuf* rbuf, int pos = 0) { if(pos >= files_.size()) { cerr<<__FILE__<<" + "<<__LINE__<<": "<<endl <<__FUNCTION__<<": "<<endl <<"Error: manipulation on an undefined object!"<<endl; exit( -1 ); } if(redirected_[pos]) files_[pos]->ostream::rdbuf(rbuf); else { redirected_[pos] = true; buffers_[pos] = files_[pos]->rdbuf(); files_[pos]->ostream::rdbuf(rbuf); } } virtual int reset(int pos = 0) { if(pos >= files_.size()) { cerr<<__FILE__<<" + "<<__LINE__<<": "<<endl <<__FUNCTION__<<": "<<endl <<"Error: manipulation on an undefined object!"<<endl; exit( -1 ); } if(redirected_[pos]) { files_[pos]->ostream::rdbuf(buffers_[pos]); redirected_[pos] = false; } } virtual const ostream* getRawStream(int pos = 0) { return files_[pos]; } virtual StrBuf* getStrBuf(int pos = 0) { return files_[pos]->rdbuf(); } virtual bool redirected(int pos = 0) { return redirected_[pos]; } virtual size_t getFileNum() { return files_.size(); } // add new file virtual int addFile(const string& filename) { files_.push_back(NULL); *(files_.end() - 1 )= new ofstream(filename.c_str()); redirected_.push_back(false); buffers_.push_back(NULL); } // add new buffer virtual int addBuffer(StrBuf* buf) { files_.push_back(NULL); files_[files_.size() - 1 ] = new ofstream(); redirected_.push_back(true); buffers_.push_back(files_[files_.size() - 1 ]->rdbuf() ); files_[files_.size() - 1 ]->ostream::rdbuf(buf); } // erase last file virtual int closeLast() { if(files_.size() > 0 ) { int pos = files_.size() - 1; if( redirected_[pos] ) files_[pos]->ostream::rdbuf(buffers_[pos]); if( files_[pos]->rdbuf() != cout.rdbuf() && files_[pos]->rdbuf() != NULL ) ((ofstream*) files_[pos] )->close(); delete files_[pos]; files_.pop_back(); buffers_.pop_back(); redirected_.pop_back(); } else return 0; } //-------------------------------------------------------------- // streaming operator //-------------------------------------------------------------- virtual MultiOStream & operator<<(char chrt) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<chrt; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(string str) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<str; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(int64_t val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(int32_t val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(unsigned long val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(unsigned int val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(double val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(float val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } /** * @brief operator<<, interface accept OsOp type parameters * @param[in] opt, represent parameter like "ENDL" and "FLUSH". * @return */ virtual MultiOStream & operator<<(OsOp opt) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<opt; return (MultiOStream &) *this; } }; }// namespace HSF #endif // HSF_MULTIOSTREAM_HPP
26.273927
78
0.570908
201c495ed49f29a8dad3964eeaa9fbbbb834c07f
417
cpp
C++
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
#include "viewport.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/quaternion.hpp> #include "render_target.hpp" namespace Manta::Rendering { void Viewport::UpdateViewport() { float aspect = (float)rect.width / (float)rect.height; perspective = glm::perspective(glm::radians(fov), aspect, z_near, z_far); eye = perspective * view; } }
26.0625
81
0.685851
201dce607c0f5c17539aa648b73aa59c1be9f0d9
270
hpp
C++
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
1
2019-06-20T16:57:43.000Z
2019-06-20T16:57:43.000Z
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
null
null
null
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
null
null
null
// vim: sw=4 expandtab #ifndef CUBE_HPP_ #define CUBE_HPP_ #include "MeshItem.hpp" #include <glm/vec3.hpp> #include <cstdint> namespace game { class Cube : public MeshItem { public: static void genGraphics(); void draw(); }; } #endif
12.857143
34
0.62963
20201374d5fa2da46c052486be7feadbc53d8e82
240
cpp
C++
src/file_descriptor.cpp
kotoko/cpp-library
d47d828191b02222e29fa186db57478454616665
[ "BSD-3-Clause" ]
null
null
null
src/file_descriptor.cpp
kotoko/cpp-library
d47d828191b02222e29fa186db57478454616665
[ "BSD-3-Clause" ]
null
null
null
src/file_descriptor.cpp
kotoko/cpp-library
d47d828191b02222e29fa186db57478454616665
[ "BSD-3-Clause" ]
null
null
null
#include <unistd.h> #include "file_descriptor.hpp" FileDescriptor::FileDescriptor(int fd) noexcept : fd_(fd) {} FileDescriptor::~FileDescriptor() noexcept { close(fd_); } FileDescriptor::operator int() const noexcept { return fd_; }
13.333333
57
0.733333
2021c46c575e7a0155786e48ce2decf3cc4ad868
12,855
hpp
C++
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Deinonychus_AnimBP_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.BlueprintPlayAnimationEvent struct UDeinonychus_AnimBP_C_BlueprintPlayAnimationEvent_Params { class UAnimMontage** AnimationMontage; // (Parm, ZeroConstructor, IsPlainOldData) float* PlayRate; // (Parm, ZeroConstructor, IsPlainOldData) float playedAnimLength; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7418 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7418_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5892 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5892_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7417 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7417_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1048 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1048_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5891 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5891_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5890 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5890_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5889 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5889_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5888 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5888_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7416 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7416_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7415 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7415_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5887 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5887_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5886 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5886_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7412 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7412_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7411 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7411_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5885 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5885_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5884 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5884_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7410 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7410_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7409 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7409_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5883 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5883_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5882 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5882_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5881 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5881_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1047 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1047_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5880 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5880_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5879 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5879_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5878 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5878_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_334 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_334_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_333 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_333_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_578 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_578_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5877 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5877_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_RotationOffsetBlendSpace_362 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_RotationOffsetBlendSpace_362_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_114 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_114_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7404 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7404_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_113 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_113_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7403 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7403_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5876 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5876_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7402 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7402_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5875 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5875_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7401 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7401_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_577 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_577_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.BlueprintUpdateAnimation struct UDeinonychus_AnimBP_C_BlueprintUpdateAnimation_Params { float* DeltaTimeX; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.ExecuteUbergraph_Deinonychus_AnimBP struct UDeinonychus_AnimBP_C_ExecuteUbergraph_Deinonychus_AnimBP_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
54.240506
161
0.894982
202204da367db1c8429deed9c79627e93bc34540
6,663
cpp
C++
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Scene.h" #include "j1FadeToBlack.h" #include "j1Pathfinding.h" #include "j1EntityManager.h" #include "j1Player.h" #include "j1Skeleton.h" #include "j1SceneUI.h" #include "Brofiler/Brofiler.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); debug_path = false; } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; pugi::xml_node spawn = config.child("spawn"); Skeleton1.x = spawn.child("Skeleton1").attribute("x").as_int(); Skeleton1.y = spawn.child("Skeleton1").attribute("y").as_int(); Skeleton2.x = spawn.child("Skeleton2").attribute("x").as_int(); Skeleton2.y = spawn.child("Skeleton2").attribute("y").as_int(); Skeleton3.x = spawn.child("Skeleton3").attribute("x").as_int(); Skeleton3.y = spawn.child("Skeleton3").attribute("y").as_int(); Skull1.x = spawn.child("Skull1").attribute("x").as_int(); Skull1.y = spawn.child("Skull1").attribute("y").as_int(); Bee1.x = spawn.child("Bee1").attribute("x").as_int(); Bee1.y = spawn.child("Bee1").attribute("y").as_int(); MapItem1.x = spawn.child("Map1").attribute("x").as_int(); MapItem1.y = spawn.child("Map1").attribute("y").as_int(); MapItem2.x = spawn.child("Map2").attribute("x").as_int(); MapItem2.y = spawn.child("Map2").attribute("y").as_int(); MapItem3.x = spawn.child("Map3").attribute("x").as_int(); MapItem3.y = spawn.child("Map3").attribute("y").as_int(); MapItem4.x = spawn.child("Map4").attribute("x").as_int(); MapItem4.y = spawn.child("Map4").attribute("y").as_int(); IngameMenuOFFb = false; IngameMenuONb = false; return ret; } // Called before the first frame bool j1Scene::Start() { BROFILER_CATEGORY("Scene Start();", Profiler::Color::SkyBlue) if (App->map->Load("SimpleLevel1.tmx") == true) { StartMap1(); //CREEM UN BOO, QUE DETECTI QUIN NIVELL S'HA CARREGAT I DESPRES CREI ELS OBJECTES QUE SIGUIN D'AQUELL MAPA } debug_tex = App->tex->Load("maps/rosa.png"); App->audio->PlayMusic(App->map->data.MusicAudio_Files.GetString()); /*if (App->map->Load("SimpleLevel2.tmx") == true) { StartMap2(); }*/ return true; } // Called each loop iteration bool j1Scene::PreUpdate() { BROFILER_CATEGORY("Scene PreUpdate();", Profiler::Color::Brown) return true; } // Called each loop iteration bool j1Scene::Update(float dt) { //OPEN CLOSE INGAME MENU if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN && App->scene_ui->OnMainMenu!=true && App->scene_ui->OnSettingsMenu!=true && App->scene_ui->OnCreditsMenu!=true) { if (App->scene_ui->OnIngameMenu == false) { App->scene_ui->IngameMenuON(); App->scene_ui->OnIngameMenu = true; if (App->scene_ui->bMuteIngameOFF == true) { App->scene_ui->MuteIngameOFF(); App->scene_ui->UnMuteIngameON(); } else { App->scene_ui->MuteIngameON(); App->scene_ui->UnMuteIngameOFF(); } } else { App->scene_ui->IngameMenuOFF(); App->scene_ui->OnIngameMenu = false; App->scene_ui->MuteIngameOFF(); App->scene_ui->UnMuteIngameOFF(); } } if (App->input->GetKey(SDL_SCANCODE_GRAVE) == KEY_DOWN) { LOG("CONSOLE OPENED"); if (App->scene_ui->OnConsole == false) { App->scene_ui->ConsoleON(); App->scene_ui->OnConsole = true; } else { LOG("CONSOLE CLOSED"); App->scene_ui->ConsoleOFF(); App->scene_ui->OnConsole = false; } } /*if (App->input->GetKey(SDL_SCANCODE_Y) == KEY_DOWN) { App->scene_ui->MainMenuON(); }*/ /*if ((App->input->GetKey(SDL_SCANCODE_L) == KEY_DOWN)) { if (App->scene_ui->OnSettingsMenu == false) { App->scene_ui->SettingsMenuON(); App->scene_ui->OnSettingsMenu = true; LOG("SETTINGS MENU WITH L ON"); } else { App->scene_ui->SettingsMenuOFF(); App->scene_ui->OnSettingsMenu = false; LOG("SETTINGS MENU WITH L OFF"); } }*/ BROFILER_CATEGORY("Scene Update();", Profiler::Color::Thistle) if (App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame("save_game.xml"); //App->SaveGame(); /*if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { App->fade->FadeToBlack("SimpleLevel1.tmx"); StartMap1(); } if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { App->fade->FadeToBlack("SimpleLevel2.tmx"); StartMap2(); }*/ App->map->Draw(); if (App->input->keyboard[SDL_SCANCODE_F9] == KEY_DOWN) { if (debug_path) { debug_path = false; } else { debug_path = true; } } if (debug_path == false) return true; int x, y; App->input->GetMousePosition(x, y); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { BROFILER_CATEGORY("Scene PostUpdate();", Profiler::Color::DarkBlue) //VOLUMEN /*if (App->input->GetKey(SDL_SCANCODE_KP_PLUS) == KEY_DOWN) { App->audio->general_volume += 5; App->audio->SetVolumeMusic(); } if (App->input->GetKey(SDL_SCANCODE_KP_MINUS) == KEY_DOWN) { App->audio->general_volume -= 5; App->audio->SetVolumeMusic(); }*/ bool ret = true; /*if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false;*/ return ret; } // Called before quitting bool j1Scene::CleanUp() { BROFILER_CATEGORY("Scene Start();", Profiler::Color::PeachPuff) LOG("Freeing scene"); return true; } bool j1Scene::Save(pugi::xml_node& data)const { pugi::xml_node mapname = data.append_child(""); return true; } void j1Scene::StartMap1() { Map1Loaded = true; int w, h; uchar* data = NULL; if (App->map->CreateWalkabilityMap(w, h, &data)) App->pathfinding->SetMap(w, h, data); RELEASE_ARRAY(data); // ENEMY SPAWNS LEVEL 1 App->entityManager->AddEnemies(Skeleton1, SKELETON); App->entityManager->AddEnemies(Bee1, BEE); App->entityManager->AddEnemies(Skeleton2, SKELETON); App->entityManager->AddEnemies(Skull1, SKULL); App->entityManager->AddEnemies(Skeleton3, SKELETON); App->entityManager->CreateEntity(PLAYER); //MAP ITEM ENTITY SPAWN App->entityManager->AddEnemies(MapItem1, MAP); App->entityManager->AddEnemies(MapItem2, MAP); App->entityManager->AddEnemies(MapItem3, MAP); App->entityManager->AddEnemies(MapItem4, MAP); } void j1Scene::StartMap2() { App->entityManager->AddEnemies(MapItem1, MAP); App->entityManager->AddEnemies(MapItem2, MAP); App->entityManager->AddEnemies(MapItem3, MAP); App->entityManager->AddEnemies(MapItem4, MAP); App->entityManager->CreateEntity(PLAYER); } void j1Scene::RestartLevelEntitiesL1() { }
22.818493
171
0.679124
2024c3d98a97d73df5bdaebbde964bdd00b622e3
612
hpp
C++
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
/* Required defines: MENU_sizeEx - Menu text size (height) */ // place the menu outside of the visible area #define MENU_X safeZoneXAbs + safeZoneWAbs #define MENU_Y safeZoneY + safeZoneH #define MENU_maxChars 12 // used to determine the necessary width of the menu #define MENU_wPerChar MENU_sizeEx * 3/4 * 0.5 // assume characters 50% width relative to height #define MENU_W (MENU_maxChars + 1.5) * MENU_wPerChar // add 1.5 characters for padding #define MENU_elementH MENU_sizeEx / 0.8 #define MENU_elementY(item) MENU_elementH * (item - 1) #define MENU_H(noOfElements) (noOfElements + 0.5) * MENU_elementH
38.25
95
0.76634
202a482a2227101c86d65a83181d73fe1ccaee9f
983
cpp
C++
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
paulcam206/WindowsCommunityToolkit
eb20ae30788f320127b2c809cad5c8bbfbd9e663
[ "MIT" ]
3
2021-05-27T00:29:00.000Z
2021-05-27T13:10:00.000Z
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
DLozanoNavas/UWPCommunityToolkit
e58479b546cbc264d391de214f3a17557088e109
[ "MIT" ]
9
2018-04-11T21:05:47.000Z
2018-05-04T03:02:07.000Z
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
DLozanoNavas/UWPCommunityToolkit
e58479b546cbc264d391de214f3a17557088e109
[ "MIT" ]
1
2020-07-31T11:15:48.000Z
2020-07-31T11:15:48.000Z
//Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. //See LICENSE in the project root for license information. #include "pch.h" #include "GazeStats.h" using namespace Platform::Collections; BEGIN_NAMESPACE_GAZE_INPUT GazeStats::GazeStats(int maxHistoryLen) { _maxHistoryLen = maxHistoryLen; _history = ref new Vector<Point>(); } void GazeStats::Reset() { _sumX = 0; _sumY = 0; _sumSquaredX = 0; _sumSquaredY = 0; _history->Clear(); } void GazeStats::Update(float x, float y) { Point pt(x, y); _history->Append(pt); if (_history->Size > _maxHistoryLen) { auto oldest = _history->GetAt(0); _history->RemoveAt(0); _sumX -= oldest.X; _sumY -= oldest.Y; _sumSquaredX -= oldest.X * oldest.X; _sumSquaredY -= oldest.Y * oldest.Y; } _sumX += x; _sumY += y; _sumSquaredX += x * x; _sumSquaredY += y * y; } END_NAMESPACE_GAZE_INPUT
20.479167
79
0.626653
202bb71b0d6fadd105929e02716275e4755984d7
833
cpp
C++
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
7
2021-08-23T09:56:00.000Z
2022-03-21T15:29:15.000Z
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
null
null
null
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
null
null
null
#include "Game/Game.h" #include "Systems/CameraMovementSystem.h" #include "Systems/NameSystems/NameSelectKeyboardControlSystem.h" int main() { if (!Registry::Instance()->HasSystem<SoundFXSystem>()) Registry::Instance()->AddSystem<SoundFXSystem>(); if (!Registry::Instance()->HasSystem<MusicPlayerSystem>()) Registry::Instance()->AddSystem<MusicPlayerSystem>(); if (!Registry::Instance()->HasSystem<CameraMovementSystem>()) Registry::Instance()->AddSystem<CameraMovementSystem>(); // Is this needed here? if (!Registry::Instance()->HasSystem<NameSelectKeyboardControlSystem>()) Registry::Instance()->AddSystem<NameSelectKeyboardControlSystem>(); // Turn music volume down Mix_VolumeMusic(10); // Run the game Instance--> There is a loop inside this Game::Instance()->Run(); Game::Instance()->Shutdown(); }
33.32
73
0.734694
202c2c9366707524fef063fbd7870343aa657e4f
725
hpp
C++
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
1
2021-06-28T00:31:08.000Z
2021-06-28T00:31:08.000Z
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
null
null
null
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
null
null
null
/****************************************************************************** * Author(s): Christopher J. Havlicek * * See LICENSE and CONTACTS. ******************************************************************************/ #pragma once #ifndef KMAP_CMD_DEFINITION_HPP #define KMAP_CMD_DEFINITION_HPP #include "../cli.hpp" #include <functional> namespace kmap { class Kmap; } namespace kmap::cmd { auto create_definition( Kmap& kmap ) -> std::function< Result< std::string >( CliCommand::Args const& args ) >; auto add_definition( Kmap& kmap ) -> std::function< Result< std::string >( CliCommand::Args const& args ) >; } // namespace kmap::cmd #endif // KMAP_CMD_DEFINITION_HPP
26.851852
81
0.525517
202c37dbbcb20fcc3d5d3400975e2a43475cb403
14,241
hpp
C++
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.os.Process ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_OS_PROCESS_HPP_DECL #define J2CPP_ANDROID_OS_PROCESS_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace os { class Process; class Process : public object<Process> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) J2CPP_DECLARE_FIELD(3) J2CPP_DECLARE_FIELD(4) J2CPP_DECLARE_FIELD(5) J2CPP_DECLARE_FIELD(6) J2CPP_DECLARE_FIELD(7) J2CPP_DECLARE_FIELD(8) J2CPP_DECLARE_FIELD(9) J2CPP_DECLARE_FIELD(10) J2CPP_DECLARE_FIELD(11) J2CPP_DECLARE_FIELD(12) J2CPP_DECLARE_FIELD(13) J2CPP_DECLARE_FIELD(14) J2CPP_DECLARE_FIELD(15) J2CPP_DECLARE_FIELD(16) J2CPP_DECLARE_FIELD(17) explicit Process(jobject jobj) : object<Process>(jobj) { } operator local_ref<java::lang::Object>() const; Process(); static jlong getElapsedCpuTime(); static jint myPid(); static jint myTid(); static jint myUid(); static jint getUidForName(local_ref< java::lang::String > const&); static jint getGidForName(local_ref< java::lang::String > const&); static void setThreadPriority(jint, jint); static void setThreadPriority(jint); static jint getThreadPriority(jint); static jboolean supportsProcesses(); static void killProcess(jint); static void sendSignal(jint, jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > SYSTEM_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > PHONE_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > FIRST_APPLICATION_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > LAST_APPLICATION_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jint > BLUETOOTH_GID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jint > THREAD_PRIORITY_DEFAULT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jint > THREAD_PRIORITY_LOWEST; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(7), J2CPP_FIELD_SIGNATURE(7), jint > THREAD_PRIORITY_BACKGROUND; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(8), J2CPP_FIELD_SIGNATURE(8), jint > THREAD_PRIORITY_FOREGROUND; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(9), J2CPP_FIELD_SIGNATURE(9), jint > THREAD_PRIORITY_DISPLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(10), J2CPP_FIELD_SIGNATURE(10), jint > THREAD_PRIORITY_URGENT_DISPLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(11), J2CPP_FIELD_SIGNATURE(11), jint > THREAD_PRIORITY_AUDIO; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(12), J2CPP_FIELD_SIGNATURE(12), jint > THREAD_PRIORITY_URGENT_AUDIO; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(13), J2CPP_FIELD_SIGNATURE(13), jint > THREAD_PRIORITY_MORE_FAVORABLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(14), J2CPP_FIELD_SIGNATURE(14), jint > THREAD_PRIORITY_LESS_FAVORABLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(15), J2CPP_FIELD_SIGNATURE(15), jint > SIGNAL_QUIT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(16), J2CPP_FIELD_SIGNATURE(16), jint > SIGNAL_KILL; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(17), J2CPP_FIELD_SIGNATURE(17), jint > SIGNAL_USR1; }; //class Process } //namespace os } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_OS_PROCESS_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_OS_PROCESS_HPP_IMPL #define J2CPP_ANDROID_OS_PROCESS_HPP_IMPL namespace j2cpp { android::os::Process::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::os::Process::Process() : object<android::os::Process>( call_new_object< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(0), android::os::Process::J2CPP_METHOD_SIGNATURE(0) >() ) { } jlong android::os::Process::getElapsedCpuTime() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(1), android::os::Process::J2CPP_METHOD_SIGNATURE(1), jlong >(); } jint android::os::Process::myPid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(2), android::os::Process::J2CPP_METHOD_SIGNATURE(2), jint >(); } jint android::os::Process::myTid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(3), android::os::Process::J2CPP_METHOD_SIGNATURE(3), jint >(); } jint android::os::Process::myUid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(4), android::os::Process::J2CPP_METHOD_SIGNATURE(4), jint >(); } jint android::os::Process::getUidForName(local_ref< java::lang::String > const &a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(5), android::os::Process::J2CPP_METHOD_SIGNATURE(5), jint >(a0); } jint android::os::Process::getGidForName(local_ref< java::lang::String > const &a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(6), android::os::Process::J2CPP_METHOD_SIGNATURE(6), jint >(a0); } void android::os::Process::setThreadPriority(jint a0, jint a1) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(7), android::os::Process::J2CPP_METHOD_SIGNATURE(7), void >(a0, a1); } void android::os::Process::setThreadPriority(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(8), android::os::Process::J2CPP_METHOD_SIGNATURE(8), void >(a0); } jint android::os::Process::getThreadPriority(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(9), android::os::Process::J2CPP_METHOD_SIGNATURE(9), jint >(a0); } jboolean android::os::Process::supportsProcesses() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(10), android::os::Process::J2CPP_METHOD_SIGNATURE(10), jboolean >(); } void android::os::Process::killProcess(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(11), android::os::Process::J2CPP_METHOD_SIGNATURE(11), void >(a0); } void android::os::Process::sendSignal(jint a0, jint a1) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(12), android::os::Process::J2CPP_METHOD_SIGNATURE(12), void >(a0, a1); } static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(0), android::os::Process::J2CPP_FIELD_SIGNATURE(0), jint > android::os::Process::SYSTEM_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(1), android::os::Process::J2CPP_FIELD_SIGNATURE(1), jint > android::os::Process::PHONE_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(2), android::os::Process::J2CPP_FIELD_SIGNATURE(2), jint > android::os::Process::FIRST_APPLICATION_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(3), android::os::Process::J2CPP_FIELD_SIGNATURE(3), jint > android::os::Process::LAST_APPLICATION_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(4), android::os::Process::J2CPP_FIELD_SIGNATURE(4), jint > android::os::Process::BLUETOOTH_GID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(5), android::os::Process::J2CPP_FIELD_SIGNATURE(5), jint > android::os::Process::THREAD_PRIORITY_DEFAULT; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(6), android::os::Process::J2CPP_FIELD_SIGNATURE(6), jint > android::os::Process::THREAD_PRIORITY_LOWEST; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(7), android::os::Process::J2CPP_FIELD_SIGNATURE(7), jint > android::os::Process::THREAD_PRIORITY_BACKGROUND; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(8), android::os::Process::J2CPP_FIELD_SIGNATURE(8), jint > android::os::Process::THREAD_PRIORITY_FOREGROUND; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(9), android::os::Process::J2CPP_FIELD_SIGNATURE(9), jint > android::os::Process::THREAD_PRIORITY_DISPLAY; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(10), android::os::Process::J2CPP_FIELD_SIGNATURE(10), jint > android::os::Process::THREAD_PRIORITY_URGENT_DISPLAY; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(11), android::os::Process::J2CPP_FIELD_SIGNATURE(11), jint > android::os::Process::THREAD_PRIORITY_AUDIO; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(12), android::os::Process::J2CPP_FIELD_SIGNATURE(12), jint > android::os::Process::THREAD_PRIORITY_URGENT_AUDIO; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(13), android::os::Process::J2CPP_FIELD_SIGNATURE(13), jint > android::os::Process::THREAD_PRIORITY_MORE_FAVORABLE; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(14), android::os::Process::J2CPP_FIELD_SIGNATURE(14), jint > android::os::Process::THREAD_PRIORITY_LESS_FAVORABLE; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(15), android::os::Process::J2CPP_FIELD_SIGNATURE(15), jint > android::os::Process::SIGNAL_QUIT; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(16), android::os::Process::J2CPP_FIELD_SIGNATURE(16), jint > android::os::Process::SIGNAL_KILL; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(17), android::os::Process::J2CPP_FIELD_SIGNATURE(17), jint > android::os::Process::SIGNAL_USR1; J2CPP_DEFINE_CLASS(android::os::Process,"android/os/Process") J2CPP_DEFINE_METHOD(android::os::Process,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::os::Process,1,"getElapsedCpuTime","()J") J2CPP_DEFINE_METHOD(android::os::Process,2,"myPid","()I") J2CPP_DEFINE_METHOD(android::os::Process,3,"myTid","()I") J2CPP_DEFINE_METHOD(android::os::Process,4,"myUid","()I") J2CPP_DEFINE_METHOD(android::os::Process,5,"getUidForName","(Ljava/lang/String;)I") J2CPP_DEFINE_METHOD(android::os::Process,6,"getGidForName","(Ljava/lang/String;)I") J2CPP_DEFINE_METHOD(android::os::Process,7,"setThreadPriority","(II)V") J2CPP_DEFINE_METHOD(android::os::Process,8,"setThreadPriority","(I)V") J2CPP_DEFINE_METHOD(android::os::Process,9,"getThreadPriority","(I)I") J2CPP_DEFINE_METHOD(android::os::Process,10,"supportsProcesses","()Z") J2CPP_DEFINE_METHOD(android::os::Process,11,"killProcess","(I)V") J2CPP_DEFINE_METHOD(android::os::Process,12,"sendSignal","(II)V") J2CPP_DEFINE_FIELD(android::os::Process,0,"SYSTEM_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,1,"PHONE_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,2,"FIRST_APPLICATION_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,3,"LAST_APPLICATION_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,4,"BLUETOOTH_GID","I") J2CPP_DEFINE_FIELD(android::os::Process,5,"THREAD_PRIORITY_DEFAULT","I") J2CPP_DEFINE_FIELD(android::os::Process,6,"THREAD_PRIORITY_LOWEST","I") J2CPP_DEFINE_FIELD(android::os::Process,7,"THREAD_PRIORITY_BACKGROUND","I") J2CPP_DEFINE_FIELD(android::os::Process,8,"THREAD_PRIORITY_FOREGROUND","I") J2CPP_DEFINE_FIELD(android::os::Process,9,"THREAD_PRIORITY_DISPLAY","I") J2CPP_DEFINE_FIELD(android::os::Process,10,"THREAD_PRIORITY_URGENT_DISPLAY","I") J2CPP_DEFINE_FIELD(android::os::Process,11,"THREAD_PRIORITY_AUDIO","I") J2CPP_DEFINE_FIELD(android::os::Process,12,"THREAD_PRIORITY_URGENT_AUDIO","I") J2CPP_DEFINE_FIELD(android::os::Process,13,"THREAD_PRIORITY_MORE_FAVORABLE","I") J2CPP_DEFINE_FIELD(android::os::Process,14,"THREAD_PRIORITY_LESS_FAVORABLE","I") J2CPP_DEFINE_FIELD(android::os::Process,15,"SIGNAL_QUIT","I") J2CPP_DEFINE_FIELD(android::os::Process,16,"SIGNAL_KILL","I") J2CPP_DEFINE_FIELD(android::os::Process,17,"SIGNAL_USR1","I") } //namespace j2cpp #endif //J2CPP_ANDROID_OS_PROCESS_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
33.273364
129
0.739906
45c8b72a9b627d263b27df6309d722f9c1676ff9
5,591
cxx
C++
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
/* * @file DoMergeAlg.cxx * * @brief Decides whether or not to read an overlay event * * @author Tracy Usher * * $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/Overlay/src/MergeAlgs/DoMergeAlg.cxx,v 1.4 2011/11/03 18:13:50 usher Exp $ */ #include "GaudiKernel/Algorithm.h" #include "GaudiKernel/MsgStream.h" #include "GaudiKernel/AlgFactory.h" #include "GaudiKernel/SmartDataPtr.h" #include "GaudiKernel/ConversionSvc.h" #include "GaudiKernel/DataSvc.h" #include "GaudiKernel/GenericAddress.h" #include "Event/TopLevel/EventModel.h" #include "Event/MonteCarlo/McPositionHit.h" #include "Event/MonteCarlo/McIntegratingHit.h" #include "OverlayEvent/OverlayEventModel.h" #include "OverlayEvent/EventOverlay.h" #include "Overlay/IOverlayDataSvc.h" #include <map> class DoMergeAlg : public Algorithm { public: DoMergeAlg(const std::string&, ISvcLocator*); StatusCode initialize(); StatusCode execute(); StatusCode finalize(); private: StatusCode setRootEvent(); bool m_mergeAll; IOverlayDataSvc* m_dataSvc; }; // Used by Gaudi for identifying this algorithm //static const AlgFactory<DoMergeAlg> Factory; //const IAlgFactory& DoMergeAlgFactory = Factory; DECLARE_ALGORITHM_FACTORY(DoMergeAlg); DoMergeAlg::DoMergeAlg(const std::string& name, ISvcLocator* pSvcLocator) : Algorithm(name, pSvcLocator) { // variable to bypass if not wanted declareProperty("MergeAll", m_mergeAll = false); } StatusCode DoMergeAlg::initialize() { // Purpose and Method: initializes DoMergeAlg // Inputs: none // Outputs: a status code // Dependencies: value of m_type determining the type of tool to run // Restrictions and Caveats: none StatusCode sc = StatusCode::SUCCESS; MsgStream log(msgSvc(), name()); log << MSG::INFO << "initialize" << endreq; if ( setProperties().isFailure() ) { log << MSG::ERROR << "setProperties() failed" << endreq; return StatusCode::FAILURE; } // Convention for multiple input overlay files is that there will be separate OverlayDataSvc's with // names appended by "_xx", for example OverlayDataSvc_1 for the second input file. // In order to ensure the data read in goes into a unique section of the TDS we need to modify the // base root path, which we do by examining the name of the service std::string dataSvcName = "OverlayDataSvc"; int subPos = name().rfind("_"); std::string nameEnding = subPos > 0 ? name().substr(subPos, name().length() - subPos) : ""; if (nameEnding != "") dataSvcName += nameEnding; IService* dataSvc = 0; sc = service(dataSvcName, dataSvc); if (sc.isFailure() ) { log << MSG::ERROR << " can't get OverlayDataSvc " << endreq; return sc; } // Caste back to the "correct" pointer m_dataSvc = dynamic_cast<IOverlayDataSvc*>(dataSvc); return sc; } StatusCode DoMergeAlg::execute() { // Purpose and Method: execution method (called once for every event) // Doesn't do anything but calls the chosen tool. // Inputs: none // Outputs: a status code // Dependencies: none // Restrictions and Caveats: none StatusCode sc = StatusCode::SUCCESS; MsgStream log(msgSvc(), name()); log << MSG::DEBUG << "execute" << endreq; // Since our overlay stuff is not stored in the /Event section of the TDS, we need // to explicitly "set the root" each event - or risk it not getting cleared. sc = setRootEvent(); if (sc.isFailure()) { log << MSG::ERROR << "Clearing of the Overlay section of TDS failed" << endreq; return sc; } if (m_mergeAll) { log << MSG::DEBUG << "Merging all events, skipping DoMergeAlg" << endreq; return sc; } // How many hits in ACD, TKR or CAL? int numPosHits = 0; int numIntHits = 0; // Recover the McPositionHits for this event SmartDataPtr<Event::McPositionHitCol> posHitCol(eventSvc(), EventModel::MC::McPositionHitCol); if (posHitCol) numPosHits = posHitCol->size(); // Recover the McIntegratingHits for this event SmartDataPtr<Event::McIntegratingHitCol> intHitCol(eventSvc(), EventModel::MC::McIntegratingHitCol); if (intHitCol) numIntHits = intHitCol->size(); // if there are no McPositionHits AND no McIntegratingHits then the simulated particle did not interact if (!(numPosHits > 0 || numIntHits > 0)) setFilterPassed(false); return sc; } StatusCode DoMergeAlg::finalize() { MsgStream log(msgSvc(), name()); log << MSG::INFO << "finalize" << endreq; return StatusCode::SUCCESS; } StatusCode DoMergeAlg::setRootEvent() { StatusCode sc = StatusCode::SUCCESS; // Set up the root event object Event::EventOverlay overObj; // Caste the data service into the input data service pointer DataSvc* dataProviderSvc = dynamic_cast<DataSvc*>(m_dataSvc); // Create a "simple" generic opaque address to go with this IOpaqueAddress* refpAddress = new GenericAddress(EXCEL_StorageType, overObj.clID(), dataProviderSvc->rootName()); sc = dataProviderSvc->setRoot(dataProviderSvc->rootName(), refpAddress); // This is the magic incantation to trigger the building of the directory tree... SmartDataPtr<Event::EventOverlay> overHeader(dataProviderSvc, dataProviderSvc->rootName()); if (!overHeader) sc = StatusCode::FAILURE; return sc; }
30.551913
134
0.669469
45cc65e0fcf35ac3154d9cf252f9279adb6c6dfe
672
hpp
C++
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_SHARED_MODEL_PROTO_UTIL_HPP #define IROHA_SHARED_MODEL_PROTO_UTIL_HPP #include <google/protobuf/message.h> #include <vector> #include "cryptography/blob.hpp" namespace shared_model { namespace proto { template <typename T> crypto::Blob makeBlob(T &&message) { crypto::Blob::Bytes data; data.resize(message.ByteSizeLong()); message.SerializeToArray(data.data(), data.size()); return crypto::Blob(std::move(data)); } } // namespace proto } // namespace shared_model #endif // IROHA_SHARED_MODEL_PROTO_UTIL_HPP
24
57
0.714286
45d1dbb8b6e694baaa42ed82da757e23199ab54b
2,765
cpp
C++
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
#include "ball.hpp" #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "gameStates.hpp" #include "headers.hpp" #include "mainMenu.hpp" Ball::Ball(std::shared_ptr<Paddle> player1, std::shared_ptr<Paddle> player2, std::shared_ptr<Score> scorePlayer1, std::shared_ptr<Score> scorePlayer2) { this->player1_ = player1; this->player2_ = player2; this->scorePlayer1_ = scorePlayer1; this->scorePlayer2_ = scorePlayer2; this->load("../assets/graphics/ball2.png"); this->buffer_ = new sf::SoundBuffer(); this->buffer_->loadFromFile("../assets/sounds/bounce.wav"); this->sound_ = new sf::Sound(*this->buffer_); this->scoreBuffer_ = new sf::SoundBuffer(); this->scoreBuffer_->loadFromFile("../assets/sounds/glass.wav"); this->scoreSound_ = new sf::Sound(*this->scoreBuffer_); this->scoreSound_->setVolume(50); } void Ball::addVelocity(std::shared_ptr<Paddle> paddle) { if (this->velocity_.y > 0) { if (paddle->velocity_.y > 0) { this->velocity_.y *= 1.30f; } else if (paddle->velocity_.y < 0 && this->velocity_.y != 5.5f) { this->velocity_.y = 5.5f; } } else if (this->velocity_.y < 0) { if (paddle->velocity_.y < 0) { this->velocity_.y *= 1.30f; } else if (paddle->velocity_.y > 0 && this->velocity_.y != -5.5f) { this->velocity_.y = -5.5f; } } } void Ball::update(sf::RenderWindow* window) { if (this->checkCollision(this->player1_)) { this->velocity_.x *= -1; addVelocity(player1_); this->sound_->play(); } if (this->checkCollision(this->player2_)) { this->velocity_.x *= -1; addVelocity(player2_); this->sound_->play(); } if (this->getPosition().y < 0 || this->getPosition().y + this->getGlobalBounds().height > window->getSize().y) { this->velocity_.y *= -1; this->sound_->play(); } if (this->getPosition().x < this->player1_->getGlobalBounds().width - 5) { this->scoreSound_->play(); this->scorePlayer2_->incrementScore(); this->reset(window); } if (this->getPosition().x > window->getSize().x - this->player2_->getGlobalBounds().width + 5) { this->scoreSound_->play(); this->scorePlayer1_->incrementScore(); this->reset(window); } Entity::update(); } void Ball::reset(sf::RenderWindow* window) { this->velocity_.x = ((rand() % 2) == 0) ? 6.5f : -6.5f; this->velocity_.y = ((rand() % 2) == 0) ? 6.5f : -6.5f; this->setPosition(window->getSize().x / 2 - 14, window->getSize().y / 2 - 10); } Ball::~Ball() { delete (this->scoreSound_); delete (this->scoreBuffer_); delete (this->buffer_); delete (this->sound_); }
34.135802
152
0.595298
45d3a9ee4be841f88fdd08ec47f1e8588fd35f75
2,306
hxx
C++
main/sd/source/ui/inc/fuformatpaintbrush.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/inc/fuformatpaintbrush.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/inc/fuformatpaintbrush.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SD_FU_FORMATPAINTBRUSH_HXX #define SD_FU_FORMATPAINTBRUSH_HXX #include "futext.hxx" // header for class SfxItemSet #include <svl/itemset.hxx> #include <boost/scoped_ptr.hpp> namespace sd { class DrawViewShell; class FuFormatPaintBrush : public FuText { public: TYPEINFO(); static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ); virtual sal_Bool MouseMove(const MouseEvent& rMEvt); virtual sal_Bool MouseButtonUp(const MouseEvent& rMEvt); virtual sal_Bool MouseButtonDown(const MouseEvent& rMEvt); virtual sal_Bool KeyInput(const KeyEvent& rKEvt); virtual void Activate(); virtual void Deactivate(); static void GetMenuState( DrawViewShell& rDrawViewShell, SfxItemSet &rSet ); static bool CanCopyThisType( sal_uInt32 nObjectInventor, sal_uInt16 nObjectIdentifier ); private: FuFormatPaintBrush ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); void DoExecute( SfxRequest& rReq ); bool HasContentForThisType( sal_uInt32 nObjectInventor, sal_uInt16 nObjectIdentifier ) const; void Paste( bool, bool ); void implcancel(); ::boost::shared_ptr<SfxItemSet> mpItemSet; bool mbPermanent; bool mbOldIsQuickTextEditMode; }; } // end of namespace sd #endif
31.589041
134
0.707285
45d6d0b9024a5843f1561bc335796def93c4635b
3,145
cpp
C++
daemon/src/main.cpp
rssrujan/akka-patterns
f668f0c1d02524659fa9e6a64d9c9a1a2084fa8c
[ "Apache-2.0" ]
1
2015-06-29T02:04:57.000Z
2015-06-29T02:04:57.000Z
daemon/src/main.cpp
rssrujan/akka-patterns
f668f0c1d02524659fa9e6a64d9c9a1a2084fa8c
[ "Apache-2.0" ]
null
null
null
daemon/src/main.cpp
rssrujan/akka-patterns
f668f0c1d02524659fa9e6a64d9c9a1a2084fa8c
[ "Apache-2.0" ]
null
null
null
#include <SimpleAmqpClient/SimpleAmqpClient.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/gpu/gpu.hpp> #include <opencv2/opencv.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/exception/all.hpp> #include <boost/thread.hpp> #include <iostream> #include <stdlib.h> #include <amqp.h> #include "messages.h" using namespace AmqpClient; using namespace akkapatterns::daemon; using namespace boost; using namespace cv; void worker() { // create the channel and then... while (true) { // create a channel and bind it to a queue Channel::ptr_t channel = Channel::Create(); channel->BindQueue("image", "amq.direct", "image.key"); std::string tag = channel->BasicConsume("image", "", true, true, false, 1); // consume the request message std::cout << "Waiting..." << std::endl; Envelope::ptr_t env = channel->BasicConsumeMessage(tag); BasicMessage::ptr_t request = env->Message(); std::string fileName = request->Body(); std::string replyTo = request->ReplyTo(); // do the processing Mat srcHost = cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE); gpu::GpuMat *srcGpu = NULL; if (gpu::getCudaEnabledDeviceCount() > 0) { srcGpu = new gpu::GpuMat(); srcGpu->upload(srcHost); std::cout << "CUDA" << std::endl; // srcGpu = NULL; } while (true) { try { Mat dstHost; Mat kernel; Size thumbnail; thumbnail.height = 32; thumbnail.width = 32; if (srcGpu != NULL) { // we're CUDA gpu::GpuMat dst; cv::gpu::threshold(*srcGpu, dst, 128.0, 255.0, CV_THRESH_BINARY); cv::gpu::resize(dst, dst, thumbnail); dst.download(dstHost); } else { // we're on CPU cv::threshold(srcHost, dstHost, 128.0, 255.0, CV_THRESH_BINARY); cv::resize(dstHost, dstHost, thumbnail); } vector<uchar> buf; cv::imencode(".jpeg", dstHost, buf); amqp_bytes_t body; amqp_basic_properties_t properties; body.len = buf.size(); body.bytes = new uchar[body.len]; memcpy(body.bytes, buf.data(), body.len); BasicMessage::ptr_t response = BasicMessage::Create(body, &properties); channel->BasicPublish("", replyTo, response, true); } catch (const std::runtime_error&) { // The reply queue is gone. // The server has disconnected. We stop sending and go back to waiting for a new request. std::cout << "Disconnected" << std::endl; break; } catch (const cv::Exception &e) { std::cerr << e.what() << std::endl; break; } } } } int main() { int count = 96; try { thread_group group; for (int i = 0; i < count; i++) group.create_thread(worker); std::cout << "Ready..." << std::endl; group.join_all(); } catch (std::runtime_error &e) { std::cout << "Error " << e.what() << std::endl; } }
29.392523
97
0.602544
45dbd1267250da7c0166294b48194847bde25319
1,861
cpp
C++
View/favicondownloader.cpp
edsykes/BookmarkManager
34839a8f068c2945907a3004f27893637eeadaf2
[ "Apache-2.0" ]
null
null
null
View/favicondownloader.cpp
edsykes/BookmarkManager
34839a8f068c2945907a3004f27893637eeadaf2
[ "Apache-2.0" ]
null
null
null
View/favicondownloader.cpp
edsykes/BookmarkManager
34839a8f068c2945907a3004f27893637eeadaf2
[ "Apache-2.0" ]
null
null
null
#include "favicondownloader.h" #include <QUrl> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QFileInfo> #include <QDir> FaviconDownloader::FaviconDownloader(QString iconPath, QString urlPath) { this->iconPath = iconPath; QUrl url = QUrl(urlPath); url.setPath("/favicon.ico"); qDebug() << url.toString(); QNetworkAccessManager *mgr = new QNetworkAccessManager(this); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); connect(mgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_queryFinish(QNetworkReply*))); connect(mgr, SIGNAL(finished(QNetworkReply*)), mgr, SLOT(deleteLater())); const char* mgrSslSignal = SIGNAL(sslErrors(QNetworkReply* reply, const QList<QSslError>& errors)); const char* sslSlot = SLOT(on_sslErrors(QNetworkReply* reply, const QList<QSslError>& errors)); connect(mgr, mgrSslSignal, this, sslSlot); mgr->get(request); } FaviconDownloader::~FaviconDownloader() { } void FaviconDownloader::on_deleteLater() { } void FaviconDownloader::on_queryFinish(QNetworkReply *reply) { qDebug() << "error: " << reply->error(); qDebug() << "error string: " << reply->errorString(); qDebug() << "finished: " << reply->isFinished(); QFileInfo fileInfo(iconPath); QString iconFile = QDir(fileInfo.absolutePath()).filePath(fileInfo.completeBaseName()) + ".ico"; QFile file(iconFile); file.open(QIODevice::WriteOnly); file.write(reply->readAll()); file.flush(); file.close(); } void FaviconDownloader::on_SslErrors(QNetworkReply* /*reply*/, const QList<QSslError>& errors) { QList<QSslError>::const_iterator i; for(i = errors.begin(); i != errors.end(); ++i) { qDebug() << i->errorString(); } qDebug() << "ssl errors complete"; }
30.508197
103
0.695862
45dc62b034f9da99c95d3406fc9c14a09226c20a
2,407
cpp
C++
UOJ/62.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
UOJ/62.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1425/C.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool neg=c=='-'; neg?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return neg?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} template<class T>inline void mset(T a,int v,int n){memset(a,v,n*sizeof(a[0]));} const int N=100010,O=998244353; inline int fpow(int x,int n){ int a=1; for(;n;n>>=1,x=(lint)x*x%O){ if(n&1){ a=(lint)a*x%O; } } return a; } inline int mod_inv(int x){ return fpow(x,O-2); } namespace sieve{ int n; int pri[N],ps=0; bool np[N]; int mu[N]; inline void main(int _n){ n=_n; mu[1]=1; for(int i=2;i<=n;i++){ if(!np[i]){ pri[ps++]=i; mu[i]=-1; } for(int j=0,p,t;j<ps&&(p=pri[j],t=i*p,t<=n);j++){ np[t]=true; if(i%p){ mu[t]=-mu[i]; }else{ mu[t]=0; break; } } } } inline void gpw(int pw[],int e){ e=(e%(O-1)+O-1)%(O-1); pw[1]=1; for(int i=2;i<=n;i++){ if(!np[i]){ pw[i]=fpow(i,e); } for(int j=0,p,t;j<ps&&(p=pri[j],t=i*p,t<=n);j++){ pw[t]=(lint)pw[i]*pw[p]%O; if(i%p==0)break; } } } } using sieve::mu; int g[N]; int invpwd[N],pwe[N]; lint b[N]; inline void Main(int n){ mset(b+1,0,n); for(int i=1;i<=n;i++){ int a=next_num<lint>()*invpwd[i]%O; for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ b[k]+=a*mu[j]; } } } for(int i=1;i<=n;i++){ b[i]%=O; if(b[i]<0){ b[i]+=O; } if(b[i]!=0&&g[i]==0){ puts("-1"); return; } b[i]=(lint)b[i]*g[i]%O; } for(int i=1;i<=n;i++){ lint x=0; for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ x+=b[k]*mu[j]; } } x=((lint)x%O*invpwd[i]%O+O)%O; printf("%lld ",x); } putchar('\n'); } int main(){ #ifndef ONLINE_JUDGE freopen("round.in","r",stdin); freopen("round.out","w",stdout); #endif int n=ni,c=ni,d=ni; sieve::main(n); sieve::gpw(pwe,c-d); sieve::gpw(invpwd,-d); {//g mset(g+1,0,n); for(int i=1;i<=n;i++){ for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ g[k]=((lint)g[k]+O+pwe[i]*mu[j])%O; } } g[i]=mod_inv(g[i]); } } for(int tot=ni;tot--;Main(n)); return 0; }
18.234848
79
0.522227
45de1a5eb2b9ca60d7094a034aa0b05e639de2f0
2,630
cpp
C++
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/input/capabilities_field.hpp> #include <sge/input/processor.hpp> #include <sge/input/processor_unique_ptr.hpp> #include <sge/input/system.hpp> #include <sge/input/system_unique_ptr.hpp> #include <sge/input/impl/log_name.hpp> #include <sge/input/impl/multi_processor.hpp> #include <sge/input/impl/multi_system.hpp> #include <sge/input/impl/system_ptr_vector.hpp> #include <sge/input/plugin/collection.hpp> #include <sge/input/plugin/context.hpp> #include <sge/input/plugin/iterator.hpp> #include <sge/input/plugin/object.hpp> #include <sge/input/plugin/traits.hpp> #include <sge/log/default_parameters.hpp> #include <sge/log/location.hpp> #include <sge/window/object_ref.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/unique_ptr_to_base.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/algorithm/map.hpp> #include <fcppt/container/bitfield/operators.hpp> #include <fcppt/log/context_reference.hpp> sge::input::impl::multi_system::multi_system( fcppt::log::context_reference const _log_context, sge::input::plugin::collection const &_collection) : sge::input::system(), log_{ _log_context, sge::log::location(), sge::log::default_parameters(sge::input::impl::log_name())}, plugins_(fcppt::algorithm::map<sge::input::impl::multi_system::plugin_vector>( _collection, [](sge::input::plugin::context const &_context) { return _context.load(); })), systems_(fcppt::algorithm::map<sge::input::impl::system_ptr_vector>( plugins_, [&_log_context](sge::input::plugin::object const &_plugin) { return _plugin.get()(_log_context); })), capabilities_(fcppt::algorithm::fold( systems_, sge::input::capabilities_field::null(), [](sge::input::system_unique_ptr const &_system, sge::input::capabilities_field const &_state) { return _state | _system->capabilities(); })) { } sge::input::impl::multi_system::~multi_system() = default; sge::input::processor_unique_ptr sge::input::impl::multi_system::create_processor(sge::window::object_ref const _window) { return fcppt::unique_ptr_to_base<sge::input::processor>( fcppt::make_unique_ptr<sge::input::impl::multi_processor>(log_, _window, systems_)); } sge::input::capabilities_field sge::input::impl::multi_system::capabilities() const { return capabilities_; }
39.253731
90
0.709506
45e0feccd1590d52dd7d0b56eff3f1f121c66890
12,642
cpp
C++
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 <boost/filesystem.hpp> #include <boost/optional.hpp> #include "ametsuchi/impl/postgres_block_index.hpp" #include "ametsuchi/impl/postgres_block_query.hpp" #include "converters/protobuf/json_proto_converter.hpp" #include "framework/result_fixture.hpp" #include "module/irohad/ametsuchi/ametsuchi_fixture.hpp" #include "module/irohad/ametsuchi/ametsuchi_mocks.hpp" #include "module/shared_model/builders/protobuf/test_block_builder.hpp" #include "module/shared_model/builders/protobuf/test_transaction_builder.hpp" using namespace iroha::ametsuchi; using testing::Return; class BlockQueryTest : public AmetsuchiTest { protected: void SetUp() override { AmetsuchiTest::SetUp(); auto tmp = FlatFile::create(block_store_path); ASSERT_TRUE(tmp); file = std::move(*tmp); mock_file = std::make_shared<MockKeyValueStorage>(); sql = std::make_unique<soci::session>(soci::postgresql, pgopt_); index = std::make_shared<PostgresBlockIndex>(*sql); blocks = std::make_shared<PostgresBlockQuery>(*sql, *file); empty_blocks = std::make_shared<PostgresBlockQuery>(*sql, *mock_file); *sql << init_; // First transaction in block1 auto txn1_1 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn1_1.hash()); // Second transaction in block1 auto txn1_2 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn1_2.hash()); auto block1 = TestBlockBuilder() .height(1) .transactions( std::vector<shared_model::proto::Transaction>({txn1_1, txn1_2})) .prevHash(shared_model::crypto::Hash(zero_string)) .build(); // First tx in block 1 auto txn2_1 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn2_1.hash()); // Second tx in block 2 auto txn2_2 = TestTransactionBuilder().creatorAccountId(creator2).build(); tx_hashes.push_back(txn2_2.hash()); auto block2 = TestBlockBuilder() .height(2) .transactions( std::vector<shared_model::proto::Transaction>({txn2_1, txn2_2})) .prevHash(block1.hash()) .build(); for (const auto &b : {std::move(block1), std::move(block2)}) { file->add(b.height(), iroha::stringToBytes( shared_model::converters::protobuf::modelToJson(b))); index->index(b); blocks_total++; } } std::unique_ptr<soci::session> sql; std::vector<shared_model::crypto::Hash> tx_hashes; std::shared_ptr<BlockQuery> blocks; std::shared_ptr<BlockQuery> empty_blocks; std::shared_ptr<BlockIndex> index; std::unique_ptr<FlatFile> file; std::shared_ptr<MockKeyValueStorage> mock_file; std::string creator1 = "user1@test"; std::string creator2 = "user2@test"; std::size_t blocks_total{0}; std::string zero_string = std::string(32, '0'); }; /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions created by user1@test is invoked * @then query over user1@test returns 3 txs */ TEST_F(BlockQueryTest, GetAccountTransactionsFromSeveralBlocks) { // Check that creator1 has created 3 transactions auto txs = blocks->getAccountTransactions(creator1); ASSERT_EQ(txs.size(), 3); std::for_each(txs.begin(), txs.end(), [&](const auto &tx) { EXPECT_EQ(tx->creatorAccountId(), creator1); }); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions created by user2@test is invoked * @then query over user2@test returns 1 tx */ TEST_F(BlockQueryTest, GetAccountTransactionsFromSingleBlock) { // Check that creator1 has created 1 transaction auto txs = blocks->getAccountTransactions(creator2); ASSERT_EQ(txs.size(), 1); std::for_each(txs.begin(), txs.end(), [&](const auto &tx) { EXPECT_EQ(tx->creatorAccountId(), creator2); }); } /** * @given block store * @when query to get transactions created by user with id not registered in the * system is invoked * @then query returns empty result */ TEST_F(BlockQueryTest, GetAccountTransactionsNonExistingUser) { // Check that "nonexisting" user has no transaction auto txs = blocks->getAccountTransactions("nonexisting user"); ASSERT_EQ(txs.size(), 0); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with existing transaction hashes * @then queried transactions */ TEST_F(BlockQueryTest, GetTransactionsExistingTxHashes) { auto txs = blocks->getTransactions({tx_hashes[1], tx_hashes[3]}); ASSERT_EQ(txs.size(), 2); ASSERT_TRUE(txs[0]); ASSERT_TRUE(txs[1]); ASSERT_EQ(txs[0].get()->hash(), tx_hashes[1]); ASSERT_EQ(txs[1].get()->hash(), tx_hashes[3]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with non-existing transaction hashes * @then nullopt values are retrieved */ TEST_F(BlockQueryTest, GetTransactionsIncludesNonExistingTxHashes) { shared_model::crypto::Hash invalid_tx_hash_1(zero_string), invalid_tx_hash_2(std::string( shared_model::crypto::DefaultCryptoAlgorithmType::kHashLength, '9')); auto txs = blocks->getTransactions({invalid_tx_hash_1, invalid_tx_hash_2}); ASSERT_EQ(txs.size(), 2); ASSERT_FALSE(txs[0]); ASSERT_FALSE(txs[1]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with empty vector * @then no transactions are retrieved */ TEST_F(BlockQueryTest, GetTransactionsWithEmpty) { // transactions' hashes are empty. auto txs = blocks->getTransactions({}); ASSERT_EQ(txs.size(), 0); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with non-existing txhash and existing txhash * @then queried transactions and empty transaction */ TEST_F(BlockQueryTest, GetTransactionsWithInvalidTxAndValidTx) { // TODO 15/11/17 motxx - Use EqualList VerificationStrategy shared_model::crypto::Hash invalid_tx_hash_1(zero_string); auto txs = blocks->getTransactions({invalid_tx_hash_1, tx_hashes[0]}); ASSERT_EQ(txs.size(), 2); ASSERT_FALSE(txs[0]); ASSERT_TRUE(txs[1]); ASSERT_EQ(txs[1].get()->hash(), tx_hashes[0]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get non-existent 1000th block * @then nothing is returned */ TEST_F(BlockQueryTest, GetNonExistentBlock) { auto stored_blocks = blocks->getBlocks(1000, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when height=1, count=1 * @then returned exactly 1 block */ TEST_F(BlockQueryTest, GetExactlyOneBlock) { auto stored_blocks = blocks->getBlocks(1, 1); ASSERT_EQ(stored_blocks.size(), 1); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when count=0 * @then no blocks returned */ TEST_F(BlockQueryTest, GetBlocks_Count0) { auto stored_blocks = blocks->getBlocks(1, 0); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get zero block * @then no blocks returned */ TEST_F(BlockQueryTest, GetZeroBlock) { auto stored_blocks = blocks->getBlocks(0, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get all blocks starting from 1 * @then returned all blocks (2) */ TEST_F(BlockQueryTest, GetBlocksFrom1) { auto stored_blocks = blocks->getBlocksFrom(1); ASSERT_EQ(stored_blocks.size(), blocks_total); for (size_t i = 0; i < stored_blocks.size(); i++) { auto b = stored_blocks[i]; ASSERT_EQ(b->height(), i + 1) << "block height: " << b->height() << "counter: " << i; } } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test. Block #1 is filled with trash data * (NOT JSON). * @when read block #1 * @then get no blocks */ TEST_F(BlockQueryTest, GetBlockButItIsNotJSON) { namespace fs = boost::filesystem; size_t block_n = 1; // write something that is NOT JSON to block #1 auto block_path = fs::path{block_store_path} / FlatFile::id_to_name(block_n); fs::ofstream block_file(block_path); std::string content = R"(this is definitely not json)"; block_file << content; block_file.close(); auto stored_blocks = blocks->getBlocks(block_n, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test. Block #1 is filled with trash data * (NOT JSON). * @when read block #1 * @then get no blocks */ TEST_F(BlockQueryTest, GetBlockButItIsInvalidBlock) { namespace fs = boost::filesystem; size_t block_n = 1; // write bad block instead of block #1 auto block_path = fs::path{block_store_path} / FlatFile::id_to_name(block_n); fs::ofstream block_file(block_path); std::string content = R"({ "testcase": [], "description": "make sure this is valid json, but definitely not a block" })"; block_file << content; block_file.close(); auto stored_blocks = blocks->getBlocks(block_n, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get top 2 blocks * @then last 2 blocks returned with correct height */ TEST_F(BlockQueryTest, GetTop2Blocks) { size_t blocks_n = 2; // top 2 blocks auto stored_blocks = blocks->getTopBlocks(blocks_n); ASSERT_EQ(stored_blocks.size(), blocks_n); for (size_t i = 0; i < blocks_n; i++) { auto b = stored_blocks[i]; ASSERT_EQ(b->height(), i + 1); } } /** * @given block store with preinserted blocks * @when hasTxWithHash is invoked on existing transaction hash * @then True is returned */ TEST_F(BlockQueryTest, HasTxWithExistingHash) { for (const auto &hash : tx_hashes) { EXPECT_TRUE(blocks->hasTxWithHash(hash)); } } /** * @given block store with preinserted blocks * user1@test AND 1 tx created by user2@test * @when hasTxWithHash is invoked on non-existing hash * @then False is returned */ TEST_F(BlockQueryTest, HasTxWithInvalidHash) { shared_model::crypto::Hash invalid_tx_hash(zero_string); EXPECT_FALSE(blocks->hasTxWithHash(invalid_tx_hash)); } /** * @given block store with preinserted blocks * @when getTopBlock is invoked on this block store * @then returned top block's height is equal to the inserted one's */ TEST_F(BlockQueryTest, GetTopBlockSuccess) { auto top_block_opt = framework::expected::val(blocks->getTopBlock()); ASSERT_TRUE(top_block_opt); ASSERT_EQ(top_block_opt.value().value->height(), 2); } /** * @given empty block store * @when getTopBlock is invoked on this block store * @then result must be a string error, because no block was fetched */ TEST_F(BlockQueryTest, GetTopBlockFail) { EXPECT_CALL(*mock_file, last_id()).WillRepeatedly(Return(0)); EXPECT_CALL(*mock_file, get(mock_file->last_id())) .WillOnce(Return(boost::none)); auto top_block_error = framework::expected::err(empty_blocks->getTopBlock()); ASSERT_TRUE(top_block_error); ASSERT_EQ(top_block_error.value().error, "error while fetching the last block"); }
32.836364
80
0.712308
45e29e1ccb8f2c0cff0d09f10b218564737845f7
2,481
cpp
C++
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include "SnapFileHelp.h" // --- Project includes --- #include "Foundation/vec3.h" // --- STL includes --- #include <iterator> #include <fstream> #include <set> using std::istream_iterator; using std::back_inserter; using std::ifstream; using std::make_pair; using std::set; int get_version(const string& infilename) { string dummystring; int version; ifstream headerfile(infilename.c_str()); // read token headerfile >> dummystring; if(dummystring=="V"){ // if V -> new version headerfile >> version ; cout << "version : " << version << endl; } else { cout << "pre- V.1 version" << endl; version=0; } headerfile.close(); return version; } vector<string> get_filenames(const string& infilename, int version) { cout << "infilename : " << infilename << endl; ifstream headerfile(infilename.c_str()); float dummy,xmax,ymax,zmax,xmin,ymin,zmin; vector<string> filenames; string dummystring; if(version==0){ headerfile >> dummy >> dummy >> dummy; headerfile >> dummystring >> dummy; } else if ((version==1) || (version==2) || (version==3)){ headerfile >> dummystring >> dummy; headerfile >> dummy >> dummy >> dummy; headerfile >> dummystring >> dummy; } else { cerr << "unknown checkpoint version " << version << endl; } // get bounding box headerfile >> dummystring; headerfile >> xmin >> ymin >> zmin >> xmax >> ymax >> zmax ; // ignore periodic bdry headerfile >> dummystring >> dummy >> dummy >> dummy; // ignore dimension headerfile >> dummystring >> dummystring; // get file names copy(istream_iterator<string>(headerfile),istream_iterator<string>(),back_inserter(filenames)); headerfile.close(); cout << "nr. of filenames: " << filenames.size() << endl; return filenames; }
29.188235
97
0.566707
45e42a1025c8adc217a96c371d3bb00ac639fb17
1,112
cpp
C++
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
//【P1968】美元汇率 - 洛谷 - 10 #include <iostream> #include <cstdio> #include <iomanip> #include <algorithm> struct Income { double dollar, mark; Income() {} } *f; int n, *a; void input() { std::cin >> n; a = new int[n + 1]; for (int i = 1; i <= n; ++i) { std::cin >> a[i]; } } int main() { input(); f = new Income[n + 1]; f[1].dollar = 100.0, f[1].mark = a[1]; for (int i = 2; i <= n; ++i) { f[i].dollar = std::max(f[i - 1].dollar, f[i - 1].mark / a[i] * 100.0); f[i].mark = std::max(f[i - 1].mark, f[i - 1].dollar * a[i] / 100.0); } printf("%.2f", (f[n].dollar > f[n].mark ? f[n].dollar : f[n].mark / a[n] * 100.0)); /* double now_my = 100.0, now_mk = 0.0, max_hl = 0.0, min_hl = 2147483647.0; for (int i = 0; i < n; ++i) { if (i + 1 == n) { now_my += now_mk * 100.0 / a[i]; now_mk = 0.0; } else if (a[i] > max_hl) { now_mk += a[i] / 100.0 * now_my; now_my = 0.0; } else if (a[i] < min_hl) { now_my += now_mk * 100.0 / a[i]; now_mk = 0.0; } max_hl = std::max(max_hl, double(a[i])); min_hl = std::min(min_hl, double(a[i])); } printf("%.2f", now_my); */ }
21.803922
84
0.502698
45e610bb53c08e45b75bd5842dd978d69f9c3ce6
2,158
cpp
C++
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
250
2017-07-26T20:54:22.000Z
2019-05-03T09:21:12.000Z
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
79
2017-08-08T20:08:02.000Z
2019-05-06T14:32:45.000Z
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
88
2017-07-28T09:11:51.000Z
2019-05-04T03:48:44.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" namespace Io { namespace Internal { // Gets the current number of ticks from QueryPerformanceCounter. Throws an // exception if the call to QueryPerformanceCounter fails. int64_t GetPerformanceCounter() { LARGE_INTEGER counter; ASSERT(QueryPerformanceCounter( &counter)); return counter.QuadPart; } } Timer::Timer() { _qpcTotalStartTime = Internal::GetPerformanceCounter(); _qpcElapsedStartTime = _qpcTotalStartTime; } HundredsOfNanoseconds Timer::GetElapsedTime() const { const int64_t qpcCurrentTime = Internal::GetPerformanceCounter(); const int64_t qpcElapsedTime = qpcCurrentTime - _qpcElapsedStartTime; return _timeConverter.QpcToRelativeTicks( qpcCurrentTime - _qpcElapsedStartTime); } double Timer::GetElapsedSeconds() const { return std::chrono::duration_cast<std::chrono::duration<double>>( GetElapsedTime()).count(); } HundredsOfNanoseconds Timer::GetTotalTime() const { const int64_t qpcCurrentTime = Internal::GetPerformanceCounter(); return _timeConverter.QpcToRelativeTicks( qpcCurrentTime); } double Timer::GetTotalSeconds() const { return std::chrono::duration_cast<std::chrono::duration<double>>( GetTotalTime()).count(); } void Timer::ResetElapsedTime() { _qpcElapsedStartTime = Internal::GetPerformanceCounter(); } }
27.316456
84
0.57507
45e648661e82340b235cd566b3b0fa122864856d
425
cpp
C++
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
#include "Tutorial01.h" int main( int argc, char ** argv ) { ApiWithoutSecrets::OS::Window window; ApiWithoutSecrets::Tutorial01 tutorial01; // window creation if(! window.Create("01-The Beginning") ) { return -1; } // Vulkan preparations and initialization if( !tutorial01.PrepareVulkan() ) { return -1; } // Rendering Loop if(!window.RenderingLoop(tutorial01) ) { return -1; } return 0; }
14.655172
43
0.663529
45e94b3dfd7697ee37a539956a2ef6eade97b84f
1,583
hpp
C++
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
#ifndef LIBSTL_UTLITIES_STRING_HPP #define LIBSTL_UTLITIES_STRING_HPP #include <array> #include <string> #include <vector> namespace libstl { namespace utilities { namespace string { std::string erase(const std::string& string, const std::string& substring) { std::string s = string; return s.erase(string.find(substring), substring.length()); } std::string trim_leading_whitespace(const std::string& string, const std::string whitespace = " ") { return string.substr(string.find_first_not_of(whitespace)); } std::string trim_trailing_whitespace(const std::string& string, const std::string whitespace = " ") { return string.substr(0, string.find_last_not_of(whitespace) + 1); } std::vector<std::string> split(const std::string& string, const std::string delimiter = " ") { std::vector<std::string> splitted_string; std::string s = string; std::size_t pos = 0; while ((pos = s.find(delimiter)) != std::string::npos) { std::string token = s.substr(0, pos); splitted_string.push_back(token); s.erase(0, pos + delimiter.length()); } splitted_string.push_back(s); return splitted_string; } std::vector<std::string> trim_and_split(const std::string& string, const std::string delimiter = " ", const std::string whitespace = " ") { return split(trim_trailing_whitespace(trim_leading_whitespace(string, whitespace), whitespace), delimiter); } } // namespace string } // namespace utilities } // namespace libstl #endif // LIBSTL_UTLITIES_STRING_HPP
26.830508
111
0.684776
45e9bbade0ee125116c9f34aaa3263b5f7990dd2
2,148
cpp
C++
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
#include "LiveDelegate.hpp" #include "jet/live/CompileCommandsCompilationUnitsParser.hpp" #include "jet/live/DefaultProgramInfoLoader.hpp" #include "jet/live/DepfileDependenciesHandler.hpp" #include "jet/live/Utility.hpp" namespace jet { void LiveDelegate::onLog(LogSeverity, const std::string&) {} void LiveDelegate::onCodePreLoad() {} void LiveDelegate::onCodePostLoad() {} size_t LiveDelegate::getWorkerThreadsCount() { return 4; } std::vector<std::string> LiveDelegate::getDirectoriesToMonitor() { return {}; } bool LiveDelegate::shouldReloadMachoSymbol(const MachoContext& context, const MachoSymbol& symbol) { return (symbol.external && symbol.type == MachoSymbolType::kSection && symbol.sectionIndex == context.textSectionIndex && !symbol.weakDef); } bool LiveDelegate::shouldReloadElfSymbol(const ElfContext& context, const ElfSymbol& symbol) { static const std::string textSectionName = ".text"; return (symbol.type == ElfSymbolType::kFunction && symbol.size != 0 && symbol.sectionIndex < context.sectionNames.size() // Some sections has reserved indices && context.sectionNames[symbol.sectionIndex] == textSectionName); } bool LiveDelegate::shouldTransferMachoSymbol(const MachoContext&, const MachoSymbol&) { return false; } bool LiveDelegate::shouldTransferElfSymbol(const ElfContext& context, const ElfSymbol& symbol) { static const std::string bssSectionName = ".bss"; return (symbol.type == ElfSymbolType::kObject && context.sectionNames[symbol.sectionIndex] == bssSectionName); } std::unique_ptr<ICompilationUnitsParser> LiveDelegate::createCompilationUnitsParser() { return jet::make_unique<CompileCommandsCompilationUnitsParser>(); } std::unique_ptr<IDependenciesHandler> LiveDelegate::createDependenciesHandler() { return jet::make_unique<DepfileDependenciesHandler>(); } std::unique_ptr<IProgramInfoLoader> LiveDelegate::createProgramInfoLoader() { return jet::make_unique<DefaultProgramInfoLoader>(); } }
37.684211
118
0.715549
45e9fcf091bd54c2bb4aead9abc73d7963ab7383
620
cpp
C++
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; using LL = long long; int main(){ //freopen("in","r",stdin) std::ios::sync_with_stdio(false);std::cin.tie(nullptr); int n; cin>>n; LL a[n]; for(int i=0;i<n;++i) cin>>a[i]; sort(a,a+n); LL b[n]={LL(2e18)}; for(int i=1;i<n;++i) b[i] = a[i]-a[i-1]; sort(b,b+n); LL s[n+1]={0}; for(int i=1;i<=n;++i) s[i]=s[i-1]+b[i-1]; auto f = [&](LL len) -> LL{ int id = upper_bound(b,b+n,len)-b; //cout<<id<<" "<<b[id]<<" "<<len<<endl; return s[id]+(len+1)*(n-id); }; int q; cin>>q; while(q--){ LL l,r; cin>>l>>r; cout<<f(r-l)<<" "; } cout<<endl; return 0; }
19.375
56
0.514516
45ec06000883e8f101cf780bfce66c6253b2d5d2
209
cpp
C++
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
#include "Hero.h" Hero::Hero(int attack, int defense, int life) { this->attack = attack; this->defense = defense; this->life = life; this->debuffAttack = 0; this->debuffDefense = 0; } Hero::~Hero() { }
13.933333
45
0.645933
45ec4eec8930c64c8fcb1910df45d16cbfbef69c
938
cpp
C++
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/interviewbit/majority-element.html . int Solution::majorityElement(const vector<int> &A) { int major = A[0], count = 1; for (int i = 1; i < A.size(); i++) { int num = A[i]; if (count == 0) { major = num; count = 1; } else if (major == num) { count++; } else { count--; } } return major; }
44.666667
345
0.630064
45eee7518b94d3bd5cfe5e48481db702e775c7da
494
cpp
C++
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
39
2020-05-31T06:14:39.000Z
2021-01-09T11:06:39.000Z
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
7
2020-06-02T11:04:14.000Z
2020-06-11T14:11:58.000Z
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
20
2020-05-31T06:21:57.000Z
2020-10-01T04:48:38.000Z
// // Created by Jesson on 2020/7/18. // #include <cstdio> //#include <malloc.h> #include <cstdlib> #include "JavaObject.h" void objectRetain(JavaObject *obj) { obj->retainCount ++; printf("retain计数+1 = %d\n",obj->retainCount); } void objectRelease(JavaObject *obj) { obj->retainCount --; if (obj->retainCount <= 0) { free(obj); } printf("retain计数-1 = %d\n",obj->retainCount); } //获得当前计数 int getRetainCount(JavaObject *obj) { return obj->retainCount; }
17.642857
49
0.631579
45f884f94ce01ba6ede76e1851e83ac115c28edf
281
hpp
C++
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
4
2022-01-06T14:06:03.000Z
2022-01-07T01:13:58.000Z
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
#pragma once namespace gfx { namespace generic { template <typename float_system> class range_space : public object { public: typedef float_system float_system_t; typedef typename float_system_t::float_t float_t; public: dynamic_reflectible(range_space, {}); }; } }
16.529412
53
0.754448
45fb42791a141643fefe6b95a9c1ad9b6e74d4c3
6,622
cpp
C++
ci/myTestTask.cpp
jonasbjurel/coreNoStopRTOS
b16b1fbf2c1ee0687dbe7b2a589cf4ee87015375
[ "Apache-2.0" ]
null
null
null
ci/myTestTask.cpp
jonasbjurel/coreNoStopRTOS
b16b1fbf2c1ee0687dbe7b2a589cf4ee87015375
[ "Apache-2.0" ]
null
null
null
ci/myTestTask.cpp
jonasbjurel/coreNoStopRTOS
b16b1fbf2c1ee0687dbe7b2a589cf4ee87015375
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************************************* * * (c) Copyright 2019 Jonas Bjurel (jonasbjurel@hotmail.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 * * licence. * * * * ************************************************************************************************* */ /* ************************************************************************************************ * * Project: coreNoStopRTOS/www....... * * Name: myTestTask.cpp * * Created: 2019-09-27 * * Originator: Jonas Bjurel * * Short description: Provides CI (Continous Integration) test stimuli for for coreNoStopRTOS * * functions... * * Resources: github, WIKI ..... * * ************************************************************************************************ */ #include "myTestTask.h" const uint8_t task1num = 1; const uint8_t* task1num_p = &task1num; const uint8_t task2num = 2; const uint8_t* task2num_p = &task2num; const uint8_t task3num = 3; const uint8_t* task3num_p = &task3num; const uint8_t task4num = 4; const uint8_t* task4num_p = &task4num; const uint8_t task5num = 5; const uint8_t* task5num_p = &task5num; void myTestTaskInit(void) { initd.startStaticTask((TaskFunction_t)myStaticTestTask, "myTestTask 1", (void*)task1num_p, 2048, 2, tskNO_AFFINITY, 7000, 60, 60, 1, 10); initd.startStaticTask((TaskFunction_t)myStaticTestTask, "myTestTask 2", (void*)task2num_p, 2048, 2, tskNO_AFFINITY, 5, 60, 60, 0, 0); initd.startStaticTask((TaskFunction_t)myStaticTestTask, "myTestTask 3", (void*)task3num_p, 2048, 2, tskNO_AFFINITY, 5, 60, 60, 3, 0); initd.startStaticTask((TaskFunction_t)myStaticTestTask, "myTestTask 4", (void*)task4num_p, 2048, 2, tskNO_AFFINITY, _WATCHDOG_DISABLE_MONIT_, 60, 60, 0, 0); initd.startStaticTask((TaskFunction_t)myStaticTestTask, "myTestTask 5", (void*)task5num_p, 2048, 2, tskNO_AFFINITY, 0, 60, 60, 0, 0); } void myStaticTestTask(task_desc_t* myTask) { uint8_t myTid; if (initd.getTidByTaskDesc(&myTid, myTask)) { logdAssert(_PANIC_, "Panic"); } // logdAssert(_DEBUG_, "Task: %s started", myTask->pcName); // logdAssert(_DEBUG_, "Task descriptor %p", myTask); // logdAssert(_DEBUG_, "Task function %p", myTask->pvTaskCode); // logdAssert(_DEBUG_, "Task name %s", myTask->pcName); // logdAssert(_DEBUG_, "stack depth %u", myTask->usStackDepth); // logdAssert(_DEBUG_, "params_p %p, params %u", myTask->pvParameters, *((uint8_t*)(myTask->pvParameters))); // logdAssert(_DEBUG_, "prio %u", myTask->uxPriority); // logdAssert(_DEBUG_, "task handle %p", myTask->pvCreatedTask); // logdAssert(_DEBUG_, "escalation restart cnt %u", myTask->escalationRestartCnt); // logdAssert(_DEBUG_, "restart cnt %u", myTask->restartCnt); switch (*((uint8_t*)(myTask->pvParameters))) { case 1: logdAssert(_INFO_, "Task: %s started, watchdog enabled, but not kicking it, system escalation set to 10 Task restarts, memory leaking task which will spawn a self destructing dynamic process every second", myTask->pcName); break; case 2: logdAssert(_INFO_, "Task: %s started, Watchdog enabled, and kicking it", myTask->pcName); break; case 3: logdAssert(_INFO_, "Task: %s started, Watchdog is enabled, and kicking it, heavy tight loop memory allocation/deallocation", myTask->pcName); break; case 4: logdAssert(_INFO_, "Task: %s started, Watchdog is disabled, but is monitored and self-terminated", myTask->pcName); break; case 5: logdAssert(_INFO_, "Task: %s, Not monitored by init, allocating 2048 Bytes heap and then self-terminated", myTask->pcName); break; default: logdAssert(_INFO_, "Task: %s started, undefined param %u", myTask->pcName, *((uint8_t*)(myTask->pvParameters))); break; } while (true) { switch (*((uint8_t*)(myTask->pvParameters))) { case 1: //logdAssert(_INFO_, "Spinning myTestTask1"); {void* memory_forget_p = initd.taskMalloc(myTask, sizeof("allocating memory")); initd.startDynamicTask((TaskFunction_t)myDynamicTestTask, "MyDynamicTestTask", (void*) "MyDynamicTestTask", 2048, 2, tskNO_AFFINITY); } vTaskDelay(1000); break; case 2: // logdAssert(_INFO_, "Spinning myTestTask2"); initd.kickTaskWatchdogs(myTask); vTaskDelay(10); break; case 3: { // logdAssert(_INFO_, "Spinning myTestTask3"); void* mem_p = initd.taskMalloc(myTask, 2048); for (int i = 0; i < 2048; i++) { *((char*)mem_p + i) = 255; } initd.taskMfree(myTask, mem_p); initd.kickTaskWatchdogs(myTask); vTaskDelay(1); } break; case 4: // logdAssert(_INFO_, "Spinning myTestTask4"); vTaskDelay(30000); logdAssert(_INFO_, "Task: %s, Killing my self", myTask->pcName); vTaskDelete(NULL); break; case 5: // logdAssert(_INFO_, "Spinning myTestTask5"); logdAssert(_INFO_, "Task %s, Allocating 2048 KB heap memory and then dying", myTask->pcName); initd.taskMalloc(myTask, 2048); vTaskDelete(NULL); break; default: vTaskDelete(NULL); break; } } } void myDynamicTestTask(char* taskName) { //logdAssert(_INFO_, "Task: %s, Killing my self", taskName); vTaskDelete(NULL); }
45.986111
224
0.556478
45fb63f68cf38af8aec14b27a9d9dfa1e0a12c53
32,363
cc
C++
tensorstore/driver/zarr/spec_test.cc
google/tensorstore
8df16a67553debaec098698ceaa5404eaf79634a
[ "BSD-2-Clause" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/driver/zarr/spec_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/driver/zarr/spec_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorstore/driver/zarr/spec.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <nlohmann/json.hpp> #include "tensorstore/codec_spec.h" #include "tensorstore/driver/zarr/metadata.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" namespace { using tensorstore::ChunkLayout; using tensorstore::CodecSpec; using tensorstore::dtype_v; using tensorstore::MatchesJson; using tensorstore::MatchesStatus; using tensorstore::Schema; using tensorstore::internal_zarr::GetFieldIndex; using tensorstore::internal_zarr::ParseDType; using tensorstore::internal_zarr::ParseSelectedField; using tensorstore::internal_zarr::SelectedField; using tensorstore::internal_zarr::ZarrMetadata; using tensorstore::internal_zarr::ZarrPartialMetadata; TEST(ParsePartialMetadataTest, InvalidZarrFormat) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"zarr_format", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"zarr_format\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidChunks) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"chunks", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"chunks\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidShape) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"shape", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"shape\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidCompressor) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"compressor", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"compressor\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidOrder) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"order", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"order\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidDType) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"dtype", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"dtype\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidFilters) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"filters", "x"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"filters\": .*")}, }); } TEST(ParsePartialMetadataTest, Empty) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); EXPECT_EQ(std::nullopt, result.zarr_format); EXPECT_EQ(std::nullopt, result.order); EXPECT_EQ(std::nullopt, result.compressor); EXPECT_EQ(std::nullopt, result.filters); EXPECT_EQ(std::nullopt, result.dtype); EXPECT_EQ(std::nullopt, result.fill_value); EXPECT_EQ(std::nullopt, result.shape); EXPECT_EQ(std::nullopt, result.chunks); } ::nlohmann::json GetMetadataSpec() { return {{"zarr_format", 2}, {"chunks", {3, 2}}, {"shape", {100, 100}}, {"order", "C"}, {"filters", nullptr}, {"fill_value", nullptr}, {"dtype", "<i2"}, {"compressor", {{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}}}; } TEST(ParsePartialMetadataTest, Complete) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(GetMetadataSpec())); EXPECT_EQ(2, result.zarr_format); EXPECT_EQ(tensorstore::c_order, result.order); ASSERT_TRUE(result.compressor); EXPECT_EQ((::nlohmann::json{{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}), ::nlohmann::json(*result.compressor)); ASSERT_TRUE(result.dtype); EXPECT_EQ("<i2", ::nlohmann::json(*result.dtype)); ASSERT_TRUE(result.fill_value); ASSERT_EQ(1, result.fill_value->size()); EXPECT_FALSE((*result.fill_value)[0].valid()); ASSERT_TRUE(result.shape); EXPECT_THAT(*result.shape, ::testing::ElementsAre(100, 100)); ASSERT_TRUE(result.chunks); EXPECT_THAT(*result.chunks, ::testing::ElementsAre(3, 2)); } TEST(ParseSelectedFieldTest, Null) { EXPECT_EQ(SelectedField(), ParseSelectedField(nullptr)); } TEST(ParseSelectedFieldTest, InvalidString) { EXPECT_THAT( ParseSelectedField(""), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: \"\"")); } TEST(ParseSelectedFieldTest, String) { EXPECT_EQ(SelectedField("label"), ParseSelectedField("label")); } TEST(ParseSelectedFieldTest, InvalidType) { EXPECT_THAT( ParseSelectedField(true), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: true")); } TEST(GetFieldIndexTest, Null) { EXPECT_EQ(0u, GetFieldIndex(ParseDType("<i4").value(), SelectedField())); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), SelectedField()), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Must specify a \"field\" that is one of: \\[\"x\",\"y\"\\]")); } TEST(GetFieldIndexTest, String) { EXPECT_THAT( GetFieldIndex(ParseDType("<i4").value(), "x"), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Requested field \"x\" but dtype does not have named fields")); EXPECT_EQ(0u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "x")); EXPECT_EQ(1u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "y")); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), "z"), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(EncodeSelectedFieldTest, NonEmpty) { auto dtype = ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}).value(); EXPECT_EQ("x", EncodeSelectedField(0, dtype)); EXPECT_EQ("y", EncodeSelectedField(1, dtype)); } TEST(EncodeSelectedFieldTest, Empty) { auto dtype = ParseDType("<i4").value(); // dtype does not have multiple fields. `EncodeSelectedField` returns the // empty string to indicate that. EXPECT_EQ("", EncodeSelectedField(0, dtype)); } template <typename... Option> tensorstore::Result<::nlohmann::json> GetNewMetadataFromOptions( ::nlohmann::json partial_metadata_json, std::string selected_field, Option&&... option) { Schema schema; if (absl::Status status; !((status = schema.Set(std::forward<Option>(option))).ok() && ...)) { return status; } TENSORSTORE_ASSIGN_OR_RETURN( auto partial_metadata, ZarrPartialMetadata::FromJson(partial_metadata_json)); TENSORSTORE_ASSIGN_OR_RETURN( auto new_metadata, GetNewMetadata(partial_metadata, selected_field, schema)); return new_metadata->ToJson(); } TEST(GetNewMetadataTest, FullMetadata) { EXPECT_THAT(GetNewMetadataFromOptions({{"chunks", {8, 10}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"shape", {5, 6}}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"chunks", {8, 10}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {5, 6}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoShape) { EXPECT_THAT( GetNewMetadataFromOptions( {{"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus(absl::StatusCode::kInvalidArgument, "domain must be specified")); } TEST(GetNewMetadataTest, AutomaticChunks) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"chunks", {2, 3}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {2, 3}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoDtype) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified")); } TEST(GetNewMetadataTest, NoCompressor) { EXPECT_THAT(GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, IntegerOverflow) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {4611686018427387903, 4611686018427387903}}, {"chunks", {4611686018427387903, 4611686018427387903}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus( absl::StatusCode::kInvalidArgument, "Product of chunk dimensions " "\\{4611686018427387903, 4611686018427387903\\} is too large")); } TEST(GetNewMetadataTest, SchemaDomainDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDomainDtypeFillValue) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>, Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)}), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaObjectWithDomainDtypeFillValue) { Schema schema; TENSORSTORE_ASSERT_OK(schema.Set(tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value())); TENSORSTORE_ASSERT_OK(schema.Set(dtype_v<int32_t>)); TENSORSTORE_ASSERT_OK( schema.Set(Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, schema), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeShapeCodec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderC) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({0, 1}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortran) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({1, 0}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortranFieldShape) { EXPECT_THAT(GetNewMetadataFromOptions( { {"compressor", nullptr}, {"dtype", {{"x", "<u4", {2, 3}}}}, }, /*selected_field=*/"x", Schema::Shape({100, 200, 2, 3}), ChunkLayout::InnerOrder({1, 0, 2, 3})), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", {{"x", "<u4", {2, 3}}}}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalid) { EXPECT_THAT( GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid \"inner_order\" constraint: \\{2, 0, 1\\}")); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalidSoft) { EXPECT_THAT(GetNewMetadataFromOptions( {{"compressor", nullptr}}, /*selected_field=*/{}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}, /*hard_constraint=*/false), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200, 300}}, {"chunks", {100, 102, 102}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaStructuredDtypeInvalidFillValue) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", ::nlohmann::json::array_t{{"x", "<u4"}, {"y", "<i4"}}}}, /*selected_field=*/"x", Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus( absl::StatusCode::kInvalidArgument, "Invalid fill_value: Cannot specify fill_value through schema for " "structured zarr data type \\[.*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatch) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", 42}}, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(43))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatchNull) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", nullptr}}, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueRedundant) { EXPECT_THAT( GetNewMetadataFromOptions( { {"dtype", "<u4"}, {"fill_value", 42}, {"compressor", nullptr}, }, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), ::testing::Optional(MatchesJson({ {"fill_value", 42}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<u4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaCodecChunkShape) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t{}, /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<uint32_t>, ChunkLayout::CodecChunkShape({5, 6})), MatchesStatus(absl::StatusCode::kInvalidArgument, "codec_chunk_shape not supported")); } TEST(GetNewMetadataTest, CodecMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT( GetNewMetadataFromOptions({{"compressor", {{"id", "blosc"}}}}, /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(GetNewMetadataTest, SelectedFieldDtypeNotSpecified) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/"x", Schema::Shape({100, 200}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified in \"metadata\" if " "\"field\" is specified")); } TEST(GetNewMetadataTest, SelectedFieldInvalid) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2}}, {"y", "<i4"}}}}, /*selected_field=*/"z", Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(GetNewMetadataTest, InvalidDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, dtype_v<tensorstore::json_t>, Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Data type not supported: json")); } TEST(GetNewMetadataTest, InvalidDomain) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, dtype_v<tensorstore::int32_t>, tensorstore::IndexDomainBuilder(2) .origin({1, 2}) .shape({100, 200}) .Finalize() .value()), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithFieldShape) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2, 3}}}}}, /*selected_field=*/"x", Schema::Shape({100, 200, 2, 4})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithMetadataRank) { EXPECT_THAT( GetNewMetadataFromOptions({{"chunks", {100, 100}}}, /*selected_field=*/{}, dtype_v<tensorstore::int32_t>, Schema::Shape({100, 200, 300})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank specified by schema \\(3\\) is not compatible with metadata")); } TEST(ValidateMetadataTest, Success) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, Unconstrained) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, ShapeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["shape"] = {7, 8}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"shape\" of \\[7,8\\] but received: \\[100,100\\]")); } TEST(ValidateMetadataTest, ChunksMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["chunks"] = {1, 1}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"chunks\" of \\[1,1\\] but received: \\[3,2\\]")); } TEST(ValidateMetadataTest, OrderMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["order"] = "F"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"order\" of \"F\" but received: \"C\"")); } TEST(ValidateMetadataTest, CompressorMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["compressor"] = nullptr; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"compressor\" of null but received: " "\\{\"blocksize\":0,\"clevel\":5,\"cname\":\"lz4\"," "\"id\":\"blosc\",\"shuffle\":-1\\}")); } TEST(ValidateMetadataTest, DTypeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["dtype"] = ">i4"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"dtype\" of \">i4\" but received: \"<i2\"")); } TEST(ValidateMetadataTest, FillValueMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["fill_value"] = 1; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"fill_value\" of 1 but received: null")); } TEST(ZarrCodecSpecTest, Merge) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec1, CodecSpec::Ptr::FromJson({{"driver", "zarr"}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec2, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"filters", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec3, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec4, CodecSpec::Ptr::FromJson( {{"driver", "zarr"}, {"compressor", {{"id", "blosc"}}}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec5, CodecSpec::Ptr::FromJson( {{"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}})); EXPECT_THAT(CodecSpec::Merge(codec1, codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(codec3, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec1, CodecSpec::Ptr()), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec::Ptr(), codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec::Ptr(), CodecSpec::Ptr()), ::testing::Optional(CodecSpec::Ptr())); EXPECT_THAT(CodecSpec::Merge(codec1, codec2), ::testing::Optional(codec2)); EXPECT_THAT(CodecSpec::Merge(codec1, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec2, codec3), ::testing::Optional(codec5)); EXPECT_THAT( CodecSpec::Merge(codec3, codec4), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(ZarrCodecSpecTest, RoundTrip) { tensorstore::TestJsonBinderRoundTripJsonOnly<tensorstore::CodecSpec::Ptr>({ ::nlohmann::json::value_t::discarded, { {"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}, }, { {"driver", "zarr"}, {"compressor", {{"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}}}, {"filters", nullptr}, }, }); } } // namespace
39.180387
80
0.541513
45fc2c960ca416349005f51c9a48b3b7ebc6b602
864
cpp
C++
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
#include "zoo.h" #include <gtest/gtest.h> #include <iostream> using namespace std; class ZooTest : public ::testing::Test { protected: ZooTest(){} }; TEST(ZooTest, Test1) { string filename="map.txt"; Zoo Z; Z.ReadZoo(filename.c_str()); ASSERT_EQ(21,Z.GetWidth()); ASSERT_EQ(21,Z.GetLength()); cout<<"width: "<<Z.GetWidth()<<endl; cout<<"length: "<<Z.GetLength()<<endl; for(int i=0;i<Z.GetWidth();i++) { for(int j=0;j<Z.GetLength();j++) { //cout<<i<<j<<(i*Z.GetLength()+j); //cout<<Z.GetCells()[i*Z.GetLength()+j]->GetX()<<Z.GetCells()[i*Z.GetLength()+j]->GetY()<<endl; ASSERT_EQ((i),Z.GetCells()[i*Z.GetLength()+j]->GetX()); ASSERT_EQ((j),Z.GetCells()[i*Z.GetLength()+j]->GetY()); } //cout<<endl; } Z.MakeCage(); ASSERT_EQ(17,Z.GetNCages()); }
26.181818
97
0.552083
3400b7fe0e4d35c15ef8c18b5b35a8a4fb0a140f
1,819
cc
C++
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
csteegz/onnxruntime
a36810471b346ec862ac6e4de7f877653f49525e
[ "MIT" ]
1
2020-07-12T15:23:49.000Z
2020-07-12T15:23:49.000Z
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
ajinkya933/onnxruntime
0e799a03f2a99da6a1b87a2cd37facb420c482aa
[ "MIT" ]
null
null
null
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
ajinkya933/onnxruntime
0e799a03f2a99da6a1b87a2cd37facb420c482aa
[ "MIT" ]
1
2020-09-09T06:55:51.000Z
2020-09-09T06:55:51.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "constant_of_shape.h" #include "core/providers/common.h" #include "gsl/gsl" using namespace ::onnxruntime::common; using namespace ONNX_NAMESPACE; namespace onnxruntime { namespace cuda { ONNX_OPERATOR_KERNEL_EX( ConstantOfShape, kOnnxDomain, 9, kCudaExecutionProvider, KernelDefBuilder() .InputMemoryType<OrtMemTypeCPUInput>(0) .TypeConstraint("T1", DataTypeImpl::GetTensorType<int64_t>()) .TypeConstraint("T2", DataTypeImpl::AllFixedSizeTensorTypes()), ConstantOfShape); Status ConstantOfShape::Compute(OpKernelContext* ctx) const { Tensor* output_tensor = nullptr; ORT_RETURN_IF_ERROR(PrepareCompute(ctx, &output_tensor)); auto output_data = output_tensor->MutableDataRaw(); const auto size = output_tensor->Shape().Size(); const void* value_ptr = GetValuePtr(); const auto element_size = output_tensor->DataType()->Size(); switch (element_size) { case sizeof(int8_t): cuda::Fill(reinterpret_cast<int8_t*>(output_data), *(reinterpret_cast<const int8_t*>(value_ptr)), size); break; case sizeof(int16_t): cuda::Fill(reinterpret_cast<int16_t*>(output_data), *(reinterpret_cast<const int16_t*>(value_ptr)), size); break; case sizeof(int32_t): cuda::Fill(reinterpret_cast<int32_t*>(output_data), *(reinterpret_cast<const int32_t*>(value_ptr)), size); break; case sizeof(int64_t): cuda::Fill(reinterpret_cast<int64_t*>(output_data), *(reinterpret_cast<const int64_t*>(value_ptr)), size); break; default: ORT_THROW("Unsupported value attribute datatype with sizeof=: ", element_size); break; } return Status::OK(); } } // namespace cuda } // namespace onnxruntime
33.685185
112
0.715778
340bb6123443172507c1477d203f1661a213c5d8
20,770
cpp
C++
admin/wmi/wbem/common/containers/cache.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/common/containers/cache.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/common/containers/cache.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef __CACHE_CPP #define __CACHE_CPP /*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: Thread.cpp Abstract: Enhancements to current functionality: Timeout mechanism should track across waits. AddRef/Release on task when scheduling. Enhancement Ticker logic. History: --*/ #include <HelperFuncs.h> /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ #if 0 // // The template argument for the below two operator functions // can never be deduced so I'm moving them to class WmiUniqueTimeout // // [TGani] // template <class WmiKey> bool operator == ( const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg1 , const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg2 ) { LONG t_Compare ; if ( ( t_Compare = a_Arg1.GetTicks () - a_Arg2.GetTicks () ) == 0 ) { t_Compare = a_Arg1.GetCounter () - a_Arg2.GetCounter () ; } return t_Compare == 0 ? true : false ; } template <class WmiKey> bool operator < ( const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg1 , const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg2 ) { LONG t_Compare ; if ( ( t_Compare = a_Arg1.GetTicks () - a_Arg2.GetTicks () ) == 0 ) { t_Compare = a_Arg1.GetCounter () - a_Arg2.GetCounter () ; } return t_Compare < 0 ? true : false ; } #endif //0 /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiCacheController <WmiKey> :: WmiCacheController ( WmiAllocator &a_Allocator ) : m_Allocator ( a_Allocator ) , m_Cache ( a_Allocator ) , m_CacheDecay ( a_Allocator ) , m_ReferenceCount ( 0 ) , m_Counter ( 0 ), m_CriticalSection(NOTHROW_LOCK) { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiCacheController <WmiKey> :: ~WmiCacheController () { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiCacheController <WmiKey> :: AddRef () { return InterlockedIncrement ( & m_ReferenceCount ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiCacheController <WmiKey> :: Release () { ULONG t_ReferenceCount = InterlockedDecrement ( & m_ReferenceCount ) ; if ( t_ReferenceCount == 0 ) { delete this ; } return t_ReferenceCount ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP WmiCacheController <WmiKey> :: QueryInterface ( REFIID , LPVOID FAR * ) { return E_NOINTERFACE ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Initialize () { WmiStatusCode t_StatusCode = m_Cache.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = m_CacheDecay.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: InitializeCriticalSection ( & m_CriticalSection ) ; } } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: UnInitialize () { WmiStatusCode t_StatusCode = m_Cache.UnInitialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = m_CacheDecay.UnInitialize () ; } WmiHelper :: DeleteCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Insert ( WmiCacheElement &a_Element , Cache_Iterator &a_Iterator ) { WmiStatusCode t_StatusCode = e_StatusCode_Success ; Lock () ; Cache_Iterator t_Iterator ; t_StatusCode = m_Cache.Insert ( a_Element.GetKey () , & a_Element , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Element.InternalAddRef () ; a_Element.SetCached ( TRUE ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Delete ( const WmiKey &a_Key ) { Lock () ; WmiStatusCode t_StatusCode = m_Cache.Delete ( a_Key ) ; UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Find ( const WmiKey &a_Key , Cache_Iterator &a_Iterator ) { Lock () ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Key , a_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Iterator.GetElement ()->AddRef ( ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Lock () { WmiStatusCode t_StatusCode = WmiHelper :: EnterCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: UnLock () { WmiStatusCode t_StatusCode = WmiHelper :: LeaveCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Shutdown () { Lock () ; ULONG t_Index = 0 ; while ( true ) { WmiUniqueTimeout t_Key ; WmiCacheElement *t_Element = NULL ; WmiStatusCode t_StatusCode = m_CacheDecay.Top ( t_Key , t_Element ) ; if ( t_StatusCode == e_StatusCode_Success ) { t_Index ++ ; t_StatusCode = m_CacheDecay.DeQueue () ; } else { break ; } } ULONG t_ElementCount = m_Cache.Size () ; WmiCacheElement **t_Elements = NULL ; WmiStatusCode t_StatusCode = m_Allocator.New ( ( void ** ) & t_Elements , sizeof ( WmiCacheElement ) * t_ElementCount ) ; if ( t_StatusCode == e_StatusCode_Success ) { for ( ULONG t_Index = 0 ; t_Index < t_ElementCount ; t_Index ++ ) { t_Elements [ t_Index ] = NULL ; } ULONG t_ElementIndex = 0 ; Cache_Iterator t_Iterator = m_Cache.Root (); while ( ! t_Iterator.Null () ) { if ( t_Iterator.GetElement ()->GetDecayed () == FALSE ) { WmiCacheElement *t_Element = t_Iterator.GetElement () ; t_Elements [ t_ElementIndex ] = t_Element ; t_Element->SetDecayed ( TRUE ) ; t_Element->SetDecaying ( FALSE ) ; t_Element->SetCached ( FALSE ) ; m_Cache.Delete ( t_Iterator.GetKey () ) ; } else { m_Cache.Delete ( t_Iterator.GetKey () ) ; } t_ElementIndex ++ ; t_Iterator = m_Cache.Root () ; } } UnLock () ; if ( t_Elements ) { for ( ULONG t_Index = 0 ; t_Index < t_ElementCount ; t_Index ++ ) { if ( t_Elements [ t_Index ] ) { t_Elements [ t_Index ]->InternalRelease () ; } } m_Allocator.Delete ( t_Elements ) ; } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Shutdown ( const WmiKey &a_Key ) { Lock () ; Cache_Iterator t_Iterator ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Key , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { if ( t_Iterator.GetElement ()->GetDecayed () == FALSE ) { CacheDecay_Iterator t_QueueIterator = m_CacheDecay.Begin () ; while ( ! t_QueueIterator.Null () ) { WmiCacheElement *t_Element = t_QueueIterator.GetElement () ; if ( t_Element == t_Iterator.GetElement () ) { m_CacheDecay.Delete ( t_QueueIterator.GetKey () ) ; break ; } t_QueueIterator.Increment () ; } WmiCacheElement *t_Element = t_Iterator.GetElement () ; t_Element->SetDecayed ( TRUE ) ; t_Element->SetDecaying ( FALSE ) ; t_Element->SetCached ( FALSE ) ; m_Cache.Delete ( a_Key ) ; UnLock () ; t_Element->InternalRelease () ; } else { m_Cache.Delete ( a_Key ) ; UnLock () ; } } else { UnLock () ; } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: StrobeBegin ( const ULONG &a_Timeout ) { return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Strobe ( ULONG &a_NextStrobeDelta ) { while ( true ) { Lock () ; WmiUniqueTimeout t_Key ; WmiCacheElement *t_Element = NULL ; WmiStatusCode t_StatusCode = m_CacheDecay.Top ( t_Key , t_Element ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_NextStrobeDelta = ( a_NextStrobeDelta < t_Element->GetPeriod () ) ? a_NextStrobeDelta : t_Element->GetPeriod () ; ULONG t_Ticks = GetTickCount () ; #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Checking ( %lx , %lx ) " , t_Ticks , t_Element , t_Key.GetTicks () ) ; OutputDebugString ( t_Buffer ) ; #endif if ( t_Ticks >= t_Key.GetTicks () ) { if ( t_Element->GetDecaying () ) { #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Strobe ( %lx , %lx ) " , t_Ticks , t_Element , t_Key.GetTicks () ) ; OutputDebugString ( t_Buffer ) ; #endif t_Element->SetDecaying ( FALSE ) ; t_Element->SetDecayed ( TRUE ) ; t_StatusCode = m_CacheDecay.DeQueue () ; UnLock () ; t_Element->InternalRelease () ; } else { t_StatusCode = m_CacheDecay.DeQueue () ; UnLock () ; } } else { UnLock () ; break ; } } else { UnLock () ; break ; } } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Decay ( WmiCacheElement &a_Element ) { Lock () ; ULONG t_Size = m_CacheDecay.Size () ; Cache_Iterator t_Iterator ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Element.GetKey () , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { BOOL t_Found = FALSE ; CacheDecay_Iterator t_QueueIterator = m_CacheDecay.Begin () ; while ( ! t_QueueIterator.Null () ) { WmiCacheElement *t_Element = t_QueueIterator.GetElement () ; if ( t_Element == & a_Element ) { m_CacheDecay.Delete ( t_QueueIterator.GetKey () ) ; break ; } t_QueueIterator.Increment () ; } ULONG t_Ticks = GetTickCount () ; WmiUniqueTimeout t_Key ( t_Ticks + a_Element.GetPeriod () , InterlockedIncrement ( & m_Counter ) ) ; #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Decaying ( %lx , %lx , %lx ) " , t_Ticks , & a_Element , t_Ticks + a_Element.GetPeriod () , a_Element.GetPeriod () ) ; OutputDebugString ( t_Buffer ) ; #endif t_StatusCode = m_CacheDecay.EnQueue ( t_Key , t_Iterator.GetElement () ) ; UnLock () ; if ( t_Size == 0 ) { StrobeBegin ( a_Element.GetPeriod () ) ; } if ( t_StatusCode != e_StatusCode_Success ) { a_Element.InternalRelease () ; } } else { UnLock () ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiContainerController <WmiKey> :: WmiContainerController ( WmiAllocator &a_Allocator ) : m_Container ( a_Allocator ) , m_ReferenceCount ( 0 ), m_CriticalSection(NOTHROW_LOCK) { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiContainerController <WmiKey> :: ~WmiContainerController () { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiContainerController <WmiKey> :: AddRef () { return InterlockedIncrement ( & m_ReferenceCount ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiContainerController <WmiKey> :: Release () { ULONG t_ReferenceCount = InterlockedDecrement ( & m_ReferenceCount ) ; if ( t_ReferenceCount == 0 ) { delete this ; } return t_ReferenceCount ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP WmiContainerController <WmiKey> :: QueryInterface ( REFIID , LPVOID FAR * ) { return E_NOINTERFACE ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Initialize () { WmiStatusCode t_StatusCode = m_Container.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: InitializeCriticalSection ( & m_CriticalSection ) ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: UnInitialize () { WmiStatusCode t_StatusCode = m_Container.UnInitialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: DeleteCriticalSection ( & m_CriticalSection ) ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Insert ( WmiContainerElement &a_Element , Container_Iterator &a_Iterator ) { WmiStatusCode t_StatusCode = e_StatusCode_Success ; Lock () ; Container_Iterator t_Iterator ; t_StatusCode = m_Container.Insert ( a_Element.GetKey () , & a_Element , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Element.InternalAddRef () ; a_Element.SetCached ( TRUE ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Delete ( const WmiKey &a_Key ) { Lock () ; WmiStatusCode t_StatusCode = m_Container.Delete ( a_Key ) ; UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Find ( const WmiKey &a_Key , Container_Iterator &a_Iterator ) { Lock () ; WmiStatusCode t_StatusCode = m_Container.Find ( a_Key , a_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Iterator.GetElement ()->AddRef ( ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Lock () { return WmiHelper :: EnterCriticalSection ( & m_CriticalSection ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: UnLock () { WmiHelper :: LeaveCriticalSection ( & m_CriticalSection ) ; return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Shutdown () { Lock () ; Container_Iterator t_Iterator = m_Container.Root (); while ( ! t_Iterator.Null () ) { m_Container.Delete ( t_Iterator.GetKey () ) ; t_Iterator = m_Container.Root () ; } UnLock () ; return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Strobe ( ULONG &a_NextStrobeDelta ) { return e_StatusCode_Success ; } #endif __CACHE_CPP
21.568017
166
0.463361
340d6c50a67b4c8909b1b938d3bfcfba35570a14
2,545
cpp
C++
benchmarks/PushmiBenchmarks.cpp
LeeHowes/pushmi
56b4edd1f891173c281cde8cd637e84a2b19db24
[ "MIT" ]
null
null
null
benchmarks/PushmiBenchmarks.cpp
LeeHowes/pushmi
56b4edd1f891173c281cde8cd637e84a2b19db24
[ "MIT" ]
null
null
null
benchmarks/PushmiBenchmarks.cpp
LeeHowes/pushmi
56b4edd1f891173c281cde8cd637e84a2b19db24
[ "MIT" ]
null
null
null
#include "pushmi/o/just.h" #include "pushmi/o/on.h" #include "pushmi/o/transform.h" #include "pushmi/o/tap.h" #include "pushmi/o/via.h" #include "pushmi/o/submit.h" #include "pushmi/trampoline.h" #include "pushmi/new_thread.h" #include "pool.h" using namespace pushmi::aliases; struct countdownsingle { countdownsingle(int& c) : counter(&c) {} int* counter; template <class ExecutorRef> void operator()(ExecutorRef exec) { if (--*counter > 0) { exec | op::submit(*this); } } }; #define concept Concept #include <nonius/nonius.h++> NONIUS_BENCHMARK("trampoline virtual derecursion 10,000", [](nonius::chronometer meter){ int counter = 0; auto tr = mi::trampoline(); using TR = decltype(tr); std::function<void(mi::any_time_executor_ref<> exec)> recurse; recurse = [&](mi::any_time_executor_ref<> tr) { if (--counter <= 0) return; tr | op::submit(recurse); }; meter.measure([&]{ counter = 10'000; return tr | op::submit([&](auto exec) { recurse(exec); }); }); }) NONIUS_BENCHMARK("trampoline static derecursion 10,000", [](nonius::chronometer meter){ int counter = 0; auto tr = mi::trampoline(); using TR = decltype(tr); countdownsingle single{counter}; meter.measure([&]{ counter = 10'000; return tr | op::submit(single); }); }) NONIUS_BENCHMARK("new thread 10 blocking_submits", [](nonius::chronometer meter){ auto nt = mi::new_thread(); using NT = decltype(nt); meter.measure([&]{ return nt | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::transform([](auto nt){ return v::now(nt); }) | op::get<std::chrono::system_clock::time_point>; }); }) NONIUS_BENCHMARK("pool 10 blocking_submits", [](nonius::chronometer meter){ mi::pool pl{std::max(1u,std::thread::hardware_concurrency())}; auto pe = pl.executor(); using PE = decltype(pe); meter.measure([&]{ return pe | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::blocking_submit() | op::transform([](auto pe){ return mi::now(pe); }) | op::get<std::chrono::system_clock::time_point>; }); })
24.95098
88
0.618468
340d8d8c9c06398aa863a0fa2d11b0c4615c77c5
35,044
cpp
C++
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-11-23T08:13:14.000Z
2021-11-23T08:13:14.000Z
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
null
null
null
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-09-13T11:17:54.000Z
2021-09-13T11:17:54.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 <fcntl.h> #include <fstream> #include <future> #include <gtest/gtest.h> #include "ability_handler.h" #include "ability_info.h" #include "ability_local_record.h" #include "ability_start_setting.h" #include "app_log_wrapper.h" #include "common_event.h" #include "common_event_manager.h" #include "context_deal.h" #include "form_event.h" #include "form_st_common_info.h" #include "iservice_registry.h" #include "nlohmann/json.hpp" #include "system_ability_definition.h" #include "system_test_form_util.h" using OHOS::AAFwk::Want; using namespace testing::ext; using namespace std::chrono_literals; using namespace OHOS::STtools; namespace { const int FORM_COUNT_200 = 200; const int FORM_COUNT_112 = 112; const int TEMP_FORM_COUNT_256 = 256; const int TEMP_FORM_COUNT_128 = 128; std::vector<std::string> bundleNameList = { "com.form.formsystemtestservicea", "com.form.formsystemtestserviceb", }; std::vector<std::string> hapNameList = { "formSystemTestServiceA-signed", "formSystemTestServiceB-signed", }; std::vector<std::string> normalFormsMaxA; std::vector<std::string> normalFormsMaxB; std::vector<std::string> normalFormsMaxC; std::vector<std::string> tempFormsMaxA; std::vector<std::string> tempFormsMaxB; } // namespace namespace OHOS { namespace AppExecFwk { class FmsAcquireFormTestMax : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); static bool SubscribeEvent(); void SetUp(); void TearDown(); void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; virtual void OnReceiveEvent(const CommonEventData &data) override; ~FormEventSubscriber() = default; }; static sptr<AAFwk::IAbilityManager> abilityMs; static FormEvent event; static std::vector<std::string> eventList; static std::shared_ptr<FormEventSubscriber> subscriber; void FmsAcquireForm2700(std::string strFormId); std::string FmsAcquireForm2900A(); std::string FmsAcquireForm2900B(); void FmsAcquireForm3000(); std::string FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName); void FmsAcquireForm2800(std::string strFormId); void FmsAcquireForm3200(); void FmsAcquireFormDeleteA(const std::string &strFormId); void FmsAcquireFormDeleteB(const std::string &strFormId); void FmsAcquireFormDeleteC(const std::string &strFormId); std::string FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName); bool FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName); }; std::vector<std::string> FmsAcquireFormTestMax::eventList = { FORM_EVENT_RECV_DELETE_FORM_COMMON, FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, FORM_EVENT_RECV_ACQUIRE_FORM_2700, FORM_EVENT_RECV_ACQUIRE_FORM_2800, FORM_EVENT_RECV_ACQUIRE_FORM_2900, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, FORM_EVENT_RECV_ACQUIRE_FORM_3000, FORM_EVENT_RECV_ACQUIRE_FORM_3100, FORM_EVENT_RECV_ACQUIRE_FORM_3200, }; FormEvent FmsAcquireFormTestMax::event = FormEvent(); sptr<AAFwk::IAbilityManager> FmsAcquireFormTestMax::abilityMs = nullptr; std::shared_ptr<FmsAcquireFormTestMax::FormEventSubscriber> FmsAcquireFormTestMax::subscriber = nullptr; void FmsAcquireFormTestMax::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) { GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); } void FmsAcquireFormTestMax::SetUpTestCase() { if (!SubscribeEvent()) { GTEST_LOG_(INFO) << "SubscribeEvent error"; } } void FmsAcquireFormTestMax::TearDownTestCase() { GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; CommonEventManager::UnSubscribeCommonEvent(subscriber); } void FmsAcquireFormTestMax::SetUp() { } void FmsAcquireFormTestMax::TearDown() { GTEST_LOG_(INFO) << "CleanMsg calld"; SystemTestFormUtil::CleanMsg(event); } bool FmsAcquireFormTestMax::SubscribeEvent() { GTEST_LOG_(INFO) << "SubscribeEvent calld"; MatchingSkills matchingSkills; for (const auto &e : eventList) { matchingSkills.AddEvent(e); } CommonEventSubscribeInfo subscribeInfo(matchingSkills); subscribeInfo.SetPriority(1); subscriber = std::make_shared<FormEventSubscriber>(subscribeInfo); return CommonEventManager::SubscribeCommonEvent(subscriber); } /** * @tc.number: FMS_acquireForm_2900 * @tc.name: A single host creates 256 different provider forms. * @tc.desc: The single host can successfully create 256 different provider forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2900, Function | MediumTest | Level1) { std::cout << "START FMS_acquireForm_2900" << std::endl; for (int count = 0; count < Constants::MAX_RECORD_PER_APP/2; count++) { sleep(7); std::string strFormId1 = FmsAcquireForm2900A(); normalFormsMaxA.emplace_back(strFormId1); std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; sleep(7); std::string strFormId2 = FmsAcquireForm2900B(); normalFormsMaxA.emplace_back(strFormId2); std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; } std::cout << "END FMS_acquireForm_2900" << std::endl; } /** * @tc.number: FMS_acquireForm_3000 * @tc.name: Create limit value verification using single party form. * @tc.desc: Failed to create the 257th host form. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3000, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3000" << std::endl; std::cout << "FMS_acquireForm_3000, form size of the host A:" << normalFormsMaxA.size() << std::endl; FmsAcquireForm3000(); std::cout << "END FMS_acquireForm_3000" << std::endl; } /** * @tc.number: FMS_acquireForm_2700 * @tc.name: When the normal form reaches the maximum value (256) created by the host, * the temporary form is transferred to the normal form. * @tc.desc: Verify that when the normal form reaches the maximum value (256) created by the single host, * the conversion of the temporary form to the normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2700, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_2700" << std::endl; std::cout << "FMS_acquireForm_2700, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); sleep(7); FmsAcquireForm2700(strFormId); std::cout << "END FMS_acquireForm_2700" << std::endl; std::cout << "the host A, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(normalFormsMaxA[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxA.clear(); std::cout << "the host A, dlete form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3100 * @tc.name: Multiple hosts create 512 forms respectively. * @tc.desc: Verify that multiple hosts can create 512 forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3100, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3100" << std::endl; std::cout << "START add form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < FORM_COUNT_200; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameA, abilityNameA); normalFormsMaxA.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host A" << std::endl; std::cout << "START add form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; for (int count = 0; count < FORM_COUNT_200; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameB, abilityNameB); normalFormsMaxB.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host B" << std::endl; std::cout << "START add form to the host C" << std::endl; std::string bundleNameC = "com.ohos.form.manager.normalc"; std::string abilityNameC = "FormAbilityC"; std::cout << "bundleName: " << bundleNameC << std::endl; std::cout << "abilityName: " << abilityNameC << std::endl; for (int count = 0; count < FORM_COUNT_112; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameC, abilityNameC); normalFormsMaxC.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host C" << std::endl; std::cout << "END FMS_acquireForm_3100" << std::endl; } /** * @tc.number: FMS_acquireForm_2800 * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, * the temporary form will be transferred to the normal form. * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, * the conversion of temporary form to normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2800, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_2800" << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host B:" << normalFormsMaxB.size() << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host C:" << normalFormsMaxC.size() << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); sleep(7); FmsAcquireForm2800(strFormId); std::cout << "END FMS_acquireForm_2800" << std::endl; } /** * @tc.number: FMS_acquireForm_2800 * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, * the temporary form will be transferred to the normal form. * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, * the conversion of temporary form to normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3200, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3200" << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host B:" << normalFormsMaxB.size() << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host C:" << normalFormsMaxC.size() << std::endl; FmsAcquireForm3200(); std::cout << "END FMS_acquireForm_3200" << std::endl; std::cout << "the host A, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(normalFormsMaxA[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxA.clear(); std::cout << "the host A, dlete form end" << std::endl; std::cout << "the host B, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxB.size(); count++) { sleep(7); FmsAcquireFormDeleteB(normalFormsMaxB[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxB.clear(); std::cout << "the host B, dlete form end" << std::endl; std::cout << "the host C, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxC.size(); count++) { sleep(7); FmsAcquireFormDeleteC(normalFormsMaxC[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxC.clear(); std::cout << "the host C, dlete form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3300 * @tc.name: A single host can create 256 temporary forms. * @tc.desc: The host of the verification form can successfully create 256 temporary forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3300, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3300" << std::endl; std::cout << "START add temp form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_256; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); tempFormsMaxA.emplace_back(strFormId); std::cout << "FMS_acquireForm_3300, form size of the host A:" << tempFormsMaxA.size() << std::endl; } std::cout << "END add temp form to the host A" << std::endl; std::cout << "END FMS_acquireForm_3300" << std::endl; std::cout << "the host A, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(tempFormsMaxA[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxA.clear(); std::cout << "the host A, dlete temp form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3400 * @tc.name: 256 temporary forms can be created by multiple hosts. * @tc.desc: Verify that multiple hosts can successfully create 256 temporary forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3400, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3400" << std::endl; std::cout << "START add temp form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); tempFormsMaxA.emplace_back(strFormId); std::cout << "FMS_acquireForm_3400, temp form size of the host A:" << tempFormsMaxA.size() << std::endl; } std::cout << "END add temp form to the host A" << std::endl; std::cout << "START add temp form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameB, abilityNameB); tempFormsMaxB.emplace_back(strFormId); std::cout << "FMS_acquireForm_3400, temp form size of the host B:" << tempFormsMaxB.size() << std::endl; } std::cout << "END add temp form to the host B" << std::endl; std::cout << "END FMS_acquireForm_3400" << std::endl; } /** * @tc.number: FMS_acquireForm_3500 * @tc.name: Create temporary form limit value (256) verification. * @tc.desc: Failed to create the 257th temporary form for multiple users. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3500, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3500" << std::endl; std::cout << "START add temp form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; bool result = FmsAcquireFormTempForFailed(bundleNameB, abilityNameB); EXPECT_TRUE(result); if (result) { std::cout << "END add temp form to the host B, Failed to create the 257th temporary form." << std::endl; } std::cout << "END FMS_acquireForm_3500" << std::endl; std::cout << "the host A, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(tempFormsMaxA[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxA.clear(); std::cout << "the host A, dlete temp form end" << std::endl; std::cout << "the host B, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxB.size(); count++) { sleep(7); FmsAcquireFormDeleteB(tempFormsMaxB[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxB.clear(); std::cout << "the host B, dlete temp form end" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName) { MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3100; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3100, EVENT_CODE_3100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm3100, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result2; return strFormId; } void FmsAcquireFormTestMax::FmsAcquireForm2700(std::string strFormId) { std::cout << "START FmsAcquireForm2700, cast temp form" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData1 = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2700, EVENT_CODE_2700, eventData1); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700)); std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700); bool result3 = data3 == "false"; EXPECT_TRUE(result3); GTEST_LOG_(INFO) << "FmsAcquireForm2700, result:" << result3; // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result4 = data4 == "true"; EXPECT_TRUE(result4); GTEST_LOG_(INFO) << "FmsAcquireForm2700, delete form, result:" << result4; std::cout << "END FmsAcquireForm2700, cast temp form" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireForm3200() { std::cout << "START FmsAcquireForm3200" << std::endl; std::string bundleName = "com.ohos.form.manager.normalc"; std::string abilityName = "FormAbilityC"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3200; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3200, EVENT_CODE_3200, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200); bool result = data == "false"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireForm3200, result:" << result; std::cout << "END FmsAcquireForm3200" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireForm2800(std::string strFormId) { std::cout << "START FmsAcquireForm2800, cast temp form" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData1 = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2800, EVENT_CODE_2800, eventData1); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800)); std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800); bool result3 = data3 == "false"; EXPECT_TRUE(result3); GTEST_LOG_(INFO) << "FmsAcquireForm2800, result:" << result3; // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result4 = data4 == "true"; EXPECT_TRUE(result4); GTEST_LOG_(INFO) << "FmsAcquireForm2800, delete form, result:" << result4; std::cout << "END FmsAcquireForm2800, cast temp form" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireForm2900A() { std::cout << "START FmsAcquireForm2900A, Provider A" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900, EVENT_CODE_2900, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm2900A, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result2; std::cout << "END FmsAcquireForm2900A, Provider A" << std::endl; return strFormId; } std::string FmsAcquireFormTestMax::FmsAcquireForm2900B() { std::cout << "START FmsAcquireForm2900B, Provider B" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900_1; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900_1, EVENT_CODE_2910, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm2900B, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result2; std::cout << "END FmsAcquireForm2900B, Provider B" << std::endl; return strFormId; } void FmsAcquireFormTestMax::FmsAcquireForm3000() { std::cout << "START FmsAcquireForm3000" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3000; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3000, EVENT_CODE_3000, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000); bool result = data == "false"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireForm3000, result:" << result; std::cout << "END FmsAcquireForm3000" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName) { std::cout << "START FmsAcquireFormTemp, add temp form" << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1); bool result2 = !data2.empty(); EXPECT_TRUE(result2); if (!result2) { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result2; } else { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formData:" << data2; } std::cout << "END FmsAcquireFormTemp, add temp form" << std::endl; return strFormId; } bool FmsAcquireFormTestMax::FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName) { std::cout << "START FmsAcquireFormTempForFailed, add temp form" << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); bool result = strFormId.empty(); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormTempForFailed, result:" << result; std::cout << "END FmsAcquireFormTempForFailed, add temp form" << std::endl; return result; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteA(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteA, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; std::cout << "START FmsAcquireFormDeleteA, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteA, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteA, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteA end" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteB(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteB, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normalb"; std::string abilityName = "FormAbilityB"; std::cout << "START FmsAcquireFormDeleteB, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteB, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteB, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteB end" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteC(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteC, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normalc"; std::string abilityName = "FormAbilityC"; std::cout << "START FmsAcquireFormDeleteC, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteC, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteC, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteC end" << std::endl; } } // namespace AppExecFwk } // namespace OHOS
45.929227
118
0.712561
340e6371cfab072dd0358adeb73a5d20197bc9ca
701
cc
C++
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
58
2015-10-15T09:28:20.000Z
2022-03-28T20:09:38.000Z
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
1,741
2015-11-24T08:17:02.000Z
2022-03-31T15:46:42.000Z
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
45
2015-10-14T13:44:16.000Z
2022-03-22T14:45:56.000Z
/* * unimodal.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/image/threshold/unimodal.h> namespace dials { namespace algorithms { namespace boost_python { using namespace boost::python; void export_unimodal() { def("maximum_deviation", &maximum_deviation, (arg("histo"))); def("probability_distribution", &probability_distribution, (arg("image"), arg("range"))); } }}} // namespace dials::algorithms::boost_python
25.962963
70
0.699001
3413fcae1164f05e6869430c9c549bdc3b7a6e7c
6,668
hpp
C++
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
1
2022-02-23T23:38:40.000Z
2022-02-23T23:38:40.000Z
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
12
2021-09-20T21:23:27.000Z
2022-03-31T22:53:30.000Z
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
2
2022-01-27T20:58:07.000Z
2022-02-09T23:07:41.000Z
/* * Copyright (c) 2021, NVIDIA 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. */ #pragma once #ifdef TRITON_ENABLE_GPU #include <cuda_runtime_api.h> #else #include <rapids_triton/cpu_only/cuda_runtime_replacement.hpp> #endif #include <cstddef> #include <rapids_triton/batch/batch.hpp> #include <rapids_triton/memory/resource.hpp> #include <rapids_triton/model/shared_state.hpp> #include <rapids_triton/tensor/tensor.hpp> #include <rapids_triton/triton/deployment.hpp> #include <rapids_triton/triton/device.hpp> #include <rapids_triton/utils/narrow.hpp> #include <string> #include <vector> namespace triton { namespace backend { namespace rapids { template <typename SharedState = SharedModelState> struct Model { virtual void predict(Batch& batch) const = 0; virtual void load() {} virtual void unload() {} /** * @brief Return the preferred memory type in which to store data for this * batch or std::nullopt to accept whatever Triton returns * * The base implementation of this method will require data on-host if the * model itself is deployed on the host OR if this backend has not been * compiled with GPU support. Otherwise, models deployed on device will * receive memory on device. Overriding this method will allow derived * model classes to select a preferred memory location based on properties * of the batch or to simply return std::nullopt if device memory or host * memory will do equally well. */ virtual std::optional<MemoryType> preferred_mem_type(Batch& batch) const { return (IS_GPU_BUILD && deployment_type_ == GPUDeployment) ? DeviceMemory : HostMemory; } virtual std::optional<MemoryType> preferred_mem_type_in(Batch& batch) const { return preferred_mem_type(batch); } virtual std::optional<MemoryType> preferred_mem_type_out(Batch& batch) const { return preferred_mem_type(batch); } /** * @brief Retrieve a stream used to set up batches for this model * * The base implementation of this method simply returns the default stream * provided by Triton for use with this model. Child classes may choose to * override this in order to provide different streams for use with * successive incoming batches. For instance, one might cycle through * several streams in order to distribute batches across them, but care * should be taken to ensure proper synchronization in this case. */ virtual cudaStream_t get_stream() const { return default_stream_; } /** * @brief Get input tensor of a particular named input for an entire batch */ template <typename T> auto get_input(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, cudaStream_t stream) const { return batch.get_input<T const>(name, mem_type, device_id_, stream); } template <typename T> auto get_input(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type) const { return get_input<T>(batch, name, mem_type, default_stream_); } template <typename T> auto get_input(Batch& batch, std::string const& name) const { return get_input<T>(batch, name, preferred_mem_type(batch), default_stream_); } /** * @brief Get output tensor of a particular named output for an entire batch */ template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, device_id_t device_id, cudaStream_t stream) const { return batch.get_output<T>(name, mem_type, device_id, stream); } template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, cudaStream_t stream) const { return get_output<T>(batch, name, mem_type, device_id_, stream); } template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type) const { return get_output<T>(batch, name, mem_type, device_id_, default_stream_); } template <typename T> auto get_output(Batch& batch, std::string const& name) const { return get_output<T>(batch, name, preferred_mem_type(batch), device_id_, default_stream_); } /** * @brief Retrieve value of configuration parameter */ template <typename T> auto get_config_param(std::string const& name) const { return shared_state_->template get_config_param<T>(name); } template <typename T> auto get_config_param(std::string const& name, T default_value) const { return shared_state_->template get_config_param<T>(name, default_value); } template <typename T> auto get_config_param(char const* name) const { return get_config_param<T>(std::string(name)); } template <typename T> auto get_config_param(char const* name, T default_value) const { return get_config_param<T>(std::string(name), default_value); } Model(std::shared_ptr<SharedState> shared_state, device_id_t device_id, cudaStream_t default_stream, DeploymentType deployment_type, std::string const& filepath) : shared_state_{shared_state}, device_id_{device_id}, default_stream_{default_stream}, deployment_type_{deployment_type}, filepath_{filepath} { if constexpr (IS_GPU_BUILD) { setup_memory_resource(device_id_); } } auto get_device_id() const { return device_id_; } auto get_deployment_type() const { return deployment_type_; } auto const& get_filepath() const { return filepath_; } auto get_output_shape(std::string const& name) const { return shared_state_->get_output_shape(name); } protected: auto get_shared_state() const { return shared_state_; } private: std::shared_ptr<SharedState> shared_state_; device_id_t device_id_; cudaStream_t default_stream_; DeploymentType deployment_type_; std::string filepath_; }; } // namespace rapids } // namespace backend } // namespace triton
33.676768
94
0.707858
3415954e216bb53928018e5951bfdded31f93395
9,872
cpp
C++
Engine/src/Core/IO/icFileWin.cpp
binofet/ice
dee91da76df8b4f46ed4727d901819d8d20aefe3
[ "MIT" ]
null
null
null
Engine/src/Core/IO/icFileWin.cpp
binofet/ice
dee91da76df8b4f46ed4727d901819d8d20aefe3
[ "MIT" ]
null
null
null
Engine/src/Core/IO/icFileWin.cpp
binofet/ice
dee91da76df8b4f46ed4727d901819d8d20aefe3
[ "MIT" ]
null
null
null
#ifdef WIN32 #include "Core/IO/icFile.h" /*! Function converts ICE file modes to Microsoft flags * * @param u8Mode 8-bit mask of ICFILEMODE flags * @param[out] pAccess Pointer for access rights * @param[out] pCreateD Pointer for creation disposition * @param[out] pFandA Pointer for flags and attributes **/ void _GetFileParams(uchar u8Mode, DWORD* pAccess, DWORD* pCreateD, DWORD* pFandA) { *pAccess=0; *pFandA = 0; if (u8Mode&ICFM_READ) *pAccess |= GENERIC_READ; if (u8Mode&ICFM_WRITE) *pAccess |= GENERIC_WRITE; if (u8Mode&ICFM_CREATE_ALWAYS) *pCreateD = CREATE_ALWAYS; if (u8Mode&ICFM_CREATE_NEW) *pCreateD = CREATE_NEW; if (u8Mode&ICFM_OPEN_ALWAYS) *pCreateD = OPEN_ALWAYS; if (u8Mode&ICFM_OPEN_EXISTING) *pCreateD = OPEN_EXISTING; if (u8Mode&ICFM_ASYNC) *pFandA |= FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING; }// END FUNCTION _GetFileParams(uchar u8Mode, DWORD* pAccess, DWORD* pCreateD) /*! Asynchronous operation callback * * * @param dwErrorCode Error flags * @param dwBytesMoved The number of bytes transferred * @param lpOverlapped The overlapped structure for async op **/ VOID CALLBACK icFile::AsyncCB(__in DWORD dwErrorCode, __in DWORD dwBytesMoved, __in LPOVERLAPPED lpOverlapped) { if (lpOverlapped) { icFile* pFile = static_cast<icFile*>(lpOverlapped); // check for errors if (dwErrorCode) { // should probably take a look at better way to handle this icWarning("There was an error returned from Async Operation"); } pFile->m_u64FilePos += dwBytesMoved; pFile->m_bStreaming = false; // call user callback function with their pointer if (pFile->m_pVoidCallback) (*pFile->m_pVoidCallback)(pFile->m_ptrUser, (size_t)dwBytesMoved); } else { // this should likely never happen icError("Undefined behavior in Asynchronous callback"); } } /*! c'tor **/ icFile::icFile(void) { ZeroMemory(this,sizeof(icFile)); m_pFile = NULL; m_ptrUser = NULL; m_pVoidCallback = NULL; m_u64FilePos = 0; m_bStreaming = false; }// END FUNCTION icFile(void) /*! d'tor **/ icFile::~icFile(void) { if (m_pFile) { StopAsync(); if (hEvent) CloseHandle(hEvent); CloseHandle(m_pFile); } }// END FUNCTION ~icFile(void) /*! Opens a file * * @param szFile Name of file to open * @param u8Mode File mode (read/write/etc) * @returns ICRESULT Status after open **/ ICRESULT icFile::Open(const char *szFile, uchar u8Mode) { Close(); DWORD dwAccess=0; DWORD dwShareMode=FILE_SHARE_READ; //! should this be exposed? DWORD dwCreateDisp=0; DWORD dwFandA=0; m_FileMode = u8Mode; _GetFileParams(u8Mode, &dwAccess, &dwCreateDisp, &dwFandA); m_pFile = CreateFileA(szFile, // LPCSTR dwAccess, // Desired Access dwShareMode, // Share Mode NULL, // lpSecurityAttributes dwCreateDisp, // Creation Disposition dwFandA, // Flags and attributes NULL); // HANDLE to template file if (m_pFile && m_pFile != INVALID_HANDLE_VALUE) return IC_OK; return IC_FAIL_GEN; }// END FUNCTION Open(const char* szFile, u /*! Closes the file * * This will stall in the event there is an asynchronous operation * still in progress. * * @returns ICRESULT Status after closing the file **/ ICRESULT icFile::Close(void) { m_FileMode = 0; m_ptrUser = NULL; m_pVoidCallback = NULL; m_u64FilePos = 0; if (m_pFile) { // WAIT FOR ANY PENDING ASYNCHRONOUS CALLS while (m_bStreaming) SleepEx(50, TRUE); if (hEvent) { CloseHandle(hEvent); hEvent = NULL; } if (CloseHandle(m_pFile)) { m_pFile = NULL; return IC_OK; } m_pFile = NULL; return IC_FAIL_GEN; } m_bStreaming = false; return IC_OK; }// END FUNCTION Close(void) /*! Reads data from file * * Note: This should not be called by ASYNC File objects * * @param pDest Destination buffer * @param size Size in bytes to read * @param sizeread Pointer to store size actually read * @returns ICRESULT Status after file read **/ ICRESULT icFile::Read(void* pDest, size_t size, size_t* sizeread) { if (m_pFile && !(m_FileMode&ICFM_ASYNC)) { if (ReadFile(m_pFile, pDest, size, (LPDWORD)sizeread, NULL)) { m_u64FilePos += *sizeread; return IC_OK; } } return IC_WARN_GEN; }// END FUNCTION Read(void* pDest, size_t size, size_t* sizeread) /*! Asynchronous Read * * * * @param pDest Destination buffer * @param size Size in bytes to read * @param userPtr Pointer user can use as needed * @param callback Function to call when read is finished * @returns ICRESULT Status after starting the async-read **/ ICRESULT icFile::ReadAsync(void* pDest, size_t size, void* userPtr, void (*callback)(void*,size_t)) { if (m_pFile && !m_bStreaming) { m_pVoidCallback = callback; m_ptrUser = userPtr; m_bStreaming = true; hEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); if (ReadFileEx(m_pFile, pDest, size, (LPOVERLAPPED)this, AsyncCB)) return IC_OK; m_bStreaming = false; } return IC_WARN_GEN; }// END FUNCTION ReadAsync(void* pDest, size_t size, void (*callback)(void)) /*! Stops all Asynchronous operations * * @returns ICRESULT Status after stopping asynchronous ops **/ ICRESULT icFile::StopAsync(void) { if (m_pFile && m_bStreaming) { if (CancelIo(m_pFile)) //if (CancelIoEx(m_pFile, this)) { m_bStreaming = false; return IC_OK; } } return IC_WARN_GEN; }// END FUNCTION StopRead(void) /*! Writes data to a file * * @param pSource Pointer to data to be written to file * @param size Size of data (in bytes) to write * @param[out] sizewritten Size of data actually written to the file * @returns ICRESULT Status after the file write **/ ICRESULT icFile::Write(void* pSource, size_t size, size_t* sizewritten) { if (m_pFile && !(m_FileMode&ICFM_ASYNC)) { if (WriteFile(m_pFile, pSource, (DWORD)size, (LPDWORD)sizewritten, NULL)) { m_u64FilePos += *sizewritten; return IC_OK; } } return IC_FAIL_GEN; }// END FUNCTION Write(void* pSource, size_t size, size_t* sizewritten) /*! Writes to a file asynchronously * * @param pSource Pointer to data to be written to file * @param size Size of data (in bytes) to write * @param userPtr Pointer for user to use in callback * @param callback Function pointer for user callback * @returns ICRESULT Status after the file write **/ ICRESULT icFile::WriteAsync(void* pSource, size_t size, void* userPtr, void (*callback)(void*,size_t)) { if (m_pFile && !m_bStreaming) { m_pVoidCallback = callback; m_ptrUser = userPtr; m_bStreaming = true; hEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); if (WriteFileEx(m_pFile, pSource, (DWORD)size, (LPOVERLAPPED)this, AsyncCB)) { FlushFileBuffers(m_pFile); return IC_OK; } else { m_bStreaming = false; DWORD err = GetLastError(); icWarningf("icFile::WriteAsync failed with error: %i",err); } } return IC_FAIL_GEN; }// END FUNCTION WriteAsync(void* pSource, size_t size, // void* userPtr, void (*callback)(void*,size_t)) /*! Get File Size in bytes * * @param size Pointer to store file size * @returns ICRESULT Status after getting size **/ ICRESULT icFile::GetSize(uint64* size) { if (m_pFile) { DWORD high=0; DWORD low = GetFileSize(m_pFile, &high); // check fail condition if (low != INVALID_FILE_SIZE) { *size = (uint64)low | (uint64)high<<32; return IC_OK; } } return IC_FAIL_GEN; }// END FUNCTION GetSize(size_t* size) /*! Get the current file position * * * @param pos Pointer to store file position * @returns ICRESULT Status after getting file position **/ ICRESULT icFile::GetPos(uint64* pos) { if (m_pFile) { *pos = m_u64FilePos; return IC_OK; } return IC_FAIL_GEN; }// END FUNCTION GetPos(size_t* pos) /*! Sets the file pointer * * @param pos Desired file position * @returns ICRESULT Status after changing file position **/ ICRESULT icFile::SetPos(const uint64 pos) { if (m_pFile) { #if 1 LARGE_INTEGER liPos; liPos.QuadPart = pos; if (SetFilePointerEx(m_pFile, liPos, (PLARGE_INTEGER)&m_u64FilePos, FILE_BEGIN)) #else long liPos = (long)pos; if (SetFilePointer(m_pFile, liPos, 0, FILE_BEGIN)) #endif return IC_OK; } ::MessageBoxA(NULL, "Failed to set file position", "Shit Ballz", 0); return IC_FAIL_GEN; }// END FUNCTION SetPos(const uint64 pos) #endif// ifdef WIN32
26.972678
84
0.588533
341750081f42a0714498e4ee2a0c996609a8b1b4
634
cpp
C++
codes/raulcr-p2624-Accepted-s747689.cpp
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
1
2020-03-17T01:44:21.000Z
2020-03-17T01:44:21.000Z
codes/raulcr-p2624-Accepted-s747689.cpp
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
null
null
null
codes/raulcr-p2624-Accepted-s747689.cpp
raulcr98/coj-solutions
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int N, M, T; int main() { cin >> T; while(T--){ cin >> N >> M; vector<int> V; int sum = 0; for(int i = 1 ; i <= M ; i++){ int a; cin >> a; sum += a; V.push_back(a); } sort(V.begin(), V.end()); int sol = 0, i = 0; while(i < M && sol < N){ sol += V[i]; i++; } if(sum >= sol && sol > N) cout << i - 1 << '\n'; else cout << i << '\n'; } return 0; }
17.135135
39
0.29653
3419a5f363a8fffd9b1b22cdb8c06ef6890742f8
31,404
cc
C++
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* * Player - One Hell of a Robot Server * Copyright (C) 2000-2003 * Brian Gerkey * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* * $Id: obot.cc 7278 2009-01-16 22:32:00Z thjc $ * * * Some of this code is borrowed and/or adapted from the 'cerebellum' * module of CARMEN; thanks to the authors of that module. */ /** @ingroup drivers */ /** @{ */ /** @defgroup driver_obot obot * @brief Botrics Obot mobile robot The obot driver controls the Obot robot, made by Botrics. It's a small, very fast robot that can carry a SICK laser (talk to the laser over a normal serial port using the @ref driver_sicklms200 driver). @par Compile-time dependencies - none @par Provides - @ref interface_position2d - @ref interface_power @par Requires - none @par Supported commands - PLAYER_POSITION2D_CMD_VEL - PLAYER_POSITION2D_CMD_CAR @par Supported configuration requests - PLAYER_POSITION2D_REQ_GET_GEOM - PLAYER_POSITION2D_REQ_SET_ODOM - PLAYER_POSITION2D_REQ_RESET_ODOM @par Configuration file options - offset (length tuple) - Default: [0.0 0.0 0.0] - Offset of the robot's center of rotation - size (length tuple) - Default: [0.45 0.45] - Bounding box (length, width) of the robot - port (string) - Default: "/dev/usb/ttyUSB1" - Serial port used to communicate with the robot. - max_speed (length, angle tuple) - Default: [0.5 40.0] - Maximum (translational, rotational) velocities - max_accel (integer) - Default: 5 - Maximum acceleration/deceleration (units?) - motors_swapped (integer) - Default: 0 - If non-zero, then assume that the motors and encoders connections are swapped. - car_angle_deadzone (angle) - Default: 5.0 degrees - Minimum angular error required to induce servoing when in car-like command mode. - car_angle_p (float) - Default: 1.0 - Value to be multiplied by angular error (in rad) to produce angular velocity command (in rad/sec) when in car-like command mode - watchdog_timeout (float, seconds) - Default: 1.0 - How long since receiving the last command before the robot is stopped, for safety. Set to -1.0 for no watchdog (DANGEROUS!). @par Example @verbatim driver ( name "obot" provides ["position2d:0"] ) @endverbatim @author Brian Gerkey */ /** @} */ #include "config.h" #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <termios.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <replace/replace.h> #include <libplayercore/playercore.h> #include "obot_constants.h" static void StopRobot(void* obotdev); class Obot : public ThreadedDriver { private: // this function will be run in a separate thread virtual void Main(); // bookkeeping bool fd_blocking; double px, py, pa; // integrated odometric pose (m,m,rad) int last_ltics, last_rtics; bool odom_initialized; player_devaddr_t position_addr; player_devaddr_t power_addr; double max_xspeed, max_yawspeed; bool motors_swapped; int max_accel; // Minimum angular error required to induce servoing when in car-like // command mode. double car_angle_deadzone; // Value to be multiplied by angular error (in rad) to produce angular // velocity command (in rad/sec) when in car-like command mode double car_angle_p; // How long since receiving the last command before we stop the robot, // for safety. double watchdog_timeout; // Robot geometry (size and rotational offset) player_bbox3d_t robot_size; player_pose3d_t robot_pose; // methods for internal use int WriteBuf(unsigned char* s, size_t len); int ReadBuf(unsigned char* s, size_t len); int BytesToInt32(unsigned char *ptr); void Int32ToBytes(unsigned char* buf, int i); int ValidateChecksum(unsigned char *ptr, size_t len); int GetOdom(int *ltics, int *rtics, int *lvel, int *rvel); void UpdateOdom(int ltics, int rtics); unsigned char ComputeChecksum(unsigned char *ptr, size_t len); int SendCommand(unsigned char cmd, int val1, int val2); int ComputeTickDiff(int from, int to); int ChangeMotorState(int state); int OpenTerm(); int InitRobot(); int GetBatteryVoltage(int* voltage); double angle_diff(double a, double b); player_position2d_cmd_car_t last_car_cmd; int last_final_lvel, last_final_rvel; double last_cmd_time; bool sent_new_command; bool car_command_mode; public: int fd; // device file descriptor const char* serial_port; // name of dev file // public, so that it can be called from pthread cleanup function int SetVelocity(int lvel, int rvel); Obot(ConfigFile* cf, int section); void ProcessCommand(player_position2d_cmd_vel_t * cmd); void ProcessCarCommand(player_position2d_cmd_car_t * cmd); // Process incoming messages from clients int ProcessMessage(QueuePointer & resp_queue, player_msghdr * hdr, void * data); virtual int MainSetup(); virtual void MainQuit(); }; // initialization function Driver* Obot_Init( ConfigFile* cf, int section) { return((Driver*)(new Obot( cf, section))); } // a driver registration function void obot_Register(DriverTable* table) { table->AddDriver("obot", Obot_Init); } Obot::Obot( ConfigFile* cf, int section) : ThreadedDriver(cf,section,true,PLAYER_MSGQUEUE_DEFAULT_MAXLEN) { memset(&this->position_addr,0,sizeof(player_devaddr_t)); memset(&this->power_addr,0,sizeof(player_devaddr_t)); // Do we create a robot position interface? if(cf->ReadDeviceAddr(&(this->position_addr), section, "provides", PLAYER_POSITION2D_CODE, -1, NULL) == 0) { if(this->AddInterface(this->position_addr) != 0) { this->SetError(-1); return; } this->robot_size.sl = cf->ReadTupleLength(section, "size", 0, OBOT_LENGTH); this->robot_size.sw = cf->ReadTupleLength(section, "size", 1, OBOT_WIDTH); this->robot_pose.px = cf->ReadTupleLength(section, "offset", 0, OBOT_POSE_X); this->robot_pose.py = cf->ReadTupleLength(section, "offset", 1, OBOT_POSE_Y); this->robot_pose.pyaw = cf->ReadTupleAngle(section, "offset", 2, OBOT_POSE_A); this->max_xspeed = cf->ReadTupleLength(section, "max_speed", 0, 0.5); this->max_yawspeed = cf->ReadTupleAngle(section, "max_speed", 1, DTOR(40.0)); this->motors_swapped = cf->ReadInt(section, "motors_swapped", 0); this->max_accel = cf->ReadInt(section, "max_accel", 5); this->car_angle_deadzone = cf->ReadAngle(section, "car_angle_deadzone", DTOR(5.0)); this->car_angle_p = cf->ReadFloat(section, "car_angle_p", 1.0); this->watchdog_timeout = cf->ReadFloat(section, "watchdog_timeout", 1.0); } // Do we create a power interface? if(cf->ReadDeviceAddr(&(this->power_addr), section, "provides", PLAYER_POWER_CODE, -1, NULL) == 0) { if(this->AddInterface(this->power_addr) != 0) { this->SetError(-1); return; } } this->fd = -1; this->serial_port = cf->ReadString(section, "port", OBOT_DEFAULT_PORT); } int Obot::InitRobot() { // initialize the robot unsigned char initstr[3]; initstr[0] = OBOT_INIT1; initstr[1] = OBOT_INIT2; initstr[2] = OBOT_INIT3; unsigned char deinitstr[1]; deinitstr[0] = OBOT_DEINIT; if(tcflush(this->fd, TCIOFLUSH) < 0 ) { PLAYER_ERROR1("tcflush() failed: %s", strerror(errno)); close(this->fd); this->fd = -1; return(-1); } if(WriteBuf(initstr,sizeof(initstr)) < 0) { PLAYER_WARN("failed to initialize robot; i'll try to de-initializate it"); if(WriteBuf(deinitstr,sizeof(deinitstr)) < 0) { PLAYER_ERROR("failed on write of de-initialization string"); return(-1); } if(WriteBuf(initstr,sizeof(initstr)) < 0) { PLAYER_ERROR("failed on 2nd write of initialization string; giving up"); return(-1); } } return(0); } int Obot::OpenTerm() { struct termios term; // open it. non-blocking at first, in case there's no robot if((this->fd = open(serial_port, O_RDWR | O_SYNC | O_NONBLOCK, S_IRUSR | S_IWUSR )) < 0 ) { PLAYER_ERROR1("open() failed: %s", strerror(errno)); return(-1); } if(tcgetattr(this->fd, &term) < 0 ) { PLAYER_ERROR1("tcgetattr() failed: %s", strerror(errno)); close(this->fd); this->fd = -1; return(-1); } cfmakeraw(&term); cfsetispeed(&term, B57600); cfsetospeed(&term, B57600); if(tcsetattr(this->fd, TCSAFLUSH, &term) < 0 ) { PLAYER_ERROR1("tcsetattr() failed: %s", strerror(errno)); close(this->fd); this->fd = -1; return(-1); } fd_blocking = false; return(0); } int Obot::MainSetup() { int flags; int ltics,rtics,lvel,rvel; this->px = this->py = this->pa = 0.0; this->odom_initialized = false; this->last_final_rvel = this->last_final_lvel = 0; this->last_cmd_time = -1.0; this->sent_new_command = false; this->car_command_mode = false; printf("Botrics Obot connection initializing (%s)...", serial_port); fflush(stdout); if(OpenTerm() < 0) { PLAYER_ERROR("failed to initialize robot"); return(-1); } if(InitRobot() < 0) { PLAYER_ERROR("failed to initialize robot"); close(this->fd); this->fd = -1; return(-1); } /* try to get current odometry, just to make sure we actually have a robot */ if(GetOdom(&ltics,&rtics,&lvel,&rvel) < 0) { PLAYER_ERROR("failed to get odometry"); close(this->fd); this->fd = -1; return(-1); } UpdateOdom(ltics,rtics); /* ok, we got data, so now set NONBLOCK, and continue */ if((flags = fcntl(this->fd, F_GETFL)) < 0) { PLAYER_ERROR1("fcntl() failed: %s", strerror(errno)); close(this->fd); this->fd = -1; return(-1); } if(fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK) < 0) { PLAYER_ERROR1("fcntl() failed: %s", strerror(errno)); close(this->fd); this->fd = -1; return(-1); } fd_blocking = true; puts("Done."); // TODO: what are reasoanable numbers here? if(SendCommand(OBOT_SET_ACCELERATIONS,this->max_accel,this->max_accel) < 0) { PLAYER_ERROR("failed to set accelerations on setup"); close(this->fd); this->fd = -1; return(-1); } return(0); } void Obot::MainQuit() { unsigned char deinitstr[1]; usleep(OBOT_DELAY_US); deinitstr[0] = OBOT_DEINIT; if(WriteBuf(deinitstr,sizeof(deinitstr)) < 0) PLAYER_ERROR("failed to deinitialize connection to robot"); if(close(this->fd)) PLAYER_ERROR1("close() failed:%s",strerror(errno)); this->fd = -1; puts("Botrics Obot has been shutdown"); } void Obot::Main() { player_position2d_data_t data; player_power_data_t charge_data; double lvel_mps, rvel_mps; int lvel, rvel; int ltics, rtics; double last_publish_time = 0.0; double t; bool stopped=false; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL); // push a pthread cleanup function that stops the robot pthread_cleanup_push(StopRobot,this); for(;;) { pthread_testcancel(); this->sent_new_command = false; ProcessMessages(); if(!this->sent_new_command) { // Have we received a command lately? GlobalTime->GetTimeDouble(&t); if((this->last_cmd_time > 0.0) && (this->watchdog_timeout > 0.0) && ((t - this->last_cmd_time) >= this->watchdog_timeout)) { if(!stopped) { PLAYER_WARN("Watchdog timer stopping robot"); stopped = true; } if(this->SetVelocity(0,0) < 0) PLAYER_ERROR("failed to set velocity"); } else { stopped = false; // Which mode are we in? if(this->car_command_mode) { // Car-like command mode. Re-compute angular vel based on target // heading this->ProcessCarCommand(&this->last_car_cmd); } else { // Direct velocity command mode. Re-send last set of velocities. if(this->SetVelocity(this->last_final_lvel, this->last_final_rvel) < 0) PLAYER_ERROR("failed to set velocity"); } } } // Update and publish odometry info if(this->GetOdom(&ltics,&rtics,&lvel,&rvel) < 0) { PLAYER_ERROR("failed to get odometry"); //pthread_exit(NULL); } else this->UpdateOdom(ltics,rtics); // Update and publish power info int volt; if(GetBatteryVoltage(&volt) < 0) PLAYER_WARN("failed to get voltage"); GlobalTime->GetTimeDouble(&t); if((t - last_publish_time) > OBOT_PUBLISH_INTERVAL) { data.pos.px = this->px; data.pos.py = this->py; data.pos.pa = this->pa; data.vel.py = 0; lvel_mps = lvel * OBOT_MPS_PER_TICK; rvel_mps = rvel * OBOT_MPS_PER_TICK; data.vel.px = (lvel_mps + rvel_mps) / 2.0; data.vel.pa = (rvel_mps-lvel_mps) / OBOT_AXLE_LENGTH; data.stall = 0; //printf("publishing: %.3f %.3f %.3f\n", //data.pos.px, //data.pos.py, //RTOD(data.pos.pa)); this->Publish(this->position_addr, PLAYER_MSGTYPE_DATA, PLAYER_POSITION2D_DATA_STATE, (void*)&data,sizeof(data),NULL); charge_data.valid = PLAYER_POWER_MASK_VOLTS | PLAYER_POWER_MASK_PERCENT; charge_data.volts = ((float)volt) / 1e1; charge_data.percent = 1e2 * (charge_data.volts / OBOT_NOMINAL_VOLTAGE); this->Publish(this->power_addr, PLAYER_MSGTYPE_DATA, PLAYER_POWER_DATA_STATE, (void*)&charge_data, sizeof(player_power_data_t), NULL); last_publish_time = t; } //usleep(OBOT_DELAY_US); } pthread_cleanup_pop(0); } // Process car-like command, which sets an angular position target and // translational velocity target. The basic idea is to compute angular // velocity so as to servo (with P-control) to target angle. Then pass the // two velocities to ProcessCommand() for thresholding and unit conversion. void Obot::ProcessCarCommand(player_position2d_cmd_car_t * cmd) { // Cache this command for later reuse this->last_car_cmd = *cmd; // Build up a cmd_vel structure to pass to ProcessCommand() player_position2d_cmd_vel_t vel_cmd; memset(&vel_cmd,0,sizeof(vel_cmd)); // Pass through trans vel unmodified vel_cmd.vel.px = cmd->velocity; // Compute rot vel double da = this->angle_diff(cmd->angle, this->pa); if(fabs(da) < DTOR(this->car_angle_deadzone)) vel_cmd.vel.pa = 0.0; else vel_cmd.vel.pa = this->car_angle_p * da; this->ProcessCommand(&vel_cmd); } void Obot::ProcessCommand(player_position2d_cmd_vel_t * cmd) { double rotational_term, command_lvel, command_rvel; int final_lvel, final_rvel; double xspeed, yawspeed; xspeed = cmd->vel.px; yawspeed = cmd->vel.pa; // Clamp velocities according to given maxima // TODO: test this to see if it does the right thing. We could clamp // individual wheel velocities instead. if(fabs(xspeed) > this->max_xspeed) { if(xspeed > 0) xspeed = this->max_xspeed; else xspeed = -this->max_xspeed; } if(fabs(yawspeed) > this->max_yawspeed) { if(yawspeed > 0) yawspeed = this->max_yawspeed; else yawspeed = -this->max_yawspeed; } // convert (tv,rv) to (lv,rv) and send to robot rotational_term = yawspeed * OBOT_AXLE_LENGTH / 2.0; command_rvel = xspeed + rotational_term; command_lvel = xspeed - rotational_term; // sanity check on per-wheel speeds if(fabs(command_lvel) > OBOT_MAX_WHEELSPEED) { if(command_lvel > 0) { command_lvel = OBOT_MAX_WHEELSPEED; command_rvel *= OBOT_MAX_WHEELSPEED/command_lvel; } else { command_lvel = - OBOT_MAX_WHEELSPEED; command_rvel *= -OBOT_MAX_WHEELSPEED/command_lvel; } } if(fabs(command_rvel) > OBOT_MAX_WHEELSPEED) { if(command_rvel > 0) { command_rvel = OBOT_MAX_WHEELSPEED; command_lvel *= OBOT_MAX_WHEELSPEED/command_rvel; } else { command_rvel = - OBOT_MAX_WHEELSPEED; command_lvel *= -OBOT_MAX_WHEELSPEED/command_rvel; } } final_lvel = (int)rint(command_lvel / OBOT_MPS_PER_TICK); final_rvel = (int)rint(command_rvel / OBOT_MPS_PER_TICK); // TODO: do this min threshold smarter, to preserve desired travel // direction /* to account for our bad low-level PID motor controller */ if(abs(final_rvel) > 0 && abs(final_rvel) < OBOT_MIN_WHEELSPEED_TICKS) { if(final_rvel > 0) final_rvel = OBOT_MIN_WHEELSPEED_TICKS; else final_rvel = -OBOT_MIN_WHEELSPEED_TICKS; } if(abs(final_lvel) > 0 && abs(final_lvel) < OBOT_MIN_WHEELSPEED_TICKS) { if(final_lvel > 0) final_lvel = OBOT_MIN_WHEELSPEED_TICKS; else final_lvel = -OBOT_MIN_WHEELSPEED_TICKS; } // Record that we got a command at this time GlobalTime->GetTimeDouble(&(this->last_cmd_time)); if((final_lvel != last_final_lvel) || (final_rvel != last_final_rvel)) { if(SetVelocity(final_lvel,final_rvel) < 0) { PLAYER_ERROR("failed to set velocity"); pthread_exit(NULL); } last_final_lvel = final_lvel; last_final_rvel = final_rvel; } } //////////////////////////////////////////////////////////////////////////////// // Process an incoming message int Obot::ProcessMessage(QueuePointer & resp_queue, player_msghdr * hdr, void * data) { if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD, PLAYER_POSITION2D_CMD_VEL, this->position_addr)) { // Only take the first new command (should probably take the last, // but...) if(!this->sent_new_command) { assert(hdr->size == sizeof(player_position2d_cmd_vel_t)); this->ProcessCommand((player_position2d_cmd_vel_t*)data); this->sent_new_command = true; this->car_command_mode = false; } return(0); } else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD, PLAYER_POSITION2D_CMD_CAR, this->position_addr)) { // Only take the first new command (should probably take the last, // but...) if(!this->sent_new_command) { assert(hdr->size == sizeof(player_position2d_cmd_vel_t)); this->ProcessCarCommand((player_position2d_cmd_car_t*)data); this->sent_new_command = true; this->car_command_mode = true; } return(0); } else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_REQ, PLAYER_POSITION2D_REQ_GET_GEOM, this->position_addr)) { player_position2d_geom_t geom; geom.pose = this->robot_pose; geom.size = this->robot_size; this->Publish(this->position_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_GET_GEOM, (void*)&geom, sizeof(geom), NULL); return(0); } else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ, PLAYER_POSITION2D_REQ_MOTOR_POWER, this->position_addr)) { /* motor state change request * 1 = enable motors * 0 = disable motors (default) */ if(hdr->size != sizeof(player_position2d_power_config_t)) { PLAYER_WARN("Arg to motor state change request wrong size; ignoring"); return(-1); } player_position2d_power_config_t* power_config = (player_position2d_power_config_t*)data; this->ChangeMotorState(power_config->state); this->Publish(this->position_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_MOTOR_POWER); return(0); } else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ, PLAYER_POSITION2D_REQ_SET_ODOM, this->position_addr)) { if(hdr->size != sizeof(player_position2d_set_odom_req_t)) { PLAYER_WARN("Arg to odometry set requests wrong size; ignoring"); return(-1); } player_position2d_set_odom_req_t* set_odom_req = (player_position2d_set_odom_req_t*)data; // Just overwrite our current odometric pose. this->px = set_odom_req->pose.px; this->py = set_odom_req->pose.py; this->pa = set_odom_req->pose.pa; this->Publish(this->position_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_SET_ODOM); return(0); } else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ, PLAYER_POSITION2D_REQ_RESET_ODOM, this->position_addr)) { // Just overwrite our current odometric pose. this->px = 0.0; this->py = 0.0; this->pa = 0.0; this->Publish(this->position_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_RESET_ODOM); return(0); } else return -1; } int Obot::ReadBuf(unsigned char* s, size_t len) { int thisnumread; size_t numread = 0; int loop; int maxloops=10; loop=0; while(numread < len) { //printf("loop %d of %d\n", loop,maxloops); // apparently the underlying PIC gets overwhelmed if we read too fast // wait...how can that be? if((thisnumread = read(this->fd,s+numread,len-numread)) < 0) { if(!this->fd_blocking && errno == EAGAIN && ++loop < maxloops) { usleep(OBOT_DELAY_US); continue; } PLAYER_ERROR1("read() failed: %s", strerror(errno)); return(-1); } if(thisnumread == 0) PLAYER_WARN("short read"); numread += thisnumread; } /* printf("read: "); for(size_t i=0;i<numread;i++) printf("%d ", s[i]); puts(""); */ return(0); } int Obot::WriteBuf(unsigned char* s, size_t len) { size_t numwritten; int thisnumwritten; unsigned char ack[1]; /* static double last = 0.0; double t; GlobalTime->GetTimeDouble(&t); printf("WriteBuf: %d bytes (time since last: %f)\n", len, t-last); last=t; */ for(;;) { numwritten=0; while(numwritten < len) { if((thisnumwritten = write(this->fd,s+numwritten,len-numwritten)) < 0) { if(!this->fd_blocking && errno == EAGAIN) { usleep(OBOT_DELAY_US); continue; } PLAYER_ERROR1("write() failed: %s", strerror(errno)); return(-1); } numwritten += thisnumwritten; } // get acknowledgement if(ReadBuf(ack,1) < 0) { PLAYER_ERROR("failed to get acknowledgement"); return(-1); } // TODO: re-init robot on NACK, to deal with underlying cerebellum reset // problem switch(ack[0]) { case OBOT_ACK: usleep(OBOT_DELAY_US); return(0); case OBOT_NACK: PLAYER_WARN("got NACK; reinitializing connection"); usleep(OBOT_DELAY_US); if(close(this->fd) < 0) PLAYER_WARN1("close failed: %s", strerror(errno)); if(OpenTerm() < 0) { PLAYER_ERROR("failed to re-open connection"); return(-1); } if(InitRobot() < 0) { PLAYER_ERROR("failed to reinitialize"); return(-1); } else { usleep(OBOT_DELAY_US); return(0); } break; default: PLAYER_WARN1("got unknown value for acknowledgement: %d",ack[0]); usleep(OBOT_DELAY_US); return(-1); } } } int Obot::BytesToInt32(unsigned char *ptr) { unsigned char char0,char1,char2,char3; int data = 0; char0 = ptr[0]; char1 = ptr[1]; char2 = ptr[2]; char3 = ptr[3]; data |= ((int)char0) & 0x000000FF; data |= (((int)char1) << 8) & 0x0000FF00; data |= (((int)char2) << 16) & 0x00FF0000; data |= (((int)char3) << 24) & 0xFF000000; return data; } int Obot::GetBatteryVoltage(int* voltage) { unsigned char buf[5]; buf[0] = OBOT_GET_VOLTAGE; if(WriteBuf(buf,1) < 0) { PLAYER_ERROR("failed to send battery voltage command"); return(-1); } if(ReadBuf(buf,5) < 0) { PLAYER_ERROR("failed to read battery voltage"); return(-1); } if(ValidateChecksum(buf,5) < 0) { PLAYER_ERROR("checksum failed on battery voltage"); return(-1); } *voltage = BytesToInt32(buf); return(0); } void Obot::Int32ToBytes(unsigned char* buf, int i) { buf[0] = (i >> 0) & 0xFF; buf[1] = (i >> 8) & 0xFF; buf[2] = (i >> 16) & 0xFF; buf[3] = (i >> 24) & 0xFF; } int Obot::GetOdom(int *ltics, int *rtics, int *lvel, int *rvel) { unsigned char buf[20]; int index; buf[0] = OBOT_GET_ODOM; if(WriteBuf(buf,1) < 0) { PLAYER_ERROR("failed to send command to retrieve odometry"); return(-1); } //usleep(OBOT_DELAY_US); // read 4 int32's, 1 error byte, and 1 checksum if(ReadBuf(buf, 18) < 0) { PLAYER_ERROR("failed to read odometry"); return(-1); } if(ValidateChecksum(buf, 18) < 0) { PLAYER_ERROR("checksum failed on odometry packet"); return(-1); } if(buf[16] == 1) { PLAYER_ERROR("Cerebellum error with encoder board"); return(-1); } index = 0; *ltics = BytesToInt32(buf+index); index += 4; *rtics = BytesToInt32(buf+index); index += 4; *rvel = BytesToInt32(buf+index); index += 4; *lvel = BytesToInt32(buf+index); //printf("ltics: %d rtics: %d\n", *ltics, *rtics); //puts("got good odom packet"); return(0); } int Obot::ComputeTickDiff(int from, int to) { int diff1, diff2; // find difference in two directions and pick shortest if(to > from) { diff1 = to - from; diff2 = (-OBOT_MAX_TICS - from) + (to - OBOT_MAX_TICS); } else { diff1 = to - from; diff2 = (from - OBOT_MAX_TICS) + (-OBOT_MAX_TICS - to); } if(abs(diff1) < abs(diff2)) return(diff1); else return(diff2); } void Obot::UpdateOdom(int ltics, int rtics) { int ltics_delta, rtics_delta; double l_delta, r_delta, a_delta, d_delta; int max_tics; static struct timeval lasttime; struct timeval currtime; double timediff; if(this->motors_swapped) { int tmp = ltics; ltics = rtics; rtics = tmp; } if(!this->odom_initialized) { this->last_ltics = ltics; this->last_rtics = rtics; gettimeofday(&lasttime,NULL); this->odom_initialized = true; return; } // MAJOR HACK! // The problem comes from one or the other encoder returning 0 ticks (always // the left, I think), we'll just throw out those readings. Shouldn't have // too much impact. if(!ltics || !rtics) { PLAYER_WARN("Invalid odometry reading (zeros); ignoring"); return; } //ltics_delta = ComputeTickDiff(last_ltics,ltics); //rtics_delta = ComputeTickDiff(last_rtics,rtics); ltics_delta = ltics - this->last_ltics; rtics_delta = rtics - this->last_rtics; // mysterious rollover code borrowed from CARMEN /* if(ltics_delta > SHRT_MAX/2) ltics_delta += SHRT_MIN; if(ltics_delta < -SHRT_MIN/2) ltics_delta -= SHRT_MIN; if(rtics_delta > SHRT_MAX/2) rtics_delta += SHRT_MIN; if(rtics_delta < -SHRT_MIN/2) rtics_delta -= SHRT_MIN; */ gettimeofday(&currtime,NULL); timediff = (currtime.tv_sec + currtime.tv_usec/1e6)- (lasttime.tv_sec + lasttime.tv_usec/1e6); max_tics = (int)rint(OBOT_MAX_WHEELSPEED / OBOT_M_PER_TICK / timediff); lasttime = currtime; //printf("ltics: %d\trtics: %d\n", ltics,rtics); //printf("ldelt: %d\trdelt: %d\n", ltics_delta, rtics_delta); //printf("maxtics: %d\n", max_tics); if(abs(ltics_delta) > max_tics || abs(rtics_delta) > max_tics) { PLAYER_WARN("Invalid odometry change (too big); ignoring"); return; } l_delta = ltics_delta * OBOT_M_PER_TICK; r_delta = rtics_delta * OBOT_M_PER_TICK; //printf("Left speed: %f\n", l_delta / timediff); //printf("Right speed: %f\n", r_delta / timediff); a_delta = (r_delta - l_delta) / OBOT_AXLE_LENGTH; d_delta = (l_delta + r_delta) / 2.0; this->px += d_delta * cos(this->pa); this->py += d_delta * sin(this->pa); this->pa += a_delta; this->pa = NORMALIZE(this->pa); //printf("obot: pose: %f,%f,%f\n", this->px,this->py, RTOD(this->pa)); this->last_ltics = ltics; this->last_rtics = rtics; } // Validate XOR checksum int Obot::ValidateChecksum(unsigned char *ptr, size_t len) { size_t i; unsigned char checksum = 0; for(i = 0; i < len-1; i++) checksum ^= ptr[i]; if(checksum == ptr[len-1]) return(0); else return(-1); } // Compute XOR checksum unsigned char Obot::ComputeChecksum(unsigned char *ptr, size_t len) { size_t i; unsigned char chksum = 0; for(i = 0; i < len; i++) chksum ^= ptr[i]; return(chksum); } int Obot::SendCommand(unsigned char cmd, int val1, int val2) { unsigned char buf[10]; int i; //printf("SendCommand: %d %d %d\n", cmd, val1, val2); i=0; buf[i] = cmd; i+=1; Int32ToBytes(buf+i,val1); i+=4; Int32ToBytes(buf+i,val2); i+=4; buf[i] = ComputeChecksum(buf,i); if(WriteBuf(buf,10) < 0) { PLAYER_ERROR("failed to send command"); return(-1); } return(0); } int Obot::SetVelocity(int lvel, int rvel) { int retval; //printf("SetVelocity: %d %d\n", lvel, rvel); if(!this->motors_swapped) retval = SendCommand(OBOT_SET_VELOCITIES,lvel,rvel); else retval = SendCommand(OBOT_SET_VELOCITIES,rvel,lvel); if(retval < 0) { PLAYER_ERROR("failed to set velocities"); return(-1); } return(0); } int Obot::ChangeMotorState(int state) { unsigned char buf[1]; if(state) buf[0] = OBOT_ENABLE_VEL_CONTROL; else buf[0] = OBOT_DISABLE_VEL_CONTROL; return(WriteBuf(buf,sizeof(buf))); } static void StopRobot(void* obotdev) { Obot* td = (Obot*)obotdev; tcflush(td->fd,TCIOFLUSH); if(td->SetVelocity(0,0) < 0) PLAYER_ERROR("failed to stop robot on thread exit"); } // computes the signed minimum difference between the two angles. double Obot::angle_diff(double a, double b) { double d1, d2; a = NORMALIZE(a); b = NORMALIZE(b); d1 = a-b; d2 = 2*M_PI - fabs(d1); if(d1 > 0) d2 *= -1.0; if(fabs(d1) < fabs(d2)) return(d1); else return(d2); }
25.42834
91
0.629156
341f5f51dd2e5f71923d964fb9924d9f9a11bc08
18,473
cpp
C++
src/BCRext/BwtIndex.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
53
2015-02-05T02:26:15.000Z
2022-01-13T05:37:06.000Z
src/BCRext/BwtIndex.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
9
2015-09-03T23:42:14.000Z
2021-10-15T15:25:49.000Z
src/BCRext/BwtIndex.cpp
ndaniel/BEETL
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
[ "BSD-2-Clause" ]
23
2015-01-08T13:43:07.000Z
2021-05-19T17:35:42.000Z
/** ** Copyright (c) 2011-2014 Illumina, Inc. ** ** This file is part of the BEETL software package, ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #include "BwtIndex.hh" #include "BwtReader.hh" #include "libzoo/util/Logger.hh" #include <algorithm> #include <unistd.h> #include <sys/types.h> #ifndef DONT_USE_MMAP # include <fcntl.h> # include <sys/mman.h> # include <sys/stat.h> # include <sys/types.h> #endif using namespace std; template< class T > BwtReaderIndex<T>::BwtReaderIndex( const string &filename, const string &optionalSharedMemoryPath ): T( filename ), indexFilename_( filename + ".idx" ), // isNextIndex_( false ), pIndexFile_( NULL ) { // current_.clear(); initIndex( optionalSharedMemoryPath ); } template< class T > void BwtReaderIndex<T>::rewindFile( void ) { // rewind file and set all vars as per constructor // current_.clear(); indexNext_ = 0; // initIndex(); T::rewindFile(); } // ~rewindFile template< class T > LetterNumber BwtReaderIndex<T>::readAndCount( LetterCount &c, const LetterNumber numChars ) { #ifdef DEBUG_RAC std::cout << "BR RLI readAndCount " << numChars << " chars " << endl; std::cout << "Before: " << currentPos_ << " " << ftell( T::pFile_ ) << " "; std::cout << c << endl;; #endif LetterNumber charsLeft( numChars ); uint32_t indexLast; #ifdef DEBUG_RAC if ( indexNext_ != indexSize_ ) assert( currentPos_ <= indexPosBwt_[indexNext_] ); #endif // gotcha: numChars can be set to maxLetterNumber so no expressions should // add to it - wraparound issues! // if indexLast==indexPosBwtSize we know we have gone past last index point // or that none are present at all if ( ( indexNext_ != indexSize_ ) && ( numChars > ( indexPosBwt_[indexNext_] - T::currentPos_ ) ) ) { // count interval spans at least one index point // how many index points does the count interval span? indexLast = indexNext_; while ( ( indexLast != indexSize_ ) && ( numChars > ( indexPosBwt_[indexLast] - T::currentPos_ ) ) ) { indexLast++; } indexLast--; if ( indexNext_ <= indexLast ) { // more than one index point in count interval - can use index if ( ! ( T::currentPos_ == 0 && charsLeft >= indexPosBwt_[indexNext_] ) ) charsLeft -= T::readAndCount( c, indexPosBwt_[indexNext_] - T::currentPos_ ); else { charsLeft -= indexPosBwt_[0]; c += indexCount_[0]; if ( indexNext_ == indexLast ) T::seek( indexPosFile_[0], indexPosBwt_[0] ); } // assert(T::currentPos_==indexNext_); if ( indexNext_ != indexLast ) { charsLeft -= ( indexPosBwt_[indexLast] - indexPosBwt_[indexNext_] ); // update counts and also indexNext_ while ( ++indexNext_ <= indexLast ) { c += indexCount_[indexNext_]; #ifdef DEBUG_RAC_VERBOSE std::cout << indexNext_ << " " << indexPosBwt_[indexNext_] << " " << indexPosFile_[indexNext_] << " " << indexCount_[indexNext_] << endl; #endif } // // skip to last index point and reset buffers T::seek( indexPosFile_[indexLast], indexPosBwt_[indexLast] ); } else { assert( T::currentPos_ == indexPosBwt_[indexLast] ); ++indexNext_; } /* T::runLength_ = 0; T::pBuf_ = T::buf_ + ReadBufferSize; T::pBufMax_ = T::buf_ + ReadBufferSize; */ } // if more than one index point // if we're in this clause we've gone past at least one index indexLast++; assert( indexLast <= indexSize_ ); } #ifdef DEBUG_RAC std::cout << "After (RLI) skip: " << T::currentPos_ << " " << ftell( T::pFile_ ) << " " << c << endl; #endif // now read as normal until done charsLeft -= T::readAndCount( c, charsLeft ); // assert(T::currentPos_==desiredPos); #ifdef DEBUG_RAC std::cout << "After (RLI) final read: " << T::currentPos_ << " " << ftell( T::pFile_ ) << " " << c << endl; #endif return ( numChars - charsLeft ); } template< class T > void BwtReaderIndex<T>::initIndex( const string &optionalSharedMemoryPath ) { indexNext_ = 0; bool useSharedMemory = !optionalSharedMemoryPath.empty(); string shmFilename1, shmFilename2, shmFilename3; if ( useSharedMemory ) { string filenameWithoutSlash = T::filename_; std::replace( filenameWithoutSlash.begin(), filenameWithoutSlash.end(), '/', '_' ); shmFilename1 = optionalSharedMemoryPath + "/BeetlIndexPosFile_" + filenameWithoutSlash; shmFilename2 = optionalSharedMemoryPath + "/BeetlIndexCount_" + filenameWithoutSlash; shmFilename3 = optionalSharedMemoryPath + "/BeetlIndexPosBwt_" + filenameWithoutSlash; if ( readWriteCheck( shmFilename1.c_str(), false, false ) ) { // Load vectors from shared memory { cerr << "Info: Using mmap'ed index " << shmFilename1 << endl; int fd = open( shmFilename1.c_str(), O_RDONLY ); assert( fd >= 0 ); off_t fileSize = lseek( fd, 0, SEEK_END ); lseek( fd, 0, SEEK_SET ); char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 ); if ( mmappedFile == ( void * ) - 1 ) { perror( "Error: Map failed" ); assert( false ); } indexSize_ = *reinterpret_cast<uint32_t *>( mmappedFile ); indexPosFile_ = reinterpret_cast<LetterNumber *>( mmappedFile + sizeof( indexSize_ ) ); close( fd ); } { int fd = open( shmFilename2.c_str(), O_RDONLY ); assert( fd >= 0 ); off_t fileSize = lseek( fd, 0, SEEK_END ); lseek( fd, 0, SEEK_SET ); char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 ); if ( mmappedFile == ( void * ) - 1 ) { perror( "Error: Map failed" ); assert( false ); } assert( indexSize_ == *reinterpret_cast<uint32_t *>( mmappedFile ) ); indexCount_ = reinterpret_cast<LETTER_COUNT_CLASS *>( mmappedFile + sizeof( indexSize_ ) ); close( fd ); } { int fd = open( shmFilename3.c_str(), O_RDONLY ); assert( fd >= 0 ); off_t fileSize = lseek( fd, 0, SEEK_END ); lseek( fd, 0, SEEK_SET ); char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 ); if ( mmappedFile == ( void * ) - 1 ) { perror( "Error: Map failed" ); assert( false ); } assert( indexSize_ == *reinterpret_cast<uint32_t *>( mmappedFile ) ); indexPosBwt_ = reinterpret_cast<LetterNumber *>( mmappedFile + sizeof( indexSize_ ) ); close( fd ); } return; } } LetterNumber currentPosBwt( 0 ); uint8_t unusedAlphabetEntries( 0 ); if ( pIndexFile_ != NULL ) fclose( pIndexFile_ ); pIndexFile_ = fopen( indexFilename_.c_str(), "r" ); if ( pIndexFile_ == NULL ) { // Logger::error() << "Error opening index file " << indexFilename_; // exit( -1 ); } else { // read file header bool isIndexV2 = false; uint8_t sizeOfAlphabet = 0; uint8_t sizeOfLetterNumber = 0; uint16_t sizeOfLetterCountCompact = 0; vector<char> buf( indexV1Header.size() ); fread( buf.data(), indexV1Header.size(), 1, pIndexFile_ ); if ( equal( buf.begin(), buf.end(), indexV1Header.begin() ) ) { // index v1 detected fread( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile_ ); fread( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile_ ); fread( &sizeOfLetterCountCompact, sizeof( uint16_t ), 1, pIndexFile_ ); } else if ( equal( buf.begin(), buf.end(), indexV2Header.begin() ) ) { // index v2 detected isIndexV2 = true; fread( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile_ ); fread( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile_ ); sizeOfLetterCountCompact = sizeof( LetterCountCompact ); // unused in index v2 } else { // default value from previous header-less format sizeOfAlphabet = 7; sizeOfLetterNumber = 8; sizeOfLetterCountCompact = 4*sizeOfAlphabet; rewind( pIndexFile_ ); } if ( sizeOfAlphabet > alphabetSize ) { Logger::error() << "WARNING: Index file " << indexFilename_ << " was built with alphabetSize == " << (int)sizeOfAlphabet << " whereas the current tools are using alphabetSize == " << alphabetSize << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl; unusedAlphabetEntries = sizeOfAlphabet - alphabetSize; } else if ( sizeOfAlphabet < alphabetSize ) { Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with alphabetSize == " << (int)sizeOfAlphabet << " whereas the current tools are using alphabetSize == " << alphabetSize << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl; exit( -1 ); } if ( sizeOfLetterNumber != sizeof( LetterNumber ) ) { Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with sizeof(LetterNumber) == " << (int)sizeOfLetterNumber << " whereas the current tools are using sizeof(LetterNumber) == " << sizeof( LetterNumber ) << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl; exit( -1 ); } if ( sizeOfLetterCountCompact != sizeof( LetterCountCompact ) + 4 * unusedAlphabetEntries ) // allow 32 bits per unused entry to be automatically ignored { Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with sizeof(LetterCountCompact) == " << sizeOfLetterCountCompact << " whereas the current tools are using sizeof(LetterCountCompact) == " << sizeof( LetterCountCompact ) << " + " << unusedAlphabetEntries << "unused alphabet entries.\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl; exit( -1 ); } indexPosFile0_.push_back( 0 ); while ( fread( &indexPosFile0_.back(), sizeof( LetterNumber ), 1, pIndexFile_ ) == 1 ) { indexCount0_.push_back( LETTER_COUNT_CLASS() ); if (!isIndexV2) { // In Index v1, counts were always stored using compact 32 bits values, which now need to be scaled to LETTER_COUNT_CLASS for (int i=0; i<alphabetSize; ++i) { assert ( fread( &indexCount0_.back().count_[i], sizeof( uint32_t ), 1, pIndexFile_ ) == 1 ); } uint32_t unusedEntry; for (int i=0; i<unusedAlphabetEntries; ++i) { assert ( fread( &unusedEntry, sizeof( uint32_t ), 1, pIndexFile_ ) == 1 ); } } else { for (int i=0; i<alphabetSize; ++i) { int byteCount; assert ( fread( &byteCount, 1, 1, pIndexFile_ ) == 1 ); if (byteCount) { #ifdef USE_COMPACT_STRUCTURES if ( byteCount > sizeof(LetterNumberCompact) ) { Logger::error() << "ERROR: Index file " << indexFilename_ << " contains large values. BEETL needs to be built without USE_COMPACT_STRUCTURES in BwtIndex.hh." << endl; exit( -1 ); } #endif assert ( fread( &indexCount0_.back().count_[i], byteCount, 1, pIndexFile_ ) == 1 ); } } } for ( int i( 0 ); i < alphabetSize; i++ ) currentPosBwt += indexCount0_.back().count_[i]; indexPosBwt0_.push_back( currentPosBwt ); #ifdef DEBUG_RAC_VERBOSE cout << indexPosBwt0_.back() << " " << indexPosFile0_.back() << " " << indexCount0_.back() << endl; #endif // skip unused alphabet entries, and check that they were indeed useless for (int i=0; i<unusedAlphabetEntries; ++i) { uint32_t unusedEntry; assert( fread( &unusedEntry, sizeof( uint32_t ), 1, pIndexFile_ ) == 1 ); assert( unusedEntry == 0 && "Error: Trying to ignore an index entry, which contains a non-zero value" ); } indexPosFile0_.push_back( 0 ); } // ~while indexPosFile0_.pop_back(); fclose( pIndexFile_ ); pIndexFile_ = NULL; } // ~if indexSize_ = indexPosBwt0_.size(); assert( indexSize_ == indexPosFile0_.size() ); assert( indexSize_ == indexCount0_.size() ); // rewindFile(); indexPosBwt_ = indexPosBwt0_.data(); indexPosFile_ = indexPosFile0_.data(); indexCount_ = indexCount0_.data(); // Save vectors to shared memory if ( useSharedMemory && !indexPosBwt0_.empty() ) { { ofstream os( shmFilename1 ); if ( !os.good() ) { cerr << "Error creating " << shmFilename1 << endl; exit( -1 ); } os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) ); os.write( reinterpret_cast<const char *>( indexPosFile0_.data() ), indexSize_ * sizeof( indexPosFile0_[0] ) ); } { ofstream os( shmFilename2 ); os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) ); os.write( reinterpret_cast<const char *>( indexCount0_.data() ), indexSize_ * sizeof( indexCount0_[0] ) ); } { ofstream os( shmFilename3 ); os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) ); os.write( reinterpret_cast<const char *>( indexPosBwt0_.data() ), indexSize_ * sizeof( indexPosBwt0_[0] ) ); } } } // ~initIndex // Index creation void buildIndex( BwtReaderBase *reader0, FILE *pIndexFile, const int indexBinSize ) { BwtReaderRunLengthBase *reader = dynamic_cast< BwtReaderRunLengthBase* >( reader0 ); const int runsPerChunk( indexBinSize ); int runsThisChunk( 0 ); LetterCount countsThisChunk; LetterNumber runsSoFar( 0 ), chunksSoFar( 0 ); bool lastRun = false; if (reader == NULL) { Logger::out() << "Warning: cannot index file " << reader0->filename_ << endl; return; } reader->currentPos_ = 0; // Write file header assert( fwrite( indexV2Header.data(), indexV2Header.size(), 1, pIndexFile ) == 1 ); uint8_t sizeOfAlphabet = alphabetSize; uint8_t sizeOfLetterNumber = sizeof( LetterNumber ); fwrite( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile ); fwrite( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile ); while ( !lastRun ) { lastRun = !reader->getRun(); if (!lastRun) { runsSoFar++; runsThisChunk++; countsThisChunk.count_[whichPile[reader->lastChar_]] += reader->runLength_; assert( countsThisChunk.count_[whichPile[reader->lastChar_]] >= reader->runLength_ && "Error: Overflow in buildIndex" ); reader->currentPos_ += reader->runLength_; } if ( runsThisChunk == runsPerChunk || lastRun ) { #ifdef DEBUG_RAC cout << reader->currentPos_ << " " << runsSoFar << " " << countsThisChunk << endl; #endif // don't bother writing this as can deduce by summing countsThisChunk // assert // ( fwrite( &reader->currentPos_, sizeof( LetterNumber ), 1, pIndexFile ) == 1 ); LetterNumber posInFile = reader->tellg(); assert ( fwrite( &posInFile, sizeof( LetterNumber ), 1, pIndexFile ) == 1 ); // In index format v2, we write each LetterCount independently, encoding the number of bytes as first byte for (int i=0; i<alphabetSize; ++i) { LetterNumber val = countsThisChunk.count_[i]; int bytesNeeded = 0; while (val >> (8*bytesNeeded)) ++bytesNeeded; assert( fwrite( &bytesNeeded, 1, 1, pIndexFile ) == 1 ); if (bytesNeeded) assert( fwrite( &val, bytesNeeded, 1, pIndexFile ) == 1 ); } chunksSoFar++; runsThisChunk = 0; countsThisChunk.clear(); } } cout << "buildIndex: read " << reader->currentPos_ << " bases compressed into " << runsSoFar << " runs" << " over " << reader->tellg() << " bytes." << endl; cout << "buildIndex: generated " << chunksSoFar << " index points." << endl; } // ~buildIndex // Explicit template instantiations template class BwtReaderIndex<BwtReaderRunLength>; template class BwtReaderIndex<BwtReaderRunLengthV3>;
40.158696
459
0.560494
3422fef3339e415cb49949b7f4aaa1d4da2b9efd
253
cpp
C++
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
valeriyvan/LinuxProgrammingWithRaspberryPi
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
[ "MIT" ]
4
2020-03-11T13:38:25.000Z
2021-12-25T00:48:53.000Z
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
valeriyvan/LinuxProgrammingWithRaspberryPi
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
[ "MIT" ]
null
null
null
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
valeriyvan/LinuxProgrammingWithRaspberryPi
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
[ "MIT" ]
8
2020-07-10T22:02:05.000Z
2021-12-15T02:11:44.000Z
#include <QApplication> #include <QLabel> #include <QPixmap> int main(int argc, char **argv) { QApplication app(argc, argv); QLabel* lb = new QLabel("", 0); lb->setPixmap(QPixmap("mandrill.jpg")); lb->show(); return app.exec(); }
16.866667
43
0.620553
34279a67e3c5d16a5ea26423c28bc022e6bc97f0
2,575
cpp
C++
src/Timer.cpp
JuanDiegoMontoya/g
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
[ "MIT" ]
2
2022-02-04T10:14:49.000Z
2022-03-01T23:45:22.000Z
src/Timer.cpp
JuanDiegoMontoya/g
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
[ "MIT" ]
null
null
null
src/Timer.cpp
JuanDiegoMontoya/g
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
[ "MIT" ]
null
null
null
#include <fwog/Common.h> #include <fwog/Timer.h> #include <numeric> namespace Fwog { TimerQuery::TimerQuery() { glGenQueries(2, queries); glQueryCounter(queries[0], GL_TIMESTAMP); } TimerQuery::~TimerQuery() { glDeleteQueries(2, queries); } uint64_t TimerQuery::GetTimestamp() { int complete = 0; glQueryCounter(queries[1], GL_TIMESTAMP); while (!complete) glGetQueryObjectiv(queries[1], GL_QUERY_RESULT_AVAILABLE, &complete); uint64_t startTime, endTime; glGetQueryObjectui64v(queries[0], GL_QUERY_RESULT, &startTime); glGetQueryObjectui64v(queries[1], GL_QUERY_RESULT, &endTime); std::swap(queries[0], queries[1]); return endTime - startTime; } TimerQueryAsync::TimerQueryAsync(uint32_t N) : capacity_(N) { FWOG_ASSERT(capacity_ > 0); queries = new uint32_t[capacity_ * 2]; glGenQueries(capacity_ * 2, queries); } TimerQueryAsync::~TimerQueryAsync() { glDeleteQueries(capacity_ * 2, queries); delete[] queries; } void TimerQueryAsync::BeginZone() { // begin a query if there is at least one inactive if (count_ < capacity_) { glQueryCounter(queries[start_], GL_TIMESTAMP); } } void TimerQueryAsync::EndZone() { // end a query if there is at least one inactive if (count_ < capacity_) { glQueryCounter(queries[start_ + capacity_], GL_TIMESTAMP); start_ = (start_ + 1) % capacity_; // wrap count_++; } } std::optional<uint64_t> TimerQueryAsync::PopTimestamp() { // return nothing if there is no active query if (count_ == 0) { return std::nullopt; } // get the index of the oldest query uint32_t index = (start_ + capacity_ - count_) % capacity_; // getting the start result is a sanity check GLint startResultAvailable{}; GLint endResultAvailable{}; glGetQueryObjectiv(queries[index], GL_QUERY_RESULT_AVAILABLE, &startResultAvailable); glGetQueryObjectiv(queries[index + capacity_], GL_QUERY_RESULT_AVAILABLE, &endResultAvailable); // the oldest query's result is not available, abandon ship! if (startResultAvailable == GL_FALSE || endResultAvailable == GL_FALSE) { return std::nullopt; } // pop oldest timing and retrieve result count_--; uint64_t startTimestamp{}; uint64_t endTimestamp{}; glGetQueryObjectui64v(queries[index], GL_QUERY_RESULT, &startTimestamp); glGetQueryObjectui64v(queries[index + capacity_], GL_QUERY_RESULT, &endTimestamp); return endTimestamp - startTimestamp; } }
27.105263
99
0.683495
342bcc038a2ca98c01e7e47922a5267283c40560
1,295
hpp
C++
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP #define ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP #include <Rosetta/PlayMode/Models/Playable.hpp> namespace RosettaStone::PlayMode { //! //! \brief PlayHistory struct. //! //! This struct holds all values for played card. //! struct PlayHistory { explicit PlayHistory(const Playable* source, const Playable* target, int _turn, int _chooseOne) { sourcePlayer = source->player; sourceCard = source->card; sourceID = source->GetGameTag(GameTag::ENTITY_ID); if (target) { targetPlayer = target->player; targetCard = target->card; } turn = _turn; chooseOne = _chooseOne; } Player* sourcePlayer = nullptr; Player* targetPlayer = nullptr; Card* sourceCard = nullptr; Card* targetCard = nullptr; int sourceID = -1; int turn = -1; int chooseOne = -1; }; } // namespace RosettaStone::PlayMode #endif // ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP
26.979167
79
0.671815
342bf1d0c337848387f546dbefaadabf6a466b8f
293
cpp
C++
BotPantela/Ball.cpp
djcvijic/BotPantela
174287e2b10cdd30d3217dd9c2ff766fcc93530d
[ "MIT" ]
null
null
null
BotPantela/Ball.cpp
djcvijic/BotPantela
174287e2b10cdd30d3217dd9c2ff766fcc93530d
[ "MIT" ]
null
null
null
BotPantela/Ball.cpp
djcvijic/BotPantela
174287e2b10cdd30d3217dd9c2ff766fcc93530d
[ "MIT" ]
null
null
null
#include "Ball.h" using namespace std; void Ball::inputPos () { double xPos; double yPos; cin >> xPos; cin >> yPos; setXPos(xPos); setYPos(yPos); } void Ball::inputVel () { double xVel; double yVel; cin >> xVel; cin >> yVel; setXVel(xVel); setYVel(yVel); }
12.73913
23
0.590444
342d610f2ded549890584ed91eed2c00fbd3e0dc
13,076
cpp
C++
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
bsairline/hamonize
6632d93b0149ed300d12c4eeb06cfc4fb01fce92
[ "Apache-2.0" ]
null
null
null
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
bsairline/hamonize
6632d93b0149ed300d12c4eeb06cfc4fb01fce92
[ "Apache-2.0" ]
1
2022-03-25T19:24:44.000Z
2022-03-25T19:24:44.000Z
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
gon1942/hamonize
0456d934569ad664e9f71c6355424426654caabf
[ "Apache-2.0", "MIT" ]
null
null
null
/* * RemoteAccessWidget.cpp - widget containing a VNC-view and controls for it * * Copyright (c) 2006-2021 Tobias Junghans <tobydox@veyon.io> * * This file is part of Veyon - https://veyon.io * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <QBitmap> #include <QLayout> #include <QMenu> #include <QPainter> #include <QPaintEvent> #include "rfb/keysym.h" #include "RemoteAccessWidget.h" #include "VncViewWidget.h" #include "VeyonConfiguration.h" #include "VeyonConnection.h" #include "VeyonMasterInterface.h" #include "Computer.h" #include "ComputerControlInterface.h" #include "PlatformCoreFunctions.h" #include "ToolButton.h" #include "Screenshot.h" // toolbar for remote-control-widget RemoteAccessWidgetToolBar::RemoteAccessWidgetToolBar( RemoteAccessWidget* parent, bool startViewOnly, bool showViewOnlyToggleButton ) : QWidget( parent ), m_parent( parent ), m_showHideTimeLine( ShowHideAnimationDuration, this ), m_iconStateTimeLine( 0, this ), m_connecting( false ), m_viewOnlyButton( showViewOnlyToggleButton ? new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/kmag.png") ), tr( "View only" ), tr( "Remote control" ) ) : nullptr ), m_sendShortcutButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/preferences-desktop-keyboard.png") ), tr( "Send shortcut" ) ) ), m_screenshotButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/camera-photo.png") ), tr( "Screenshot" ) ) ), m_fullScreenButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/view-fullscreen.png") ), tr( "Fullscreen" ), tr( "Window" ) ) ), m_exitButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/application-exit.png") ), tr( "Exit" ) ) ) { QPalette pal = palette(); pal.setBrush( QPalette::Window, QPixmap( QStringLiteral(":/core/toolbar-background.png") ) ); setPalette( pal ); setAttribute( Qt::WA_NoSystemBackground, true ); move( 0, 0 ); show(); startConnection(); if( m_viewOnlyButton ) { m_viewOnlyButton->setCheckable( true ); m_viewOnlyButton->setChecked( startViewOnly ); connect( m_viewOnlyButton, &ToolButton::toggled, this, &RemoteAccessWidgetToolBar::updateControls ); connect( m_viewOnlyButton, &QAbstractButton::toggled, parent, &RemoteAccessWidget::toggleViewOnly ); } m_fullScreenButton->setCheckable( true ); m_fullScreenButton->setChecked( false ); connect( m_fullScreenButton, &QAbstractButton::toggled, parent, &RemoteAccessWidget::toggleFullScreen ); connect( m_screenshotButton, &QAbstractButton::clicked, parent, &RemoteAccessWidget::takeScreenshot ); connect( m_exitButton, &QAbstractButton::clicked, parent, &QWidget::close ); auto vncView = parent->vncView(); auto shortcutMenu = new QMenu(); #if QT_VERSION < 0x050600 #warning Building legacy compat code for unsupported version of Qt connect( shortcutMenu->addAction( tr( "Ctrl+Alt+Del" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlAltDel ); } ); connect( shortcutMenu->addAction( tr( "Ctrl+Esc" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlEscape ); } ); connect( shortcutMenu->addAction( tr( "Alt+Tab" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltTab ); } ); connect( shortcutMenu->addAction( tr( "Alt+F4" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltF4 ); } ); connect( shortcutMenu->addAction( tr( "Win+Tab" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWinTab ); } ); connect( shortcutMenu->addAction( tr( "Win" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWin ); } ); connect( shortcutMenu->addAction( tr( "Menu" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutMenu ); } ); connect( shortcutMenu->addAction( tr( "Alt+Ctrl+F1" ) ), &QAction::triggered, vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltCtrlF1 ); } ); #else shortcutMenu->addAction( tr( "Ctrl+Alt+Del" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlAltDel ); } ); shortcutMenu->addAction( tr( "Ctrl+Esc" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlEscape ); } ); shortcutMenu->addAction( tr( "Alt+Tab" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltTab ); } ); shortcutMenu->addAction( tr( "Alt+F4" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltF4 ); } ); shortcutMenu->addAction( tr( "Win+Tab" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWinTab ); } ); shortcutMenu->addAction( tr( "Win" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWin ); } ); shortcutMenu->addAction( tr( "Menu" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutMenu ); } ); shortcutMenu->addAction( tr( "Alt+Ctrl+F1" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltCtrlF1 ); } ); #endif m_sendShortcutButton->setMenu( shortcutMenu ); m_sendShortcutButton->setPopupMode( QToolButton::InstantPopup ); m_sendShortcutButton->setObjectName( QStringLiteral("shortcuts") ); auto layout = new QHBoxLayout( this ); layout->setContentsMargins( 1, 1, 1, 1 ); layout->setSpacing( 1 ); layout->addStretch( 0 ); layout->addWidget( m_sendShortcutButton ); if( m_viewOnlyButton ) { layout->addWidget( m_viewOnlyButton ); } layout->addWidget( m_screenshotButton ); layout->addWidget( m_fullScreenButton ); layout->addWidget( m_exitButton ); layout->addSpacing( 5 ); connect( vncView, &VncViewWidget::startConnection, this, &RemoteAccessWidgetToolBar::startConnection ); connect( vncView, &VncViewWidget::connectionEstablished, this, &RemoteAccessWidgetToolBar::connectionEstablished ); setFixedHeight( m_exitButton->height() ); connect( &m_showHideTimeLine, &QTimeLine::valueChanged, this, &RemoteAccessWidgetToolBar::updatePosition ); m_iconStateTimeLine.setFrameRange( 0, 100 ); m_iconStateTimeLine.setDuration( 1500 ); m_iconStateTimeLine.setUpdateInterval( 60 ); m_iconStateTimeLine.easingCurve().setType( QEasingCurve::SineCurve ); connect( &m_iconStateTimeLine, &QTimeLine::valueChanged, this, &RemoteAccessWidgetToolBar::updateConnectionAnimation ); connect( &m_iconStateTimeLine, &QTimeLine::finished, &m_iconStateTimeLine, &QTimeLine::start ); } void RemoteAccessWidgetToolBar::appear() { m_showHideTimeLine.setDirection( QTimeLine::Backward ); if( m_showHideTimeLine.state() != QTimeLine::Running ) { m_showHideTimeLine.resume(); } } void RemoteAccessWidgetToolBar::disappear() { if( !m_connecting && !rect().contains( mapFromGlobal( QCursor::pos() ) ) ) { QTimer::singleShot( DisappearDelay, this, [this]() { if( m_showHideTimeLine.state() != QTimeLine::Running ) { m_showHideTimeLine.setDirection( QTimeLine::Forward ); m_showHideTimeLine.resume(); } } ); } } void RemoteAccessWidgetToolBar::updateControls( bool viewOnly ) { m_sendShortcutButton->setVisible( viewOnly == false ); } void RemoteAccessWidgetToolBar::leaveEvent( QEvent *event ) { disappear(); QWidget::leaveEvent( event ); } void RemoteAccessWidgetToolBar::paintEvent( QPaintEvent *paintEv ) { QPainter p( this ); QFont f = p.font(); p.setOpacity( 0.8-0.8*m_showHideTimeLine.currentValue() ); p.fillRect( paintEv->rect(), palette().brush( QPalette::Window ) ); p.setOpacity( 1 ); f.setPointSize( 12 ); f.setBold( true ); p.setFont( f ); //p.setPen( Qt::white ); //p.drawText( 64, 22, m_parent->windowTitle() ); p.setPen( QColor( 192, 192, 192 ) ); f.setPointSize( 10 ); p.setFont( f ); if( m_connecting ) { QString dots; for( int i = 0; i < ( m_iconStateTimeLine.currentTime() / 120 ) % 6; ++i ) { dots += QLatin1Char('.'); } p.drawText( 32, height() / 2 + fontMetrics().height(), tr( "Connecting %1" ).arg( dots ) ); } else { p.drawText( 32, height() / 2 + fontMetrics().height(), tr( "Connected." ) ); } } void RemoteAccessWidgetToolBar::updateConnectionAnimation() { repaint(); } void RemoteAccessWidgetToolBar::updatePosition() { const auto newY = static_cast<int>( m_showHideTimeLine.currentValue() * height() ); if( newY != -y() ) { move( x(), qMax( -height(), -newY ) ); } } void RemoteAccessWidgetToolBar::startConnection() { m_connecting = true; m_iconStateTimeLine.start(); appear(); update(); } void RemoteAccessWidgetToolBar::connectionEstablished() { m_connecting = false; m_iconStateTimeLine.stop(); disappear(); // within the next 1000ms the username should be known and therefore we update QTimer::singleShot( 1000, this, QOverload<>::of( &RemoteAccessWidgetToolBar::update ) ); } RemoteAccessWidget::RemoteAccessWidget( const ComputerControlInterface::Pointer& computerControlInterface, bool startViewOnly, bool showViewOnlyToggleButton ) : QWidget( nullptr ), m_computerControlInterface( computerControlInterface ), m_vncView( new VncViewWidget( computerControlInterface->computer().hostAddress(), -1, this, VncView::RemoteControlMode ) ), m_toolBar( new RemoteAccessWidgetToolBar( this, startViewOnly, showViewOnlyToggleButton ) ) { const auto openOnMasterScreen = VeyonCore::config().showFeatureWindowsOnSameScreen(); const auto master = VeyonCore::instance()->findChild<VeyonMasterInterface *>(); if( master && openOnMasterScreen ) { const auto masterWindow = master->mainWindow(); move( masterWindow->x(), masterWindow->y() ); } else { move( 0, 0 ); } updateRemoteAccessTitle(); connect( m_computerControlInterface.data(), &ComputerControlInterface::userChanged, this, &RemoteAccessWidget::updateRemoteAccessTitle ); setWindowIcon( QPixmap( QStringLiteral(":/remoteaccess/kmag.png") ) ); setAttribute( Qt::WA_DeleteOnClose, true ); m_vncView->move( 0, 0 ); m_vncView->installEventFilter( this ); connect( m_vncView, &VncViewWidget::mouseAtBorder, m_toolBar, &RemoteAccessWidgetToolBar::appear ); connect( m_vncView, &VncViewWidget::sizeHintChanged, this, &RemoteAccessWidget::updateSize ); showMaximized(); VeyonCore::platform().coreFunctions().raiseWindow( this, false ); showNormal(); toggleViewOnly( startViewOnly ); } RemoteAccessWidget::~RemoteAccessWidget() { delete m_vncView; } bool RemoteAccessWidget::eventFilter( QObject* object, QEvent* event ) { if( event->type() == QEvent::KeyRelease && dynamic_cast<QKeyEvent *>( event )->key() == Qt::Key_Escape && m_vncView->connection()->isConnected() == false ) { close(); return true; } if( object == m_vncView && event->type() == QEvent::FocusOut ) { m_toolBar->disappear(); } return QWidget::eventFilter( object, event ); } void RemoteAccessWidget::enterEvent( QEvent* event ) { m_toolBar->disappear(); QWidget::enterEvent( event ); } void RemoteAccessWidget::leaveEvent( QEvent* event ) { QTimer::singleShot( AppearDelay, this, [this]() { if( underMouse() == false && window()->isActiveWindow() ) { m_toolBar->appear(); } } ); QWidget::leaveEvent( event ); } void RemoteAccessWidget::resizeEvent( QResizeEvent* event ) { m_vncView->resize( size() ); m_toolBar->setFixedSize( width(), m_toolBar->height() ); QWidget::resizeEvent( event ); } void RemoteAccessWidget::updateSize() { if( !( windowState() & Qt::WindowFullScreen ) && m_vncView->sizeHint().isEmpty() == false ) { resize( m_vncView->sizeHint() ); } } void RemoteAccessWidget::toggleFullScreen( bool _on ) { if( _on ) { setWindowState( windowState() | Qt::WindowFullScreen ); } else { setWindowState( windowState() & ~Qt::WindowFullScreen ); } } void RemoteAccessWidget::toggleViewOnly( bool viewOnly ) { m_vncView->setViewOnly( viewOnly ); m_toolBar->updateControls( viewOnly ); m_toolBar->update(); } void RemoteAccessWidget::takeScreenshot() { Screenshot().take( m_computerControlInterface ); } void RemoteAccessWidget::updateRemoteAccessTitle() { if ( m_computerControlInterface->userFullName().isEmpty() ) { setWindowTitle( tr( "%1 - Hamonize Remote Access" ).arg( m_computerControlInterface->computer().name(), VeyonCore::applicationName() ) ); } else { setWindowTitle( tr( "%1 - %2 - Hamonize Remote Access" ).arg( m_computerControlInterface->userFullName(), m_computerControlInterface->computer().name(), VeyonCore::applicationName() ) ); } }
30.985782
172
0.712986
3430893905c8ae152e3b4e1ca262be70577a7af7
838
cpp
C++
native/ndarray/test/ndatest.cpp
bluemathsoft/bm-linalg
f4b96ec3f39480339898a587bf60b8aba0ad52bf
[ "Apache-2.0" ]
5
2017-10-18T14:19:17.000Z
2019-12-16T17:31:17.000Z
native/ndarray/test/ndatest.cpp
bluemathsoft/bm-linalg
f4b96ec3f39480339898a587bf60b8aba0ad52bf
[ "Apache-2.0" ]
1
2019-03-12T12:41:29.000Z
2019-03-12T12:41:29.000Z
native/ndarray/test/ndatest.cpp
bluemathsoft/bm-linalg
f4b96ec3f39480339898a587bf60b8aba0ad52bf
[ "Apache-2.0" ]
null
null
null
#include "ndarray.h" #include "ndatest.h" CPPUNIT_TEST_SUITE_REGISTRATION(NDATest); void NDATest::setUp() { } void NDATest::tearDown() { } void NDATest::testConstructor() { NDArray<uint32_t>::ShapeType shape = {2,2}; NDArray<uint32_t> ndarr(shape); CPPUNIT_ASSERT(ndarr.size() == 4); } void NDATest::testGetter() { NDArray<uint32_t>::ShapeType shape = {2,2}; std::vector<uint32_t> ndata = {4,5,6,7}; NDArray<uint32_t> ndarr(shape, ndata.data()); NDArray<uint32_t>::IndexType index = {0,1}; CPPUNIT_ASSERT(ndarr.get(index) == 5); } void NDATest::testSetter() { NDArray<uint32_t>::ShapeType shape = {2,2}; std::vector<uint32_t> ndata = {4,5,6,7}; NDArray<uint32_t> ndarr(shape, ndata.data()); NDArray<uint32_t>::IndexType index = {0,1}; ndarr.set(index, 356); CPPUNIT_ASSERT(ndarr.get(index) == 356); }
17.829787
47
0.678998
3437e389a3bb554caa194c623883806e623cea07
6,641
cpp
C++
src/llvmsym/stanalysis/inputvariables.cpp
yaqwsx/SymDivine
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
[ "MIT" ]
6
2015-10-13T20:01:01.000Z
2017-04-05T04:00:17.000Z
src/llvmsym/stanalysis/inputvariables.cpp
yaqwsx/SymDivine
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
[ "MIT" ]
6
2015-10-12T09:30:34.000Z
2016-05-24T16:44:12.000Z
src/llvmsym/stanalysis/inputvariables.cpp
yaqwsx/SymDivine
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
[ "MIT" ]
3
2015-10-12T12:20:25.000Z
2017-04-05T04:06:06.000Z
#include <llvmsym/llvmwrap/Instructions.h> #include <llvmsym/llvmwrap/Constants.h> #include <llvmsym/stanalysis/inputvariables.h> #include <llvmsym/cxa_abi/demangler.h> namespace { bool _is_nonconstant_pointer( const llvm::Value *val ) { return ( val->getType()->isPointerTy() && !llvm::isa< llvm::Constant >( val ) ) || llvm::isa< llvm::GlobalVariable >( val ); } } bool MultivalInfo::visit_value( const llvm::Value *val, const llvm::Function *parent ) { bool change = false; const llvm::User *v = llvm::dyn_cast< llvm::User >( val ); if ( !v ) return false; for ( unsigned i = 0; i < v->getNumOperands(); ++i ) { auto operand = v->getOperand( i ); if ( llvm::isa< llvm::ConstantExpr >( operand ) ) { auto operand_expr = llvm::cast< llvm::ConstantExpr >( operand ); change = change || visit_value( operand_expr, parent ); } } if ( llvm::isa< llvm::Function >( val ) ) return change; unsigned opcode; if ( llvm::isa< llvm::Instruction >( v ) ) { const llvm::Instruction *tmp_inst = llvm::cast< llvm::Instruction >( v ); opcode = tmp_inst->getOpcode(); } else { const llvm::ConstantExpr *tmp_inst = llvm::cast< llvm::ConstantExpr >( v ); opcode = tmp_inst->getOpcode(); } typedef llvm::Instruction LLVMInst; switch ( opcode ) { case LLVMInst::Ret: { const llvm::Value* returned = llvm::cast< llvm::ReturnInst >( v )->getReturnValue(); if ( returned && isMultival( returned ) ) { if ( !isMultival( parent ) ) { setMultival( parent ); change = true; } } else if ( returned && _is_nonconstant_pointer( returned ) ) { change = change || mergeRegionMultivalInfo( returned, parent ); } return change; } case LLVMInst::GetElementPtr: { assert( v->getType()->isPointerTy() ); const llvm::Value *elem = v->getOperand( 0 ); const llvm::Type *elem_type = elem->getType()->getPointerElementType(); std::vector< int > indices; if ( elem_type->isStructTy() ) { llvm::Type *ty = elem->getType()->getPointerElementType(); for ( auto it = v->op_begin() + 2; ty->isStructTy() && it < v->op_end(); ++it ) { assert( llvm::isa< llvm::ConstantInt >( it ) ); const llvm::ConstantInt *ci = llvm::cast< llvm::ConstantInt >( it ); int idx = ci->getLimitedValue(); indices.push_back( idx ); ty = ty->getContainedType( idx ); } } return mergeRegionMultivalInfoSubtype( elem, v, indices ); } case LLVMInst::ICmp: case LLVMInst::FCmp: { return change; } case LLVMInst::Store: { const llvm::Value *val_operand = llvm::cast< llvm::StoreInst >( v )->getValueOperand(); const llvm::Value *ptr = llvm::cast< llvm::StoreInst >( v )->getPointerOperand(); bool is_multival = isMultival( val_operand ); if ( is_multival && !isRegionMultival( ptr ) ) { setRegionMultival( ptr ); change = true; } if ( _is_nonconstant_pointer( val_operand ) ) { change = mergeRegionMultivalInfo( val_operand, ptr ); } return change; } case LLVMInst::Load: { const llvm::Value *ptr = llvm::cast< llvm::LoadInst >( v )->getPointerOperand(); if ( !v->getType()->isPointerTy() && !isMultival( v ) ) { if ( isRegionMultival( ptr ) ) { setMultival( v ); change = true; } } if ( v->getType()->isPointerTy() ) { change = mergeRegionMultivalInfo( v, ptr ); } return change; } case LLVMInst::Call: { const llvm::CallInst *ci = llvm::cast< llvm::CallInst >( v ); const llvm::Value *called_value = ci->getCalledFunction() ? ci->getCalledFunction() : ci->getCalledValue(); const llvm::Function *called_fun = ci->getCalledFunction(); if ( isMultival( called_value ) && !isMultival( v ) ) { setMultival( v ); change = true; } else if ( _is_nonconstant_pointer( v ) ) change = change || mergeRegionMultivalInfo( v, called_value ); if ( !called_fun ) return change; auto arg = called_fun->arg_begin(); for ( unsigned arg_no = 0; arg_no < ci->getNumArgOperands(); ++arg_no, ++arg) { const auto &operand = ci->getArgOperand( arg_no ); if ( isMultival( operand ) ) { if ( !isMultival( arg ) ) { setMultival( arg ); change = true; } } if ( _is_nonconstant_pointer( operand ) ) { change = mergeRegionMultivalInfo( operand, arg ); } } return change; } case LLVMInst::ExtractValue: { //TODO eventually abort(); } case LLVMInst::InsertValue: { //TODO eventually abort(); } } for ( unsigned operand = 0; operand < v->getNumOperands(); ++operand ) { if ( isMultival( v->getOperand( operand ) ) && !isMultival( v ) ) { setMultival( v ); change = true; break; } } return change; } bool MultivalInfo::visit_function( const llvm::Function &function ) { bool change = false; for ( const llvm::Value *v : *llvm_sym::collectUsedValues( &function ) ) { change = change || visit_value( v, &function ); } return change; } void MultivalInfo::get_multivalues( const llvm::Module *module ) { bool has_input = false; for ( const llvm::Function &f : *module ) { std::string fun_name = Demangler::demangle( f.getName() ); if ( llvm_sym::isFunctionInput( fun_name ) ) { has_input = true; setMultival( &f ); } } if ( !has_input ) return; bool change = true; while ( change ) { change = false; for ( const llvm::Function &function : *module ) { change = change || visit_function( function ); } } }
35.513369
99
0.514983
3438f017a59ebe1f52a4e23ee50c1de8ea272471
3,224
hpp
C++
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
uavosky/uavosky-px4
5793a7264a1400914521a077a7009dd227f9c766
[ "BSD-3-Clause" ]
4,224
2015-01-02T11:51:02.000Z
2020-10-27T23:42:28.000Z
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
uavosky/uavosky-px4
5793a7264a1400914521a077a7009dd227f9c766
[ "BSD-3-Clause" ]
11,736
2015-01-01T11:59:16.000Z
2020-10-28T17:13:38.000Z
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
uavosky/uavosky-px4
5793a7264a1400914521a077a7009dd227f9c766
[ "BSD-3-Clause" ]
11,850
2015-01-02T14:54:47.000Z
2020-10-28T16:42:47.000Z
/**************************************************************************** * * Copyright (c) 2022 PX4 Development Team. 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 PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include "ActuatorEffectiveness.hpp" #include <px4_platform_common/module_params.h> class ActuatorEffectivenessHelicopter : public ModuleParams, public ActuatorEffectiveness { public: static constexpr int NUM_SWASH_PLATE_SERVOS_MAX = 4; static constexpr int NUM_CURVE_POINTS = 5; struct SwashPlateGeometry { float angle; float arm_length; }; struct Geometry { SwashPlateGeometry swash_plate_servos[NUM_SWASH_PLATE_SERVOS_MAX]; int num_swash_plate_servos{0}; float throttle_curve[NUM_CURVE_POINTS]; float pitch_curve[NUM_CURVE_POINTS]; }; ActuatorEffectivenessHelicopter(ModuleParams *parent); virtual ~ActuatorEffectivenessHelicopter() = default; bool getEffectivenessMatrix(Configuration &configuration, EffectivenessUpdateReason external_update) override; const char *name() const override { return "Helicopter"; } const Geometry &geometry() const { return _geometry; } void updateSetpoint(const matrix::Vector<float, NUM_AXES> &control_sp, int matrix_index, ActuatorVector &actuator_sp) override; private: void updateParams() override; struct ParamHandlesSwashPlate { param_t angle; param_t arm_length; }; struct ParamHandles { ParamHandlesSwashPlate swash_plate_servos[NUM_SWASH_PLATE_SERVOS_MAX]; param_t num_swash_plate_servos; param_t throttle_curve[NUM_CURVE_POINTS]; param_t pitch_curve[NUM_CURVE_POINTS]; }; ParamHandles _param_handles{}; Geometry _geometry{}; int _first_swash_plate_servo_index{}; };
35.822222
111
0.743797
343973ee233f02e5296e9d3f81ba60df5cdf46c0
2,604
cpp
C++
src/RawlogHelper.cpp
dzunigan/extrinsic_calib
aec3747aeb6baecc7bc6202fc0832a113a1bc528
[ "BSD-3-Clause" ]
5
2018-10-24T02:14:54.000Z
2019-05-11T12:36:01.000Z
src/RawlogHelper.cpp
dzunigan/extrinsic_calib
aec3747aeb6baecc7bc6202fc0832a113a1bc528
[ "BSD-3-Clause" ]
null
null
null
src/RawlogHelper.cpp
dzunigan/extrinsic_calib
aec3747aeb6baecc7bc6202fc0832a113a1bc528
[ "BSD-3-Clause" ]
1
2021-06-30T01:12:49.000Z
2021-06-30T01:12:49.000Z
#include "RawlogHelper.hpp" //MRPT redefinition so they work without using mrpt namepase (more general) #ifndef CLASS_ID_ #define CLASS_ID_(class_name, space_name) static_cast<const mrpt::utils::TRuntimeClassId*>(&space_name::class_name::class##class_name) #endif #ifndef IS_CLASS_ #define IS_CLASS_( ptrObj, class_name, space_name ) ((ptrObj)->GetRuntimeClass()==CLASS_ID_(class_name, space_name)) #endif //STL #include <cmath> //MRPT #include <mrpt/system/datetime.h> //Debug #include <iostream> RawlogHelper::RawlogHelper(const ParametersPtr &params) : n(0), m(0), last_obs() //last_obs is a null pointer (default constructor) { max_time_diff = params->max_time_diff; verbose = params->verbose; rawlog.loadFromRawLogFile(params->rawlog_file); } bool RawlogHelper::getNextObservation(mrpt::obs::CObservation3DRangeScanPtr &obs) { mrpt::obs::CObservationPtr observation; while (!this->hasFinished()) { //1. Get observation from rawlog observation = rawlog.getAsObservation(n); n++; if (verbose) std::cout << "RawlogHelper: entry " << n << " (" << rawlog.size()+1 << ")" << std::endl; if(!observation || !IS_CLASS_(observation, CObservation3DRangeScan, mrpt::obs)) { if (verbose) std::cout << "Skipping rawlog entry " << (n-1) << "... (not valid CObservation3DRangeScan)" << std::endl; continue; } obs = (mrpt::obs::CObservation3DRangeScanPtr) observation; last_obs = obs; return true; } return false; } bool RawlogHelper::getNextPair(ObservationPair &obs2) { //Handle first call if (!last_obs) if (!this->getNextObservation(last_obs)) return false; do { obs2.first = last_obs; if (!this->getNextObservation(obs2.second)) return false; if (verbose) { std::cout << obs2.first->sensorLabel << ": " << obs2.first->timestamp << std::endl; std::cout << obs2.second->sensorLabel << ": " << obs2.second->timestamp << std::endl; } if (obs2.first->sensorLabel.compare(obs2.second->sensorLabel) != 0) m++; } while ((obs2.first->sensorLabel.compare(obs2.second->sensorLabel) == 0) || (std::abs(mrpt::system::timeDifference(obs2.first->timestamp, obs2.second->timestamp))) > max_time_diff); //abs shouldn't be needed, but it also doesn't harm... if (verbose) std::cout << "Synch" << std::endl; return true; } bool RawlogHelper::hasFinished() { return (n >= rawlog.size()); }
28
138
0.630184
343c15b6a0ac86e95b2432f6043483abcc50d90a
48
cc
C++
test/define/d3.cc
aytchell/cppclean
29ba7547a085f742585a74798cc5ad083bd0836f
[ "Apache-2.0" ]
607
2015-01-02T12:37:18.000Z
2022-03-20T13:37:01.000Z
test/define/d3.cc
aytchell/cppclean
29ba7547a085f742585a74798cc5ad083bd0836f
[ "Apache-2.0" ]
1,372
2019-11-14T09:22:21.000Z
2022-03-29T13:01:20.000Z
test/define/d3.cc
aytchell/cppclean
29ba7547a085f742585a74798cc5ad083bd0836f
[ "Apache-2.0" ]
86
2019-11-14T04:47:23.000Z
2022-03-03T02:44:15.000Z
#include "d3.h" void Namespace::Function() {}
9.6
29
0.645833
343dd66fe901d165781aa02d49bb2f845c2d716d
475
cpp
C++
examples/rocketwar/src/shared/network/incommingPacket.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
examples/rocketwar/src/shared/network/incommingPacket.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
examples/rocketwar/src/shared/network/incommingPacket.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
#include "incommingPacket.hpp" #include <cassert> namespace network { void IncommingPacket::reset() { assert(mHandled && "You are resetting a not handled packet!"); mPacket.clear(); mReadPos = 0; mHandled = false; } aw::uint8* IncommingPacket::reserve(size_t bytes) { mPacket.clear(); mPacket.writeToPayload(nullptr, bytes); return mPacket.payload().data(); } void IncommingPacket::resize(size_t bytes) { mPacket.resize(bytes); } } // namespace network
16.37931
64
0.711579
343f31dec15ad1b495e5e8c680c73fab57df1546
613
cpp
C++
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // #ifndef ONLINE_JUDGE // freopen("/home/shiva/Learning/1.txt", "r", stdin); // freopen("/home/shiva/Learning/2.txt", "w", stdout); // #endif int arr[10] = {0}; int t; cin >> t; long long b; string a; for (int x = 0; x < t; x++) { memset(arr, 0, sizeof arr); cin >> a >> b; if (b == 0) {cout << 1 << endl; continue;} int aa = int(a[int(a.size()) - 1]) - 48; int res = aa; int c = 0; vector<int> v; while (!arr[res]) { v.push_back(res); arr[res] = 1; res = (res * aa) % 10; c++; } cout << v[(b - 1) % c] << endl; } }
21.892857
55
0.51876
343f9c7d95740fbbad670c65ce53c46bc304e826
1,084
cc
C++
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
willianchanlovegithub/AliOS-Things
637c0802cab667b872d3b97a121e18c66f256eab
[ "Apache-2.0" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
/* * Copyright 1999-2019 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Executor.h" #include <alibabacloud/core/AlibabaCloud.h> static AlibabaCloud::Executor *executor = nullptr; void AlibabaCloud::InitializeSdk() { if (IsSdkInitialized()) return; executor = new Executor; executor->start(); } bool AlibabaCloud::IsSdkInitialized() { return executor != nullptr; } void AlibabaCloud::ShutdownSdk() { if (!IsSdkInitialized()) return; executor->shutdown(); delete executor; executor = nullptr; }
27.1
75
0.72786
343ff49b559c0f21635c590d49fe79a1fc4fa51a
984
hpp
C++
MazeSolver/Source/graph.hpp
Darhal/Maze-Solver
f8d46a6b3732a391efff63ed663ab47000b61388
[ "MIT" ]
null
null
null
MazeSolver/Source/graph.hpp
Darhal/Maze-Solver
f8d46a6b3732a391efff63ed663ab47000b61388
[ "MIT" ]
null
null
null
MazeSolver/Source/graph.hpp
Darhal/Maze-Solver
f8d46a6b3732a391efff63ed663ab47000b61388
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <utility> #include <stdint.h> #include <limits.h> class Graph { public: Graph(uint32_t vertecies = 0) : graph(vertecies) { } void SetVertex(uint32_t vertex, std::vector<std::pair<uint32_t, uint32_t>> next) { graph[vertex] = std::move(next); } void AddEdgeToVertex(uint32_t vertex, uint32_t next, uint32_t cost = 1) { graph[vertex].emplace_back(next, cost); } std::vector<std::pair<uint32_t, uint32_t>>& GetVertex(uint32_t vertex) { return graph[vertex]; } bool IsNext(uint32_t vertex, uint32_t next) { for (std::pair<uint32_t, uint32_t> v : this->GetVertex(vertex)) { if (v.first == next) { return true; } } return false; } uint32_t GetCost(uint32_t vertex, uint32_t next) { for (std::pair<uint32_t, uint32_t> v : this->GetVertex(vertex)) { if (v.first == next) { return v.second; } } return UINT_MAX; } private: std::vector<std::vector<std::pair<uint32_t, uint32_t>>> graph; };
18.566038
81
0.668699
34407b0deadf3a5daf2ecf83f8962faca98e3f7c
828
hpp
C++
01_src/compontents/components.hpp
gledr/SMT_MacroPlacer
b5b25f0ce9094553167ffd4985721f86414ceddc
[ "MIT" ]
3
2020-06-05T15:33:30.000Z
2021-05-03T07:34:15.000Z
01_src/compontents/components.hpp
gledr/SMT_MacroPlacer
b5b25f0ce9094553167ffd4985721f86414ceddc
[ "MIT" ]
null
null
null
01_src/compontents/components.hpp
gledr/SMT_MacroPlacer
b5b25f0ce9094553167ffd4985721f86414ceddc
[ "MIT" ]
1
2021-05-03T07:34:17.000Z
2021-05-03T07:34:17.000Z
//================================================================== // Author : Pointner Sebastian // Company : Johannes Kepler University // Name : SMT Macro Placer // Workfile : components.hpp // // Date : 19. May 2020 // Compiler : gcc version 9.3.0 (GCC) // Copyright : Johannes Kepler University // Description : Include Header for all Components //================================================================== #ifndef COMPONENTS_HPP #define COMPONENTS_HPP #include <cell.hpp> #include <component.hpp> #include <macro.hpp> #include <macro_definition.hpp> #include <partition.hpp> #include <pin.hpp> #include <pin_definition.hpp> #include <supplementmacro.hpp> #include <supplementpin.hpp> #include <terminal.hpp> #include <terminal_definition.hpp> #endif /* COMPONENTS_HPP */
29.571429
68
0.588164
34419f6dafb6189ebd9e5f5222f6a7701c2275ed
4,746
cc
C++
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 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 "chromecast/device/bluetooth/le/le_scan_manager_impl.h" #include <algorithm> #include <utility> #include "base/stl_util.h" #include "chromecast/base/bind_to_task_runner.h" #include "chromecast/device/bluetooth/bluetooth_util.h" #include "chromecast/public/cast_media_shlib.h" #define RUN_ON_IO_THREAD(method, ...) \ io_task_runner_->PostTask( \ FROM_HERE, base::BindOnce(&LeScanManagerImpl::method, \ weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); #define MAKE_SURE_IO_THREAD(method, ...) \ DCHECK(io_task_runner_); \ if (!io_task_runner_->BelongsToCurrentThread()) { \ RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ return; \ } #define EXEC_CB_AND_RET(cb, ret, ...) \ do { \ if (cb) { \ std::move(cb).Run(ret, ##__VA_ARGS__); \ } \ return; \ } while (0) namespace chromecast { namespace bluetooth { namespace { const int kMaxMessagesInQueue = 5; } // namespace LeScanManagerImpl::LeScanManagerImpl( bluetooth_v2_shlib::LeScannerImpl* le_scanner) : le_scanner_(le_scanner), observers_(new base::ObserverListThreadSafe<Observer>()), weak_factory_(this) {} LeScanManagerImpl::~LeScanManagerImpl() = default; void LeScanManagerImpl::Initialize( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) { io_task_runner_ = std::move(io_task_runner); } void LeScanManagerImpl::Finalize() {} void LeScanManagerImpl::AddObserver(Observer* observer) { observers_->AddObserver(observer); } void LeScanManagerImpl::RemoveObserver(Observer* observer) { observers_->RemoveObserver(observer); } void LeScanManagerImpl::SetScanEnable(bool enable, SetScanEnableCallback cb) { MAKE_SURE_IO_THREAD(SetScanEnable, enable, BindToCurrentSequence(std::move(cb))); bool success; if (enable) { success = le_scanner_->StartScan(); } else { success = le_scanner_->StopScan(); } if (!success) { LOG(ERROR) << "Failed to " << (enable ? "enable" : "disable") << " ble scanning"; EXEC_CB_AND_RET(cb, false); } observers_->Notify(FROM_HERE, &Observer::OnScanEnableChanged, enable); EXEC_CB_AND_RET(cb, true); } void LeScanManagerImpl::GetScanResults(GetScanResultsCallback cb, base::Optional<ScanFilter> scan_filter) { MAKE_SURE_IO_THREAD(GetScanResults, BindToCurrentSequence(std::move(cb)), std::move(scan_filter)); std::move(cb).Run(GetScanResultsInternal(std::move(scan_filter))); } // Returns a list of all scan results. The results are sorted by RSSI. std::vector<LeScanResult> LeScanManagerImpl::GetScanResultsInternal( base::Optional<ScanFilter> scan_filter) { DCHECK(io_task_runner_->BelongsToCurrentThread()); std::vector<LeScanResult> results; for (const auto& pair : addr_to_scan_results_) { for (const auto& scan_result : pair.second) { if (!scan_filter || scan_filter->Matches(scan_result)) { results.push_back(scan_result); } } } std::sort(results.begin(), results.end(), [](const LeScanResult& d1, const LeScanResult& d2) { return d1.rssi > d2.rssi; }); return results; } void LeScanManagerImpl::ClearScanResults() { MAKE_SURE_IO_THREAD(ClearScanResults); addr_to_scan_results_.clear(); } void LeScanManagerImpl::OnScanResult( const bluetooth_v2_shlib::LeScanner::ScanResult& scan_result_shlib) { LeScanResult scan_result; if (!scan_result.SetAdvData(scan_result_shlib.adv_data)) { // Error logged. return; } scan_result.addr = scan_result_shlib.addr; scan_result.rssi = scan_result_shlib.rssi; // Remove results with the same data as the current result to avoid duplicate // messages in the queue auto& previous_scan_results = addr_to_scan_results_[scan_result.addr]; previous_scan_results.remove_if([&scan_result](const auto& previous_result) { return previous_result.adv_data == scan_result.adv_data; }); previous_scan_results.push_front(scan_result); if (previous_scan_results.size() > kMaxMessagesInQueue) { previous_scan_results.pop_back(); } // Update observers. observers_->Notify(FROM_HERE, &Observer::OnNewScanResult, scan_result); } } // namespace bluetooth } // namespace chromecast
32.067568
80
0.665402
3441a9435a11658516d1b142812b86ad399095eb
1,045
cpp
C++
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "unique_store_buffer_type.hpp" #include "unique_store_entry.h" namespace vespalib::datastore { template class BufferType<UniqueStoreEntry<int8_t>>; template class BufferType<UniqueStoreEntry<int16_t>>; template class BufferType<UniqueStoreEntry<int32_t>>; template class BufferType<UniqueStoreEntry<int64_t>>; template class BufferType<UniqueStoreEntry<uint32_t>>; template class BufferType<UniqueStoreEntry<float>>; template class BufferType<UniqueStoreEntry<double>>; template class UniqueStoreBufferType<UniqueStoreEntry<int8_t>>; template class UniqueStoreBufferType<UniqueStoreEntry<int16_t>>; template class UniqueStoreBufferType<UniqueStoreEntry<int32_t>>; template class UniqueStoreBufferType<UniqueStoreEntry<int64_t>>; template class UniqueStoreBufferType<UniqueStoreEntry<uint32_t>>; template class UniqueStoreBufferType<UniqueStoreEntry<float>>; template class UniqueStoreBufferType<UniqueStoreEntry<double>>; };
40.192308
104
0.844019
45175a27e0afcdfbd6bdfa5d764209c195f5bc5c
2,411
hpp
C++
drtm-dst/src/rtx/batch_op_impl.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
9
2020-12-17T01:59:13.000Z
2022-03-30T16:25:08.000Z
drtm-dst/src/rtx/batch_op_impl.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-07-30T12:06:33.000Z
2021-07-31T10:16:09.000Z
drtm-dst/src/rtx/batch_op_impl.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-08-01T13:47:07.000Z
2021-08-01T13:47:07.000Z
#include "msg_format.hpp" namespace nocc { using namespace nocc::util; namespace rtx { struct BatchOpCtrlBlock { char *req_buf_; char *req_buf_end_; char *reply_buf_; std::set<int> mac_set_; int batch_size_; inline BatchOpCtrlBlock(char *req_buf,char *res_buf) : batch_size_(0), req_buf_(req_buf), reply_buf_(res_buf) { clear(); } inline void add_mac(int pid) { mac_set_.insert(pid); } inline void clear() { mac_set_.clear(); req_buf_end_ = req_buf_ + sizeof(RTXRequestHeader); batch_size_ = 0; } inline void clear_buf() { req_buf_end_ = req_buf_ + sizeof(RTXRequestHeader); batch_size_ = 0; } inline int batch_msg_size() { return req_buf_end_ - req_buf_; } inline int send_batch_op(RRpc *rpc,int cid,int rpc_id,bool pa = false) { if(batch_size_ > 0) { ((RTXRequestHeader *)req_buf_)->num = batch_size_; if(!pa) { rpc->prepare_multi_req(reply_buf_,mac_set_.size(),cid); } rpc->broadcast_to(req_buf_,rpc_id, batch_msg_size(), cid,RRpc::REQ,mac_set_); } return mac_set_.size(); } }; inline __attribute__((always_inline)) void TXOpBase::start_batch_rpc_op(BatchOpCtrlBlock &ctrl) { // no pending batch requests ctrl.clear(); } template <typename REQ,typename... _Args> // batch req inline __attribute__((always_inline)) void TXOpBase::add_batch_entry(BatchOpCtrlBlock &ctrl,int pid, _Args&& ... args) { ctrl.batch_size_ += 1; // copy the entries *((REQ *)ctrl.req_buf_end_) = REQ(std::forward<_Args>(args)...); ctrl.req_buf_end_ += sizeof(REQ); ctrl.mac_set_.insert(pid); } template <typename REQ,typename... _Args> // batch req inline __attribute__((always_inline)) void TXOpBase::add_batch_entry_wo_mac(BatchOpCtrlBlock &ctrl,int pid, _Args&& ... args) { ctrl.batch_size_ += 1; // copy the entries *((REQ *)ctrl.req_buf_end_) = REQ(std::forward<_Args>(args)...); ctrl.req_buf_end_ += sizeof(REQ); } inline __attribute__((always_inline)) int TXOpBase::send_batch_rpc_op(BatchOpCtrlBlock &ctrl,int cid,int rpc_id,bool pa) { return ctrl.send_batch_op(rpc_,cid,rpc_id,pa); } template <typename REPLY> inline __attribute__((always_inline)) REPLY *TXOpBase::get_batch_res(BatchOpCtrlBlock &ctrl,int idx) { return ((REPLY *)ctrl.reply_buf_ + idx); } }; // namespace rtx }; // namespace nocc
24.11
89
0.676898
451a0e3f3980397b7f77b9c1b79f06c786ecbfe0
1,115
cpp
C++
tests/actor_behavior.cpp
zzxx-husky/ZAF
b9c37c758a2f8242aec0d70c467d718468d08fa5
[ "Apache-2.0" ]
4
2021-07-29T12:49:09.000Z
2022-01-13T03:40:46.000Z
tests/actor_behavior.cpp
zzxx-husky/ZAF
b9c37c758a2f8242aec0d70c467d718468d08fa5
[ "Apache-2.0" ]
null
null
null
tests/actor_behavior.cpp
zzxx-husky/ZAF
b9c37c758a2f8242aec0d70c467d718468d08fa5
[ "Apache-2.0" ]
null
null
null
#include "zaf/actor_behavior.hpp" #include "zaf/actor_system.hpp" #include "gtest/gtest.h" namespace zaf { GTEST_TEST(ActorBehavior, Basic) { ActorSystem actor_system; ActorBehavior actor1; actor1.initialize_actor(actor_system, actor_system); ActorBehavior actor2; actor2.initialize_actor(actor_system, actor_system); actor1.send(actor2, 0, std::string("Hello World")); actor2.receive_once({ Code{0} - [](const std::string& hw) { EXPECT_EQ(hw, "Hello World"); } }); } GTEST_TEST(ActorBehavior, DelayedSendWithReceiveTimeout) { ActorSystem actor_system; auto a = actor_system.spawn([&](ActorBehavior& self) { self.delayed_send(std::chrono::seconds{1}, self, Code{0}); bool received = false; for (int i = 0; i < 4; i++) { self.receive_once({ Code{0} - [&]() { received = true; } }, std::chrono::milliseconds{200}); EXPECT_FALSE(received); } self.receive_once({ Code{0} - [&]() { received = true; } }, std::chrono::milliseconds{210}); EXPECT_TRUE(received); }); } } // namespace zaf
23.723404
62
0.634978
451ec556f9b2d36764908afcb2fcad82f82ed0d8
4,619
cpp
C++
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
avblocks/avblocks-samples
7388111a27c8110a9f7222e86e912fe38f444543
[ "MIT" ]
1
2022-02-28T04:12:09.000Z
2022-02-28T04:12:09.000Z
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
avblocks/avblocks-samples
7388111a27c8110a9f7222e86e912fe38f444543
[ "MIT" ]
null
null
null
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
avblocks/avblocks-samples
7388111a27c8110a9f7222e86e912fe38f444543
[ "MIT" ]
1
2022-02-28T02:43:24.000Z
2022-02-28T02:43:24.000Z
/* * Copyright (c) 2016 Primo Software. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ #include "stdafx.h" #include "util.h" #include "options.h" using namespace primo::codecs; using namespace primo::avblocks; using namespace std; class stdout_utf16 { public: stdout_utf16() { // change stdout to Unicode. Cyrillic and Ideographic characters will appear in the console (console font is unicode). _setmode(_fileno(stdout), _O_U16TEXT); } ~stdout_utf16() { // restore ANSI mode _setmode(_fileno(stdout), _O_TEXT); } }; void printStatus(const wchar_t* action, const primo::error::ErrorInfo* e) { if (action) { wcout << action << L": "; } if (primo::error::ErrorFacility::Success == e->facility()) { wcout << L"Success" << endl; return; } if (e->message()) { wcout << e->message() << L", "; } wcout << L"facility:" << e->facility() << L", error:" << e->code() << endl; } bool isHardwareEncoderAvailable(primo::codecs::HwVendor::Enum vendor, primo::codecs::HwCodecType::Enum type) { primo::ref<Hardware> hw(Library::createHardware()); hw->refresh(); for (int i = 0; i < hw->devices()->count(); ++i) { HwDevice* device = hw->devices()->at(i); if (device->vendor() == vendor) { for (int j = 0; j < device->codecs()->count(); ++j) { if (device->codecs()->at(j)->type() == type) return true; } } } return false; } primo::ref<MediaSocket> createInputSocket(Options& opt) { auto socket = primo::make_ref(Library::createMediaSocket()); socket->setStreamType(StreamType::UncompressedVideo); socket->setFile(opt.yuv_file.c_str()); auto pin = primo::make_ref(Library::createMediaPin()); socket->pins()->add(pin.get()); auto vsi = primo::make_ref(Library::createVideoStreamInfo()); pin->setStreamInfo(vsi.get()); vsi->setStreamType(StreamType::UncompressedVideo); vsi->setFrameWidth(opt.frame_size.width_); vsi->setFrameHeight(opt.frame_size.height_); vsi->setColorFormat(opt.yuv_color.Id); vsi->setFrameRate(opt.fps); vsi->setScanType(ScanType::Progressive); return socket; } primo::ref<MediaSocket> createOutputSocket(Options& opt) { auto socket = primo::make_ref(Library::createMediaSocket()); socket->setFile(opt.h264_file.c_str()); socket->setStreamType(StreamType::H264); socket->setStreamSubType(StreamSubType::AVC_Annex_B); auto pin = primo::make_ref(Library::createMediaPin()); socket->pins()->add(pin.get()); auto vsi = primo::make_ref(Library::createVideoStreamInfo()); pin->setStreamInfo(vsi.get()); pin->params()->addInt(Param::HardwareEncoder, HardwareEncoder::Intel); vsi->setStreamType(StreamType::H264); vsi->setStreamSubType(StreamSubType::AVC_Annex_B); return socket; } bool encode(Options& opt) { auto inSocket = createInputSocket(opt); // create output socket auto outSocket = createOutputSocket(opt); // create transcoder auto transcoder = primo::make_ref(Library::createTranscoder()); transcoder->setAllowDemoMode(TRUE); transcoder->inputs()->add(inSocket.get()); transcoder->outputs()->add(outSocket.get()); // transcoder will fail if output exists (by design) deleteFile(opt.h264_file.c_str()); bool_t res = transcoder->open(); printStatus(L"Transcoder open:", transcoder->error()); if(!res) return false; res = transcoder->run(); printStatus(L"Transcoder run:", transcoder->error()); if(!res) return false; transcoder->close(); printStatus(L"Transcoder close:", transcoder->error()); return true; } int wmain(int argc, wchar_t* argv[]) { Options opt; switch(prepareOptions( opt, argc, argv)) { case Command: return 0; case Error: return 1; } Library::initialize(); if (!isHardwareEncoderAvailable(primo::codecs::HwVendor::Intel, primo::codecs::HwCodecType::H264Encoder)) { wcout << "Intel H.264 hardware encoder is not available on your system" << endl; return 0; } bool result = encode(opt); Library::shutdown(); return result ? 0 : 1; }
26.394286
127
0.606841
452178ec8ad3cabe4e642fbe06772ac6f04cd837
6,590
cpp
C++
sg/importer/Importer.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
52
2018-10-09T23:56:32.000Z
2022-03-25T09:27:40.000Z
sg/importer/Importer.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
11
2018-11-19T18:51:47.000Z
2022-03-28T14:03:57.000Z
sg/importer/Importer.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
8
2019-02-10T00:16:24.000Z
2022-02-17T19:50:15.000Z
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "Importer.h" #include "sg/visitors/PrintNodes.h" #include "../JSONDefs.h" namespace ospray { namespace sg { OSPSG_INTERFACE std::map<std::string, std::string> importerMap = { {"obj", "importer_obj"}, {"gltf", "importer_gltf"}, {"glb", "importer_gltf"}, {"raw", "importer_raw"}, {"structured", "importer_raw"}, {"spherical", "importer_raw"}, {"vdb", "importer_vdb"}, {"pcd", "importer_pcd"}, {"pvol", "importer_pvol"}}; Importer::Importer() {} NodeType Importer::type() const { return NodeType::IMPORTER; } void Importer::importScene() { } OSPSG_INTERFACE void importScene( std::shared_ptr<StudioContext> context, rkcommon::FileName &sceneFileName) { std::cout << "Importing a scene" << std::endl; context->filesToImport.clear(); std::ifstream sgFile(sceneFileName.str()); if (!sgFile) { std::cerr << "Could not open " << sceneFileName << " for reading" << std::endl; return; } JSON j; sgFile >> j; std::map<std::string, JSON> jImporters; sg::NodePtr lights; // If the sceneFile contains a world (importers and lights), parse it here // (must happen before refreshScene) if (j.contains("world")) { auto &jWorld = j["world"]; for (auto &jChild : jWorld["children"]) { // Import either the old-type enum directly, or the new-type enum STRING NodeType nodeType = jChild["type"].is_string() ? NodeTypeFromString[jChild["type"]] : jChild["type"].get<NodeType>(); switch (nodeType) { case NodeType::IMPORTER: { FileName fileName = std::string(jChild["filename"]); // Try a couple different paths to find the file before giving up std::vector<std::string> possibleFileNames = {fileName, // as imported sceneFileName.path() + fileName.base(), // in scenefile directory fileName.base(), // in local directory ""}; for (auto tryFile : possibleFileNames) { if (tryFile != "") { std::ifstream f(tryFile); if (f.good()) { context->filesToImport.push_back(tryFile); jImporters[jChild["name"]] = jChild; break; } } else std::cerr << "Unable to find " << fileName << std::endl; } } break; case NodeType::LIGHTS: // Handle lights in either the (world) or the lightsManager lights = createNodeFromJSON(jChild); break; default: break; } } } // refreshScene imports all filesToImport if (!context->filesToImport.empty()) context->refreshScene(true); // Any lights in the scenefile World are added here if (lights) { for (auto &light : lights->children()) context->lightsManager->addLight(light.second); } // If the sceneFile contains a lightsManager, add those lights here if (j.contains("lightsManager")) { auto &jLights = j["lightsManager"]; for (auto &jLight : jLights["children"]) context->lightsManager->addLight(createNodeFromJSON(jLight)); } // If the sceneFile contains materials, parse them here, after the model has // loaded. These parameters will overwrite materials in the model file. if (j.contains("materialRegistry")) { sg::NodePtr materials = createNodeFromJSON(j["materialRegistry"]); for (auto &mat : materials->children()) { // XXX temporary workaround. Just set params on existing materials. // Prevents loss of texture data. Will be fixed when textures can reload. // Modify existing material or create new material // (account for change of material type) if (context->baseMaterialRegistry->hasChild(mat.first) && context->baseMaterialRegistry->child(mat.first).subType() == mat.second->subType()) { auto &bMat = context->baseMaterialRegistry->child(mat.first); for (auto &param : mat.second->children()) { auto &p = *param.second; // This is a generated node value and can't be imported if (param.first == "handles") continue; // Modify existing param or create new params if (bMat.hasChild(param.first)) bMat[param.first] = p.value(); else bMat.createChild( param.first, p.subType(), p.description(), p.value()); } } else context->baseMaterialRegistry->add(mat.second); } // refreshScene imports all filesToImport and updates materials context->refreshScene(true); } // If the sceneFile contains a camera location // (must happen after refreshScene) if (j.contains("camera")) { CameraState cs = j["camera"]; context->setCameraState(cs); context->updateCamera(); } // after import, correctly apply transform import nodes // (must happen after refreshScene) auto world = context->frame->childNodeAs<sg::Node>("world"); for (auto &jImport : jImporters) { // lamdba, find node by name std::function<sg::NodePtr(const sg::NodePtr, const std::string &)> findFirstChild = [&findFirstChild](const sg::NodePtr root, const std::string &name) -> sg::NodePtr { sg::NodePtr found = nullptr; // Quick shallow top-level search first for (auto child : root->children()) if (child.first == name) return child.second; // Next level, deeper search if not found for (auto child : root->children()) { found = findFirstChild(child.second, name); if (found) return found; } return found; }; auto importNode = findFirstChild(world, jImport.first); if (importNode) { // should be associated xfm node auto childName = jImport.second["children"][0]["name"]; Node &xfmNode = importNode->child(childName); // XXX parse JSON to get RST transforms saved to sg file. This is // temporary. We will want RST to be a first-class citizen node that gets // handled correctly without this kind of hardcoded workaround auto child = createNodeFromJSON(jImport.second["children"][0]); if (child) { xfmNode = child->value(); // assigns base affine3f value xfmNode.add(child->child("rotation")); xfmNode.add(child->child("translation")); xfmNode.add(child->child("scale")); } } } } // global assets catalogue AssetsCatalogue cat; } // namespace sg } // namespace ospray
31.5311
80
0.619272
4522b88d3e7187d55aa1849d096e3394be564b19
639
cpp
C++
checker.cpp
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
67b5cdce6696caed510efcd1e82f619dadfd08e3
[ "MIT" ]
null
null
null
checker.cpp
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
67b5cdce6696caed510efcd1e82f619dadfd08e3
[ "MIT" ]
null
null
null
checker.cpp
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
67b5cdce6696caed510efcd1e82f619dadfd08e3
[ "MIT" ]
null
null
null
#include <assert.h> bool vitalsRangeIsOk(float value,int lowerLimit,int upperLimit) { return (value >= lowerLimit && value <= upperLimit); } bool vitalsAreOk(float bpm, float spo2, float respRate) { return (vitalsRangeIsOk(bpm,70,150) && vitalsRangeIsOk(spo2,90,100) && vitalsRangeIsOk(respRate,30,95)); } int main() { assert(vitalsRangeIsOk(160,70,150) == false); assert(vitalsRangeIsOk(20,70,150) == false); assert(vitalsRangeIsOk(70,70,150) == true); assert(vitalsRangeIsOk(90,70,150) == true); assert(vitalsAreOk(80, 95, 60) == true); assert(vitalsAreOk(60, 90, 40) == false); return 0; }
26.625
108
0.672926
452c2bc19dabb166d7962055bbbd3adb041b7e93
514
cpp
C++
uppdev/RichHtml/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/RichHtml/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/RichHtml/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include <CtrlLib/CtrlLib.h> #include <RichText/RichText.h> #include <Web/Web.h> using namespace Upp; #define TOPICFILE <RichHtml/tst.tpp/all.i> #include <Core/topic_group.h> GUI_APP_MAIN { Index<String> css; VectorMap<String, String> links; String qtf = GetTopic("topic://RichHtml/tst/Topic$en-us"); String html = EncodeHtml(ParseQTF(qtf), css, links, "e:\\xxx"); Htmls content = HtmlHeader("Ultimate++", AsCss(css)) .BgColor(White) / html; SaveFile(GetHomeDirFile("html.html"), content); }
23.363636
64
0.702335
452da6fe4e6d905249e89e7673f85c4a1a11cda2
774
cpp
C++
Miscellaneous/InterviewBit/Array/RotateImage.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
24
2021-02-09T17:59:54.000Z
2022-03-11T07:30:38.000Z
Miscellaneous/InterviewBit/Array/RotateImage.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
null
null
null
Miscellaneous/InterviewBit/Array/RotateImage.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
3
2021-06-22T03:09:49.000Z
2022-03-09T18:25:14.000Z
#include <bits/stdc++.h> void rotate(std::vector<std::vector<int> > &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details for(int i = 0; i < A.size() / 2; i++) { for(int j = i; j < A.size() - i - 1; j++) { int temp = A[i][j]; A[i][j] = A[A.size() - 1 - j][i]; A[A.size() - j - 1][i] = A[A.size() - 1 - i][A.size() - j - 1]; A[A.size() - 1 - i][A.size() - j - 1] = A[j][A.size() - i - 1]; A[j][A.size() - i - 1] = temp; } } }
35.181818
93
0.459948
452ee43e21aafb068418cfb57dfdab51a06eee65
2,784
cpp
C++
benchmark/demo_benchmark.cpp
Algorithms-and-Data-Structures-2021/semester-work-median
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
[ "MIT" ]
null
null
null
benchmark/demo_benchmark.cpp
Algorithms-and-Data-Structures-2021/semester-work-median
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
[ "MIT" ]
null
null
null
benchmark/demo_benchmark.cpp
Algorithms-and-Data-Structures-2021/semester-work-median
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
[ "MIT" ]
null
null
null
#include <fstream> // ifstream #include <iostream> // cout #include <string> // string, stoi #include <string_view> // string_view #include <chrono> // high_resolution_clock, duration_cast, nanoseconds #include <sstream> // stringstream #include <vector> // подключаем алгоритм #include "algorithm.hpp" using namespace std; // абсолютный путь до набора данных и папки проекта static constexpr auto kDatasetPath = string_view{PROJECT_DATASET_DIR}; static constexpr auto kProjectPath = string_view{PROJECT_SOURCE_DIR}; //Путь к папке с наборами данных для заполнения const string setsPath = "C:/Users/Admin/Desktop/sets"; // Сгенирировать наборы даннх : https://github.com/rthoor/generation.git //укажите названия папок с наборами данных, если они есть string folders[5] = {"/01/","/02/","/03/","/04/","/05/"}; //если их нет //string folders[1] = {"/"}; //укажите названия файлов с наборами данных (без .csv) string files[8] = {"11", "51", "101", "501", "1001", "5001", "10001", "50001"}; //Путь к папке, куда нужно выгрузить результаты const string outputPath = "C:/Users/Admin/Desktop/results/"; // Ознакомтесь с директорией "results-path-example/results" // в папке выгруза результатов нужно будет реализовать похожую структуру, // опираясь на названия файлов в массиве files // ----------------------------------- // запускать main() (в самом низу) | // ----------------------------------- //Вывод результатов void writeResults(string file, long time) { // вывод результата // не забудьте подготовить директорию std::ofstream out(outputPath + file + "/results.txt", std::ios::app); if (out.is_open()) { out << time << std::endl; } out.close(); } void goTest() { for (auto file : files) { for (auto folder : folders) { for (int i = 0; i < 10; i++) { // i = сколько раз прогоняем один и тот же csv файл auto input_file = ifstream(setsPath + folder + file + ".csv"); string line; // Создание структуры vector<int> array; // добавление while (getline(input_file, line, ',')) { array.push_back(stoi(line)); } auto time_point_before = chrono::steady_clock::now(); itis::quickselect(array); auto time_point_after = chrono::steady_clock::now(); auto time_diff_insert = time_point_after - time_point_before; long time = chrono::duration_cast<chrono::nanoseconds>(time_diff_insert).count(); array.clear(); // запись результатов writeResults(file, time); } } } } int main() { goTest(); return 0; }
32
97
0.600575
45310c3ba8f1aa569b5c663e734e95570828b415
2,128
cpp
C++
Shared Classes/Stats.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
Shared Classes/Stats.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
Shared Classes/Stats.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* ------------------------------------------------------------------------------------------ Copyright (c) 2014 Vinyl Games Studio Author: Mikhail Kutuzov Date: 10/7/2014 5:45:48 PM ------------------------------------------------------------------------------------------ */ #include "Stats.h" #include "Effect.h" using namespace merrymen; // // handles application of the effect // void Stats::ApplyEffect(const Effect& effect, vgs::GameObject* const author) { Effect* appliedEffect = new Effect(effect); // add the effect to the list of applied effects AppliedEffects.insert(std::pair<Effect*, vgs::GameObject*>(appliedEffect, author)); } // // cancels one of the applied effects // void Stats::UnapplyEffect(Effect* const effect, vgs::GameObject* const author) { // remove the effect from the list of applied effects AppliedEffects.erase(effect); delete effect; } // // returns all of the effects applied to the stats which match the passed type // std::vector<Effect*> Stats::GetAppliedEffectsOfType(const SpecificEffectType& type) { std::vector<Effect*> result; for (auto effect : AppliedEffects) { SpecificEffectType effectType = SpecificEffectType(effect.first->Type, effect.first->Reason); if (effectType == type) { result.push_back(effect.first); } } return result; } // // returns all of the effects of the same type as the passed effect, which are applied to the stats // std::vector<Effect*> Stats::GetSimilarAppliedEffects(const Effect& effect) { std::vector<Effect*> result; SpecificEffectType effectType = SpecificEffectType(effect.Type, effect.Reason); for (auto appliedEffect : AppliedEffects) { SpecificEffectType appliedEfectType = SpecificEffectType(appliedEffect.first->Type, appliedEffect.first->Reason); if (effectType == appliedEfectType) { result.push_back(appliedEffect.first); } } return result; } // // cound the number of effects of the same type as the passed effect, which are applied to the stats // int Stats::CountSimilarAppliedEffects(const Effect& effect) { return GetSimilarAppliedEffects(effect).size(); }
25.035294
115
0.670583
4531123f6dcce4fd01d694f2d37959abaadcdd44
9,191
cpp
C++
cpp/cppfind/src/FindSettings.cpp
clarkcb/xfind
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
[ "MIT" ]
null
null
null
cpp/cppfind/src/FindSettings.cpp
clarkcb/xfind
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
[ "MIT" ]
null
null
null
cpp/cppfind/src/FindSettings.cpp
clarkcb/xfind
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
[ "MIT" ]
null
null
null
#include "FileUtil.h" #include "StringUtil.h" #include "FindSettings.h" namespace cppfind { FindSettings::FindSettings() { m_in_archiveextensions = {}; m_in_archivefilepatterns = {}; m_in_dirpatterns = {}; m_in_extensions = {}; m_in_filepatterns = {}; m_in_filetypes = {}; m_out_archiveextensions = {}; m_out_archivefilepatterns = {}; m_out_dirpatterns = {}; m_out_extensions = {}; m_out_filepatterns = {}; m_out_filetypes = {}; m_paths = {}; } void FindSettings::add_pattern(const std::string& p, std::vector<FindPattern*>* ps) { ps->push_back(new FindPattern(p)); } void FindSettings::add_extensions(const std::string& exts, std::vector<std::string>* extensions) { std::vector<std::string> xs = StringUtil::split_string(exts, ","); for (const auto& x : xs) { if (!x.empty()) { extensions->push_back(x); } } } void FindSettings::add_in_archiveextension(const std::string& ext) { add_extensions(ext, &m_in_archiveextensions); } void FindSettings::add_in_archivefilepattern(const std::string& p) { add_pattern(p, &m_in_archivefilepatterns); } void FindSettings::add_in_dirpattern(const std::string& p) { add_pattern(p, &m_in_dirpatterns); } void FindSettings::add_in_extension(const std::string& ext) { add_extensions(ext, &m_in_extensions); } void FindSettings::add_in_filepattern(const std::string& p) { add_pattern(p, &m_in_filepatterns); } void FindSettings::add_in_filetype(const FileType filetype) { m_in_filetypes.push_back(filetype); } void FindSettings::add_out_archiveextension(const std::string& ext) { add_extensions(ext, &m_out_archiveextensions); } void FindSettings::add_out_archivefilepattern(const std::string& p) { add_pattern(p, &m_out_archivefilepatterns); } void FindSettings::add_out_dirpattern(const std::string& p) { add_pattern(p, &m_out_dirpatterns); } void FindSettings::add_out_extension(const std::string& ext) { add_extensions(ext, &m_out_extensions); } void FindSettings::add_out_filepattern(const std::string& p) { add_pattern(p, &m_out_filepatterns); } void FindSettings::add_out_filetype(const FileType filetype) { m_out_filetypes.push_back(filetype); } void FindSettings::add_path(const std::string& p) { m_paths.push_back(p); } bool FindSettings::archivesonly() const { return m_archivesonly; } bool FindSettings::debug() const { return m_debug; } bool FindSettings::excludehidden() const { return m_excludehidden; } bool FindSettings::includearchives() const { return m_includearchives; } bool FindSettings::listdirs() const { return m_listdirs; } bool FindSettings::listfiles() const { return m_listfiles; } bool FindSettings::printusage() const { return m_printusage; } bool FindSettings::printversion() const { return m_printversion; } bool FindSettings::recursive() const { return m_recursive; } std::vector<std::string>* FindSettings::in_archiveextensions() { return &m_in_archiveextensions; } std::vector<FindPattern*>* FindSettings::in_archivefilepatterns() { return &m_in_archivefilepatterns; } std::vector<FindPattern*>* FindSettings::in_dirpatterns() { return &m_in_dirpatterns; } std::vector<std::string>* FindSettings::in_extensions() { return &m_in_extensions; } std::vector<FindPattern*>* FindSettings::in_filepatterns() { return &m_in_filepatterns; } std::vector<FileType>* FindSettings::in_filetypes() { return &m_in_filetypes; } std::vector<std::string>* FindSettings::out_archiveextensions() { return &m_out_archiveextensions; } std::vector<FindPattern*>* FindSettings::out_archivefilepatterns() { return &m_out_archivefilepatterns; } std::vector<FindPattern*>* FindSettings::out_dirpatterns() { return &m_out_dirpatterns; } std::vector<std::string>* FindSettings::out_extensions() { return &m_out_extensions; } std::vector<FindPattern*>* FindSettings::out_filepatterns() { return &m_out_filepatterns; } std::vector<FileType>* FindSettings::out_filetypes() { return &m_out_filetypes; } std::vector<std::string>* FindSettings::paths() { return &m_paths; } bool FindSettings::verbose() const { return m_verbose; } void FindSettings::archivesonly(const bool b) { m_archivesonly = b; if (b) m_includearchives = b; } void FindSettings::debug(const bool b) { m_debug = b; if (b) m_verbose = b; } void FindSettings::excludehidden(const bool b) { m_excludehidden = b; } void FindSettings::includearchives(const bool b) { m_includearchives = b; } void FindSettings::listdirs(const bool b) { m_listdirs = b; } void FindSettings::listfiles(const bool b) { m_listfiles = b; } void FindSettings::printusage(const bool b) { m_printusage = b; } void FindSettings::printversion(const bool b) { m_printversion = b; } void FindSettings::recursive(const bool b) { m_recursive = b; } void FindSettings::verbose(const bool b) { m_verbose = b; } std::string FindSettings::bool_to_string(bool b) { return b ? "true" : "false"; } std::string FindSettings::string_vector_to_string(std::vector<std::string>* ss) { std::string ss_string = "["; int count = 0; for (auto const& s : *ss) { if (count > 0) { ss_string.append(", "); } ss_string.append("\"").append(s).append("\""); count++; } ss_string.append("]"); return ss_string; } std::string FindSettings::findpatterns_to_string(std::vector<FindPattern*>* ps) { std::string ps_string = "["; int count = 0; for (auto const& p : *ps) { if (count > 0) { ps_string.append(", "); } ps_string.append("\"").append(p->pattern()).append("\""); count++; } ps_string.append("]"); return ps_string; } std::string FindSettings::filetypes_to_string(std::vector<FileType>* ts) { std::string ts_string = "["; int count = 0; for (auto const& t : *ts) { if (count > 0) { ts_string.append(", "); } ts_string.append("\"").append(FileTypes::to_name(t)).append("\""); count++; } ts_string.append("]"); return ts_string; } std::string FindSettings::string() { auto settings_str = std::string("FindSettings(") + "archivesonly: " + bool_to_string(m_archivesonly) + ", debug: " + bool_to_string(m_debug) + ", excludehidden: " + bool_to_string(m_excludehidden) + ", in_archiveextensions: " + string_vector_to_string(&m_in_archiveextensions) + ", in_archivefilepatterns: " + findpatterns_to_string(&m_in_archivefilepatterns) + ", in_dirpatterns: " + findpatterns_to_string(&m_in_dirpatterns) + ", in_extensions: " + string_vector_to_string(&m_in_extensions) + ", in_filepatterns: " + findpatterns_to_string(&m_in_filepatterns) + ", in_filetypes: " + filetypes_to_string(&m_in_filetypes) + ", includearchives: " + bool_to_string(m_includearchives) + ", listdirs: " + bool_to_string(m_listdirs) + ", listfiles: " + bool_to_string(m_listfiles) + ", out_archiveextensions: " + string_vector_to_string(&m_out_archiveextensions) + ", out_archivefilepatterns: " + findpatterns_to_string(&m_out_archivefilepatterns) + ", out_dirpatterns: " + findpatterns_to_string(&m_out_dirpatterns) + ", out_extensions: " + string_vector_to_string(&m_out_extensions) + ", out_filepatterns: " + findpatterns_to_string(&m_out_filepatterns) + ", out_filetypes: " + filetypes_to_string(&m_out_filetypes) + ", paths: " + string_vector_to_string(&m_paths) + ", printusage: " + bool_to_string(m_printusage) + ", printversion: " + bool_to_string(m_printversion) + ", recursive: " + bool_to_string(m_recursive) + ", verbose: " + bool_to_string(m_verbose) + ")"; return settings_str; } std::ostream& operator<<(std::ostream& strm, FindSettings& settings) { std::string settings_string = settings.string(); return strm << settings_string; } }
30.433775
102
0.598955
4536e307f42d425866f3d9ad9020706f0477068b
3,190
cpp
C++
vec3f.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
vec3f.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
vec3f.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Thomas Kaldahl #include "qecvec.hpp" // Constructors Vec3f::Vec3f( float x, float y, float z ) { this->x = x; this->y = y; this->z = z; } Vec3f::Vec3f(float val) : Vec3f(val, val, val) {} Vec3f::Vec3f() : Vec3f(0) {} Vec3f::Vec3f(Vec2f v, float z) : Vec3f(v.x, v.y, z) {} Vec3f::Vec3f(float x, Vec2f v) : Vec3f(x, v.x, v.y) {} // Statics Vec3f Vec3f::zero() {return Vec3f();} Vec3f Vec3f::up() {return Vec3f( 0, 1, 0 );} Vec3f Vec3f::down() {return Vec3f( 0, -1, 0 );} Vec3f Vec3f::left() {return Vec3f( -1, 0, 0 );} Vec3f Vec3f::right() {return Vec3f( 1, 0, 0 );} Vec3f Vec3f::forward() {return Vec3f( 0, 0, 1 );} Vec3f Vec3f::backward() {return Vec3f( 0, 0, -1 );} //vec2f.cpp: Vec2f Vec2f::up() {return Vec2f( 0, 1 );} //vec2f.cpp: Vec2f Vec2f::down() {return Vec2f( 0, -1 );} //vec2f.cpp: Vec2f Vec2f::left() {return Vec2f( -1, 0 );} //vec2f.cpp: Vec2f Vec2f::right() {return Vec2f( 1, 0 );} //vec2f.cpp: Vec2f Vec2f::polar(float r, float theta) { //vec2f.cpp: return Vec2f(r * cos(theta), r * sin(theta)); //vec2f.cpp: } Vec3f Vec3f::randomUniform(float min, float max) { float x = (max - min) * rand() / (float)RAND_MAX + min; float y = (max - min) * rand() / (float)RAND_MAX + min; float z = (max - min) * rand() / (float)RAND_MAX + min; return Vec3f(x, y, z); } // Accessors char *Vec3f::string() const { char *res = (char*)malloc(64); snprintf(res, 64, "< %0.3f, %0.3f, %0.3f >", x, y, z); return res; } Vec2f Vec3f::xy() const {return Vec2f(x, y);} Vec2f Vec3f::xz() const {return Vec2f(x, z);} Vec2f Vec3f::yz() const {return Vec2f(y, z);} // Technical methods Vec3f Vec3f::copy() const { return Vec3f(x, y, z); } // In-place operations Vec3f Vec3f::operator*=(float scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; } Vec3f Vec3f::operator/=(float divisor) { x /= divisor; y /= divisor; z /= divisor; return *this; } Vec3f Vec3f::operator+=(Vec3f addend) { x += addend.x; y += addend.y; z += addend.z; return *this; } Vec3f Vec3f::operator-=(Vec3f subtrahend) { x -= subtrahend.x; y -= subtrahend.y; z -= subtrahend.z; return *this; } Vec3f Vec3f::operator&=(Vec3f multiplier) { x *= multiplier.x; y *= multiplier.y; z *= multiplier.z; return *this; } Vec3f Vec3f::normalize() { x /= norm(); y /= norm(); z /= norm(); return *this; } // Binary operations Vec3f Vec3f::operator*(float scalar) const {return copy() *= scalar;} Vec3f Vec3f::operator/(float divisor) const {return copy() /= divisor;} float Vec3f::operator^(float exponent) const {return pow(norm(), exponent);} Vec3f operator*(float scalar, Vec3f vector) {return vector * scalar;} Vec3f Vec3f::operator+(Vec3f addend) const {return copy() += addend;} Vec3f Vec3f::operator-(Vec3f subtrahend) const {return copy() -= subtrahend;} Vec3f Vec3f::operator&(Vec3f multiplier) const {return copy() &= multiplier;} float Vec3f::operator*(Vec3f multiplier) const { return x * multiplier.x + y * multiplier.y + z * multiplier.z; } // Unary operations Vec3f Vec3f::operator-() const {return -1 * *this;} float Vec3f::norm() const {return sqrt(x*x + y*y + z*z);} Vec3f Vec3f::normal() const {return *this / norm();}
25.52
77
0.630408
45382cb1d1d0ba807d163bc1cb1d314da6852610
3,806
cpp
C++
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
/*** *mbsdec.c - Move MBCS string pointer backward one charcter. * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * Move MBCS string pointer backward one character. * *******************************************************************************/ #ifndef _MBCS #error This file should only be compiled with _MBCS defined #endif #include <corecrt_internal.h> #include <corecrt_internal_mbstring.h> #include <locale.h> #include <stddef.h> /*** *_mbsdec - Move MBCS string pointer backward one charcter. * *Purpose: * Move the supplied string pointer backwards by one * character. MBCS characters are handled correctly. * *Entry: * const unsigned char *string = pointer to beginning of string * const unsigned char *current = current char pointer (legal MBCS boundary) * *Exit: * Returns pointer after moving it. * Returns nullptr if string >= current. * *Exceptions: * Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/ extern "C" unsigned char * __cdecl _mbsdec_l( const unsigned char *string, const unsigned char *current, _locale_t plocinfo ) { const unsigned char *temp; /* validation section */ _VALIDATE_RETURN(string != nullptr, EINVAL, nullptr); _VALIDATE_RETURN(current != nullptr, EINVAL, nullptr); if (string >= current) return(nullptr); _LocaleUpdate _loc_update(plocinfo); if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0) return (unsigned char *)--current; temp = current - 1; /* There used to be an optimisation here: * * If (current-1) returns true from _ismbblead, it is a trail byte, because * current is a known character start point, and so current-1 would have to be a * legal single byte MBCS character, which a lead byte is not. Therefore, if so, * return (current-2) because it must be the trailbyte's lead. * * if ( _ismbblead(*temp) ) * return (unsigned char *)(temp - 1); * * But this is not a valid optimisation if you want to cope correctly with an * MBCS string which is terminated by a leadbyte and a 0 byte, when you are passed * an initial position pointing to the \0 at the end of the string. * * This optimisation is also invalid if you are passed a pointer to half-way * through an MBCS pair. * * Neither of these are truly valid input conditions, but to ensure predictably * correct behaviour in the presence of these conditions, we have removed * the optimisation. */ /* * It is unknown whether (current - 1) is a single byte character or a * trail. Now decrement temp until * a) The beginning of the string is reached, or * b) A non-lead byte (either single or trail) is found. * The difference between (current-1) and temp is the number of non-single * byte characters preceding (current-1). There are two cases for this: * a) (current - temp) is odd, and * b) (current - temp) is even. * If odd, then there are an odd number of "lead bytes" preceding the * single/trail byte (current - 1), indicating that it is a trail byte. * If even, then there are an even number of "lead bytes" preceding the * single/trail byte (current - 1), indicating a single byte character. */ while ( (string <= --temp) && (_ismbblead_l(*temp, _loc_update.GetLocaleT())) ) ; return (unsigned char *)(current - 1 - ((current - temp) & 0x01) ); } extern "C" unsigned char * (__cdecl _mbsdec)( const unsigned char *string, const unsigned char *current ) { return _mbsdec_l(string, current, nullptr); }
34.6
88
0.64083
4539f7f1d006ae249eb8f841b2f0a897d401f16e
1,678
cpp
C++
Heap.cpp
Aman-Chopra/DataStructure-Algorithms
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
[ "MIT" ]
null
null
null
Heap.cpp
Aman-Chopra/DataStructure-Algorithms
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
[ "MIT" ]
3
2016-06-09T07:46:15.000Z
2017-05-06T07:56:18.000Z
Heap.cpp
Aman-Chopra/DataStructure-Algorithms
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
[ "MIT" ]
4
2016-06-09T07:14:37.000Z
2021-05-21T22:07:20.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; int smallest = 0; int largest = 0; void max_heapify(vector<int> &v, int i, int *n) { int left = 2*i; int right = 2*i+1; if(left <= *n && v[left] > v[i]) largest = left; else largest = i; if(right <= *n && v[right] > v[largest]) largest = right; if(largest != i) { swap(v[i],v[largest]); max_heapify(v,largest,n); } } void min_heapify(vector<int> &v, int i, int *n) { int left = 2*i; int right = 2*i+1; if(left <= *n && v[left] < v[i]) smallest = left; else smallest = i; if(right <= *n && v[right] < v[smallest]) smallest = right; if(smallest != i) { swap(v[i],v[smallest]); min_heapify(v,smallest,n); } } void build_minheap(vector<int> &v, int *size) { for(int i=(*size)/2;i>=1;i--) { min_heapify(v,i,size); } } void build_maxheap(vector<int> &v, int *size) { for(int i = (*size)/2;i>=1;i--) { max_heapify(v,i,size); } } void heap_sort(vector<int> &v, int *size) { int n = *size; build_maxheap(v,size); for(int i=n;i>=2;i--) { swap(v[1],v[i]); n--; max_heapify(v,1,&n); } } int main() { cout<<"Enter the number of elements to store in the heap"<<endl; int size; cin>>size; vector<int> heap(size+1); for(int i=1;i<=size;i++) { cin>>heap[i]; } cout<<"Heap Sort:"<<endl; heap_sort(heap,&size); for(int i=1;i<=size;i++) { cout<<heap[i]<<" "; } cout<<endl; cout<<"Max Heap:"<<endl; build_maxheap(heap, &size); for(int i=1;i<=size;i++) { cout<<heap[i]<<" "; } cout<<endl; cout<<"Min Heap:"<<endl; build_minheap(heap, &size); for(int i=1;i<=size;i++) { cout<<heap[i]<<" "; } cout<<endl; return 0; }
15.537037
65
0.573897
453a1e6a515d4a67d7d37444149865b65fb7a952
4,785
cpp
C++
idlib-math/tests/idlib/tests/math/constants.cpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
1
2021-07-30T14:02:43.000Z
2021-07-30T14:02:43.000Z
idlib-math/tests/idlib/tests/math/constants.cpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
null
null
null
idlib-math/tests/idlib/tests/math/constants.cpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
2
2017-01-27T16:53:08.000Z
2017-08-27T07:28:43.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // // Idlib: A C++ utility library // Copyright (C) 2017-2018 Michael Heilmann // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // /////////////////////////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "idlib/math.hpp" namespace idlib::tests { TEST(constants, pi_s) { auto x = idlib::pi<single>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f); } TEST(constants, two_pi_s) { auto x = idlib::two_pi<single>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 2.0f * 3.1415926535897932384626433832795f); } TEST(constants, inv_pi_s) { auto x = idlib::inv_pi<single>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 1.0f / 3.1415926535897932384626433832795f); // GoogleTest tolerance is four ULP, ours was two ULP. } TEST(constants, inv_two_pi_s) { auto x = idlib::inv_two_pi<single>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 1.0f / (2.0f * 3.1415926535897932384626433832795f)); } TEST(constants, pi_over_two_s) { auto x = idlib::pi_over<single, 2>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f / 2.0f); } TEST(constants, pi_over_four_s) { auto x = idlib::pi_over<single, 4>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f / 4.0f); } TEST(constants, pi_d) { auto x = idlib::pi<double>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795); } TEST(constants, two_pi_d) { auto x = idlib::two_pi<double>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 2.0 * 3.1415926535897932384626433832795); } TEST(constants, inv_pi_d) { auto x = idlib::inv_pi<double>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 1.0 / 3.1415926535897932384626433832795); } TEST(constants, inv_two_pi_d) { auto x = idlib::inv_two_pi<double>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 1.0 / (2.0 * 3.1415926535897932384626433832795)); } TEST(constants, pi_over_two_d) { auto x = idlib::pi_over<double, 2>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795 / 2.0); } TEST(constants, pi_over_four_d) { auto x = idlib::pi_over<double, 4>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795 / 4.0); } TEST(constants, sqrt_two_s) { auto x = idlib::sqrt_two<single>(); ASSERT_TRUE(!std::isnan(x)); ASSERT_TRUE(!std::isinf(x)); ASSERT_FLOAT_EQ(x, std::sqrt(2.0f)); } TEST(constants, inv_sqrt_two_s) { auto x = idlib::inv_sqrt_two<single>(); auto y = 1.0f / std::sqrt(2.0f); ASSERT_TRUE(!std::isnan(x) && !std::isnan(y)); ASSERT_TRUE(!std::isinf(x) && !std::isinf(y)); ASSERT_TRUE(0.0 < x && 0.0 < y); ASSERT_FLOAT_EQ(x, y); } TEST(constants, sqrt_two_d) { auto x = idlib::sqrt_two<double>(); auto y = std::sqrt(2.0); ASSERT_TRUE(!std::isnan(x) && !std::isnan(y)); ASSERT_TRUE(!std::isinf(x) && !std::isinf(y)); ASSERT_TRUE(0.0 < x && 0.0 < y); ASSERT_FLOAT_EQ(x, y); } TEST(constants, inv_sqrt_two_d) { double x = idlib::inv_sqrt_two<double>(); double y = 1.0 / std::sqrt(2.0); ASSERT_TRUE(!std::isnan(x) && !std::isnan(y)); ASSERT_TRUE(!std::isinf(x) && !std::isinf(y)); ASSERT_TRUE(0.0 < x && 0.0 < y); ASSERT_FLOAT_EQ(x, y); } } // namespace idlib::tests
29
121
0.63908
453a2e4418602f71031fee4718f9682dd556d6c0
446
hpp
C++
include/lua_object.hpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
3
2017-10-02T03:18:59.000Z
2020-11-01T09:21:28.000Z
include/lua_object.hpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
2
2019-04-06T21:48:08.000Z
2020-05-22T23:38:54.000Z
include/lua_object.hpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
1
2017-07-17T20:58:26.000Z
2017-07-17T20:58:26.000Z
#ifndef HPP_LUA_OBJECT #define HPP_LUA_OBJECT #include <string> #include <memory> #include "xd/vendor/sol/forward.hpp" class Lua_Object { public: Lua_Object(); virtual ~Lua_Object(); void set_lua_property(const std::string& name, sol::stack_object value); sol::main_object get_lua_property(const std::string& name); private: struct Impl; friend struct Impl; std::unique_ptr<Impl> pimpl; }; #endif
22.3
77
0.690583
453a31f903a11270acdc2a5ad22af96280f0cdc3
838
cpp
C++
UVA/UVA11340.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
UVA/UVA11340.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
UVA/UVA11340.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <string> #include <map> using namespace std; typedef long long ll; int main(){ map<char, int> charPrice; char artLine[10100]; int T; scanf("%d\n", &T); int N; ll totalCents; while(T--){ totalCents=0; charPrice.clear(); scanf("%d\n", &N); char c; int val; while(N--){ scanf("%c %d\n", &c, &val); charPrice[c]=val; } scanf("%d\n", &N); while(N--){ gets(artLine); string line(artLine); for(char c: line){ totalCents+=charPrice[c]; } } printf("%.2f$\n", totalCents/100.0 ); } return 0; }
23.942857
52
0.387828
453cb5d3bf24c54030f48b5001b55ae381b4d385
507
cc
C++
libcef/sqlite_diagnostics_stub.cc
svn2github/cef1
61d1537c697bec6265e02c9e9bb4c416b7b22db5
[ "BSD-3-Clause" ]
18
2015-07-11T03:16:54.000Z
2019-01-19T12:10:38.000Z
libcef/sqlite_diagnostics_stub.cc
svn2github/cef
61d1537c697bec6265e02c9e9bb4c416b7b22db5
[ "BSD-3-Clause" ]
2
2019-01-14T00:10:11.000Z
2019-02-03T08:19:11.000Z
libcef/sqlite_diagnostics_stub.cc
svn2github/cef1
61d1537c697bec6265e02c9e9bb4c416b7b22db5
[ "BSD-3-Clause" ]
9
2015-01-08T01:07:25.000Z
2018-03-05T03:52:04.000Z
// Copyright (c) 2012 The Chromium Embedded Framework 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 "content/public/common/url_constants.h" namespace chrome { // Used by ClearOnExitPolicy const char kHttpScheme[] = "http"; const char kHttpsScheme[] = "https"; } // namespace chrome namespace content { // Used by ClearOnExitPolicy const char kStandardSchemeSeparator[] = "://"; } // namespace content
24.142857
80
0.737673
453d0e2d0c29f82be0ecfb636cb3150dbe88e579
1,000
cpp
C++
tools/EncoderTemplate/Encoder.cpp
EmilianC/Jewel3D
ce11aa686ab35d4989f018c948b26abed6637d77
[ "MIT" ]
30
2017-02-02T01:57:13.000Z
2020-07-04T04:38:20.000Z
tools/EncoderTemplate/Encoder.cpp
EmilianC/Jewel3D
ce11aa686ab35d4989f018c948b26abed6637d77
[ "MIT" ]
null
null
null
tools/EncoderTemplate/Encoder.cpp
EmilianC/Jewel3D
ce11aa686ab35d4989f018c948b26abed6637d77
[ "MIT" ]
10
2017-07-10T01:31:54.000Z
2020-01-13T20:38:57.000Z
#include "Encoder.h" #define CURRENT_VERSION 1 Encoder::Encoder() : gem::Encoder(CURRENT_VERSION) { } gem::ConfigTable Encoder::GetDefault() const { gem::ConfigTable defaultConfig; defaultConfig.SetValue("version", CURRENT_VERSION); // Any default values for a new asset can be added to metadata here. return defaultConfig; } bool Encoder::Validate(const gem::ConfigTable& metadata, unsigned loadedVersion) const { switch (loadedVersion) { case 1: // Check the presence of your metadata fields here. // Also ensure that they have correct values. //... if (metadata.GetSize() != 1) { gem::Error("Incorrect number of value entries."); return false; } } return true; } bool Encoder::Convert(std::string_view source, std::string_view destination, const gem::ConfigTable& metadata) const { // Load the source file and output the built data to the destination folder. // The conversion should be done using the properties inside the metadata. //... return true; }
21.276596
116
0.725
45423747d3b937f5418714dac6ac022f087f6b9e
3,742
cpp
C++
src/FEM/FEM1DApp.cpp
Jerry-Shen0527/Numerical
0bd6b630ac450caa0642029792ab348867d2390d
[ "MIT" ]
null
null
null
src/FEM/FEM1DApp.cpp
Jerry-Shen0527/Numerical
0bd6b630ac450caa0642029792ab348867d2390d
[ "MIT" ]
null
null
null
src/FEM/FEM1DApp.cpp
Jerry-Shen0527/Numerical
0bd6b630ac450caa0642029792ab348867d2390d
[ "MIT" ]
null
null
null
#include <FEM/FEM1DApp.hpp> Float StaticFEM1DApp::GradientSelfInnerProduct(int i, int j) { std::vector<int> i_id, j_id; auto i_mesh = IdxToMesh(i, i_id); auto j_mesh = IdxToMesh(j, j_id); Float ret = 0; for (int a = 0; a < i_mesh.size(); ++a) { for (int b = 0; b < j_mesh.size(); ++b) { if (i_mesh[a] == j_mesh[b]) { auto sub_interval = interval.SubInterval(i_mesh[a]); ret += WeightedL2InnerProduct(sub_interval.remap(ShapeFunctions[i_id[a]]), sub_interval.remap(ShapeFunctionGradients[j_id[b]], 1.0 / sub_interval.length()), b_func, sub_interval); } } } return ret; } Float StaticFEM1DApp::GradientInnerProduct(int i, int j) { std::vector<int> i_id, j_id; auto i_mesh = IdxToMesh(i, i_id); auto j_mesh = IdxToMesh(j, j_id); Float ret = 0; for (int a = 0; a < i_mesh.size(); ++a) { for (int b = 0; b < j_mesh.size(); ++b) { if (i_mesh[a] == j_mesh[b]) { auto sub_interval = interval.SubInterval(i_mesh[a]); ret += WeightedL2InnerProduct( sub_interval.remap(ShapeFunctionGradients[i_id[a]], 1.0 / sub_interval.length()), sub_interval.remap(ShapeFunctionGradients[j_id[b]], 1.0 / sub_interval.length()), d_func, sub_interval); } } } return ret; } Float StaticFEM1DApp::SelfInnerProduct(int i, int j) { std::vector<int> i_id, j_id; auto i_mesh = IdxToMesh(i, i_id); auto j_mesh = IdxToMesh(j, j_id); Float ret = 0; for (int a = 0; a < i_mesh.size(); ++a) { for (int b = 0; b < j_mesh.size(); ++b) { if (i_mesh[a] == j_mesh[b]) { auto sub_interval = interval.SubInterval(i_mesh[a]); ret += WeightedL2InnerProduct(sub_interval.remap(ShapeFunctions[i_id[a]]), sub_interval.remap(ShapeFunctions[j_id[b]]), c_func, sub_interval); } } } return ret; } Float StaticFEM1DApp::RHSInnerProduct(int i) { std::vector<int> func_id; auto i_mesh = IdxToMesh(i, func_id); Float ret = 0; for (int a = 0; a < func_id.size(); ++a) { auto sub_interval = interval.SubInterval(i_mesh[a]); ret += L2InnerProduct(sub_interval.remap(ShapeFunctions[func_id[a]]), RHS_func, sub_interval); } return ret; } std::vector<int> StaticFEM1DApp::RelatedFuncIdx(int idx) { std::vector<int> ret; std::vector<int> foo_id; auto MeshIds = IdxToMesh(idx, foo_id); std::set<int> set_ret; for (auto mesh_id : MeshIds) { for (int i = 0; i < ShapeFunctions.size(); ++i) { int idx; if (MeshToIdx(mesh_id, i, idx)) { set_ret.emplace(idx); } } } ret.assign(set_ret.begin(), set_ret.end()); return ret; } Float StaticFEM1DApp::Value(Float x) { if (mat_size == 0) { return 0; } Float ret = 0; for (int i = 0; i < interval.GetPartitionCount(); ++i) { auto sub_interval = interval.SubInterval(i); if (sub_interval.Inside(x)) { for (int j = 0; j < ShapeFunctions.size(); ++j) { int idx; if (MeshToIdx(i, j, idx)) { ret += sub_interval.remap(ShapeFunctions[j])(x) * rst(idx); } } } } return ret; } std::function<Float(Float)> LagrangianBase(int N, int i) { std::vector<Point2d> points(N + 1); Float h = 1.0 / N; for (int i = 0; i <= N; ++i) { points[i] = Point2d(i * h, 0); } points[i] = Point2d(i * h, 1.0); return LagrangianPolynomial(points); } std::function<Float(Float)> LagrangianBaseDerivative(int N, int i) { return [=](Float x) { Float ret = 0; for (int missing = 0; missing <= N; ++missing) { if (missing != i) { std::vector<Point2d> points; Float h = 1.0 / N; for (int j = 0; j <= N; ++j) if (j != missing) if (j == i) points.emplace_back(j * h, 1.0); else points.emplace_back(j * h, 0.0); ret += LagrangianPolynomial(points)(x) / (h * (i - missing)); } } return ret; }; }
21.022472
96
0.617584
45462edbf1008c8ccc83843d664762d8e82e0909
2,396
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_PrintNsFuncDefn.cpp // #include "smtc_PrintNsFuncDefn.h" // semantic #include "smtc_FuncDefn.h" #include "smtc_IsNameQual.h" #include "smtc_IsNsEnclUnmd.h" #include "smtc_Output.h" #include "smtc_PrintFuncDefn.h" // config #include "conf_Config.h" #define LZZ_INLINE inline namespace { using namespace smtc; } namespace { struct Printer { FuncDefnPtr const & func_defn; NsPtr const & ns; bool is_decl; void printDecl (FilePtr const & file); void printDefn (FilePtr const & file, SectionKind skind = BODY_SECTION); public: explicit Printer (FuncDefnPtr const & func_defn, NsPtr const & ns); ~ Printer (); }; } namespace { void Printer::printDecl (FilePtr const & file) { PrintFuncDecl printer; printer.is_decl = is_decl; printer.not_inline = true; printer.print (file, DECLARATION_SECTION, func_defn, ns); is_decl = false; } } namespace { void Printer::printDefn (FilePtr const & file, SectionKind skind) { PrintFuncDefn printer; printer.is_decl = is_decl; printer.print (file, skind, func_defn, ns); } } namespace { LZZ_INLINE Printer::Printer (FuncDefnPtr const & func_defn, NsPtr const & ns) : func_defn (func_defn), ns (ns), is_decl (true) {} } namespace { Printer::~ Printer () {} } namespace smtc { void printNsFuncDefn (Output & out, FuncDefnPtr const & func_defn, NsPtr const & ns) { Printer printer (func_defn, ns); bool is_qual = isNameQual (func_defn->getName ()); if (func_defn->isStatic () || isNsEnclUnmd (ns)) { if (! is_qual) { printer.printDecl (out.getSrcFile ()); } printer.printDefn (out.getSrcFile ()); } else { if (! is_qual) { printer.printDecl (out.getHdrFile ()); } if (func_defn->isInline ()) { if (conf::getOptionValue (conf::opt_inl_inl)) { printer.printDefn (out.getHdrFile (), INLINE_BODY_SECTION); printer.printDefn (out.getSrcFile (), INLINE_BODY_SECTION); } else if (conf::getOptionValue (conf::opt_inl)) { printer.printDefn (out.getInlFile ()); } else { printer.printDefn (out.getHdrFile ()); } } else { printer.printDefn (out.getSrcFile ()); } } } } #undef LZZ_INLINE
22.185185
86
0.613523
454c4fa14854858d2b69b4484640aceeebf81c39
33,476
hpp
C++
rosidl_typesupport_introspection_tests/test/introspection_libraries_under_test.hpp
Greek64/rosidl
1612b07501ebb712ff7893e0cebc2138813d139c
[ "Apache-2.0" ]
null
null
null
rosidl_typesupport_introspection_tests/test/introspection_libraries_under_test.hpp
Greek64/rosidl
1612b07501ebb712ff7893e0cebc2138813d139c
[ "Apache-2.0" ]
null
null
null
rosidl_typesupport_introspection_tests/test/introspection_libraries_under_test.hpp
Greek64/rosidl
1612b07501ebb712ff7893e0cebc2138813d139c
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef INTROSPECTION_LIBRARIES_UNDER_TEST_HPP_ #define INTROSPECTION_LIBRARIES_UNDER_TEST_HPP_ #include <rcutils/macros.h> #include <rosidl_typesupport_interface/macros.h> #include <rosidl_typesupport_introspection_c/message_introspection.h> #include <rosidl_typesupport_introspection_c/service_introspection.h> #include <memory> #include <rosidl_typesupport_introspection_cpp/message_introspection.hpp> #include <rosidl_typesupport_introspection_cpp/service_introspection.hpp> #include "rosidl_typesupport_introspection_tests/msg/arrays.h" #include "rosidl_typesupport_introspection_tests/msg/basic_types.h" #include "rosidl_typesupport_introspection_tests/msg/bounded_sequences.h" #include "rosidl_typesupport_introspection_tests/msg/constants.h" #include "rosidl_typesupport_introspection_tests/msg/defaults.h" #include "rosidl_typesupport_introspection_tests/msg/empty.h" #include "rosidl_typesupport_introspection_tests/msg/multi_nested.h" #include "rosidl_typesupport_introspection_tests/msg/strings.h" #include "rosidl_typesupport_introspection_tests/msg/unbounded_sequences.h" #include "rosidl_typesupport_introspection_tests/srv/arrays.h" #include "rosidl_typesupport_introspection_tests/srv/basic_types.h" #include "rosidl_typesupport_introspection_tests/srv/empty.h" #include "rosidl_typesupport_introspection_tests/msg/arrays.hpp" #include "rosidl_typesupport_introspection_tests/msg/basic_types.hpp" #include "rosidl_typesupport_introspection_tests/msg/bounded_sequences.hpp" #include "rosidl_typesupport_introspection_tests/msg/constants.hpp" #include "rosidl_typesupport_introspection_tests/msg/defaults.hpp" #include "rosidl_typesupport_introspection_tests/msg/empty.hpp" #include "rosidl_typesupport_introspection_tests/msg/multi_nested.hpp" #include "rosidl_typesupport_introspection_tests/msg/strings.hpp" #include "rosidl_typesupport_introspection_tests/msg/unbounded_sequences.hpp" #include "rosidl_typesupport_introspection_tests/srv/arrays.hpp" #include "rosidl_typesupport_introspection_tests/srv/basic_types.hpp" #include "rosidl_typesupport_introspection_tests/srv/empty.hpp" #include "rosidl_typesupport_introspection_tests/fixtures.hpp" #include "rosidl_typesupport_introspection_tests/helpers.hpp" #include "rosidl_typesupport_introspection_tests/libraries.hpp" #include "rosidl_typesupport_introspection_tests/type_traits.hpp" // Extra C++ APIs to homogeneize access to test interfaces in C and C++ DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, Arrays) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, BasicTypes) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, BoundedSequences) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, Constants) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, Defaults) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, Empty) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, MultiNested) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, Strings) DEFINE_CXX_API_FOR_C_MESSAGE(rosidl_typesupport_introspection_tests, msg, UnboundedSequences) DEFINE_CXX_API_FOR_C_SERVICE(rosidl_typesupport_introspection_tests, srv, Arrays) DEFINE_CXX_API_FOR_C_SERVICE(rosidl_typesupport_introspection_tests, srv, BasicTypes) DEFINE_CXX_API_FOR_C_SERVICE(rosidl_typesupport_introspection_tests, srv, Empty) namespace rosidl_typesupport_introspection_tests { // Typesupport library definition for introspection of test interfaces in C struct IntrospectionCTypeSupportTestLibrary { using MessageDescriptorT = rosidl_typesupport_introspection_c__MessageMembers; using ServiceDescriptorT = rosidl_typesupport_introspection_c__ServiceMembers; using MemberDescriptorT = rosidl_typesupport_introspection_c__MessageMember; static constexpr const char * name = RCUTILS_STRINGIFY( ROSIDL_TYPESUPPORT_INTERFACE__LIBRARY_NAME( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests)); static constexpr const char * identifier = "rosidl_typesupport_introspection_c"; static constexpr const char * messages_namespace = "rosidl_typesupport_introspection_tests__msg"; static constexpr const char * services_namespace = "rosidl_typesupport_introspection_tests__srv"; static constexpr const char * actions_namespace = "rosidl_typesupport_introspection_tests__action"; static constexpr const MessageTypeSupportSymbolRecord messages[] = { MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Arrays), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, BasicTypes), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, BoundedSequences), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Constants), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Defaults), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Empty), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Strings), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, MultiNested), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, UnboundedSequences) }; static constexpr const ServiceTypeSupportSymbolRecord services[] = { SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, Arrays), SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, BasicTypes), SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, Empty) }; // static constexpr const ActionTypeSupportSymbolRecord actions[] = { // ACTION_TYPESUPPORT_SYMBOL_RECORD( // rosidl_typesupport_introspection_c, // rosidl_typesupport_introspection_tests, action, Fibonacci) // }; }; // Traits to aid introspection of tests interfaces in C template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__Arrays> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Arrays); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__BasicTypes> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, BasicTypes); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__BoundedSequences> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, BoundedSequences); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__Constants> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Constants); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__Defaults> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Defaults); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__Empty> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Empty); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__MultiNested> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, MultiNested); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__Strings> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, Strings); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__msg__UnboundedSequences> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, msg, UnboundedSequences); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__srv__Arrays> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, Arrays); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__srv__BasicTypes> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, BasicTypes); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests__srv__Empty> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_c, rosidl_typesupport_introspection_tests, srv, Empty); using TypeSupportLibraryT = IntrospectionCTypeSupportTestLibrary; }; // Examples of test interfaces in C, useful in test fixtures template<> struct Example<rosidl_typesupport_introspection_tests__msg__Arrays> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__Arrays, std::function<void (rosidl_typesupport_introspection_tests__msg__Arrays *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__Arrays * message) { rosidl_typesupport_introspection_tests__msg__Arrays__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__Arrays, deleter}; if (!rosidl_typesupport_introspection_tests__msg__Arrays__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_values[2] = true; message->float64_values[1] = 1.234; message->uint16_values[0] = 1234u; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__msg__BasicTypes> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__BasicTypes, std::function<void (rosidl_typesupport_introspection_tests__msg__BasicTypes *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__BasicTypes * message) { rosidl_typesupport_introspection_tests__msg__BasicTypes__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__BasicTypes, deleter}; if (!rosidl_typesupport_introspection_tests__msg__BasicTypes__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_value = true; message->float32_value = 1.234f; message->uint16_value = 1234u; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__msg__BoundedSequences> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__BoundedSequences, std::function<void (rosidl_typesupport_introspection_tests__msg__BoundedSequences *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__BoundedSequences * message) { rosidl_typesupport_introspection_tests__msg__BoundedSequences__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__BoundedSequences, deleter}; if ( !rosidl_typesupport_introspection_tests__msg__BoundedSequences__init(message.get()) || !rosidl_runtime_c__boolean__Sequence__init(&message->bool_values, 1) || !rosidl_runtime_c__double__Sequence__init(&message->float64_values, 1) || !rosidl_runtime_c__int64__Sequence__init(&message->int64_values, 1)) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_values.data[0] = true; message->float64_values.data[0] = 1.234; message->int64_values.data[0] = 12341234ul; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__msg__MultiNested> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__MultiNested, std::function<void (rosidl_typesupport_introspection_tests__msg__MultiNested *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__MultiNested * message) { rosidl_typesupport_introspection_tests__msg__MultiNested__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__MultiNested, deleter}; if (!rosidl_typesupport_introspection_tests__msg__MultiNested__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->array_of_arrays[1].int32_values[0] = -1234; if (!rosidl_typesupport_introspection_tests__msg__Arrays__Sequence__init( &message->unbounded_sequence_of_arrays, 1u)) { throw std::runtime_error(rcutils_get_error_string().str); } message->unbounded_sequence_of_arrays.data[0].char_values[2] = 'a'; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__msg__Strings> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__Strings, std::function<void (rosidl_typesupport_introspection_tests__msg__Strings *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__Strings * message) { rosidl_typesupport_introspection_tests__msg__Strings__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__Strings, deleter}; if ( !rosidl_typesupport_introspection_tests__msg__Strings__init(message.get()) || !rosidl_runtime_c__String__assign(&message->string_value, "foo") || !rosidl_runtime_c__String__assign(&message->bounded_string_value, "bar")) { throw std::runtime_error(rcutils_get_error_string().str); } return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__msg__UnboundedSequences> { static auto Make() { using ReturnT = std::unique_ptr< rosidl_typesupport_introspection_tests__msg__UnboundedSequences, std::function<void (rosidl_typesupport_introspection_tests__msg__UnboundedSequences *)>>; auto deleter = [](rosidl_typesupport_introspection_tests__msg__UnboundedSequences * message) { rosidl_typesupport_introspection_tests__msg__UnboundedSequences__fini(message); delete message; }; ReturnT message{new rosidl_typesupport_introspection_tests__msg__UnboundedSequences, deleter}; if ( !rosidl_typesupport_introspection_tests__msg__UnboundedSequences__init(message.get()) || !rosidl_runtime_c__boolean__Sequence__init(&message->bool_values, 1) || !rosidl_runtime_c__double__Sequence__init(&message->float64_values, 1) || !rosidl_runtime_c__int64__Sequence__init(&message->int64_values, 1)) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_values.data[0] = true; message->float64_values.data[0] = 1.234; message->int64_values.data[0] = 12341234ul; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__srv__Arrays> { static auto MakeRequest() { using MessageT = rosidl_typesupport_introspection_tests__srv__Arrays_Request; auto deleter = [](MessageT * message) { rosidl_typesupport_introspection_tests__srv__Arrays_Request__fini(message); delete message; }; using ReturnT = std::unique_ptr<MessageT, std::function<void (MessageT *)>>; ReturnT message{new MessageT, deleter}; if (!rosidl_typesupport_introspection_tests__srv__Arrays_Request__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_values[2] = true; message->float64_values[1] = 1.234; message->uint16_values[0] = 1234u; return message; } static auto MakeResponse() { using MessageT = rosidl_typesupport_introspection_tests__srv__Arrays_Response; auto deleter = [](MessageT * message) { rosidl_typesupport_introspection_tests__srv__Arrays_Response__fini(message); delete message; }; using ReturnT = std::unique_ptr<MessageT, std::function<void (MessageT *)>>; ReturnT message{new MessageT, deleter}; if (!rosidl_typesupport_introspection_tests__srv__Arrays_Response__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->byte_values[1] = 0xAB; message->char_values[0] = 'b'; message->int8_values[2] = 123; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests__srv__BasicTypes> { static auto MakeRequest() { using MessageT = rosidl_typesupport_introspection_tests__srv__BasicTypes_Request; auto deleter = [](MessageT * message) { rosidl_typesupport_introspection_tests__srv__BasicTypes_Request__fini(message); delete message; }; using ReturnT = std::unique_ptr<MessageT, std::function<void (MessageT *)>>; ReturnT message{new MessageT, deleter}; if (!rosidl_typesupport_introspection_tests__srv__BasicTypes_Request__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->char_value = 'c'; message->uint32_value = 1234u; message->float32_value = 1.234f; if (!rosidl_runtime_c__String__assign(&message->string_value, "foo")) { throw std::runtime_error(rcutils_get_error_string().str); } return message; } static auto MakeResponse() { using MessageT = rosidl_typesupport_introspection_tests__srv__BasicTypes_Response; auto deleter = [](MessageT * message) { rosidl_typesupport_introspection_tests__srv__BasicTypes_Response__fini(message); delete message; }; using ReturnT = std::unique_ptr<MessageT, std::function<void (MessageT *)>>; ReturnT message{new MessageT, deleter}; if (!rosidl_typesupport_introspection_tests__srv__BasicTypes_Response__init(message.get())) { throw std::runtime_error(rcutils_get_error_string().str); } message->bool_value = true; message->byte_value = 0xAB; message->float64_value = -1.234; if (!rosidl_runtime_c__String__assign(&message->string_value, "bar")) { throw std::runtime_error(rcutils_get_error_string().str); } return message; } }; // Typesupport library definition for introspection of test interfaces in C++ struct IntrospectionCppTypeSupportTestLibrary { using MessageDescriptorT = rosidl_typesupport_introspection_cpp::MessageMembers; using ServiceDescriptorT = rosidl_typesupport_introspection_cpp::ServiceMembers; using MemberDescriptorT = rosidl_typesupport_introspection_cpp::MessageMember; static constexpr const char * name = RCUTILS_STRINGIFY( ROSIDL_TYPESUPPORT_INTERFACE__LIBRARY_NAME( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests)); static constexpr const char * identifier = "rosidl_typesupport_introspection_cpp"; static constexpr const char * messages_namespace = "rosidl_typesupport_introspection_tests::msg"; static constexpr const char * services_namespace = "rosidl_typesupport_introspection_tests::srv"; static constexpr const char * actions_namespace = "rosidl_typesupport_introspection_tests::action"; static constexpr const MessageTypeSupportSymbolRecord messages[] = { MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Arrays), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, BasicTypes), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, BoundedSequences), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Constants), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Defaults), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Empty), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, MultiNested), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Strings), MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, UnboundedSequences) }; static constexpr const ServiceTypeSupportSymbolRecord services[] = { SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, Arrays), SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, BasicTypes), SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, Empty) }; // static constexpr const ActionTypeSupportSymbolRecord actions[] = { // ACTION_TYPESUPPORT_SYMBOL_RECORD( // rosidl_typesupport_introspection_cpp, // rosidl_typesupport_introspection_tests, action, Fibonacci) // }; }; // Traits to aid introspection of `rosidl_typesupport_introspection_tests` package interfaces in C++ template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::Arrays> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Arrays); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::BasicTypes> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, BasicTypes); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::BoundedSequences> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, BoundedSequences); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::Constants> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Constants); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::Defaults> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Defaults); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::Empty> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Empty); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::MultiNested> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, MultiNested); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::Strings> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, Strings); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::msg::UnboundedSequences> { static constexpr const MessageTypeSupportSymbolRecord typesupport = MESSAGE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, msg, UnboundedSequences); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::srv::Arrays> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, Arrays); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::srv::BasicTypes> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, BasicTypes); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; template<> struct introspection_traits<rosidl_typesupport_introspection_tests::srv::Empty> { static constexpr const ServiceTypeSupportSymbolRecord typesupport = SERVICE_TYPESUPPORT_SYMBOL_RECORD( rosidl_typesupport_introspection_cpp, rosidl_typesupport_introspection_tests, srv, Empty); using TypeSupportLibraryT = IntrospectionCppTypeSupportTestLibrary; }; // Examples of test interfaces in C++, useful in test fixtures template<> struct Example<rosidl_typesupport_introspection_tests::msg::Arrays> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::Arrays> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::Arrays>(); message->bool_values[2] = true; message->float64_values[1] = 1.234; message->uint16_values[0] = 1234u; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::msg::BasicTypes> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::BasicTypes> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::BasicTypes>(); message->bool_value = true; message->float32_value = 1.234f; message->uint16_value = 1234u; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::msg::BoundedSequences> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::BoundedSequences> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::BoundedSequences>(); message->bool_values.push_back(true); message->float64_values.push_back(1.234); message->int64_values.push_back(12341234ul); return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::msg::MultiNested> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::MultiNested> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::MultiNested>(); message->array_of_arrays[1].int32_values[0] = -1234; message->unbounded_sequence_of_arrays.emplace_back(); message->unbounded_sequence_of_arrays[0].char_values[2] = 'a'; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::msg::Strings> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::Strings> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::Strings>(); message->string_value = "foo"; message->bounded_string_value = "bar"; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::msg::UnboundedSequences> { static std::unique_ptr<rosidl_typesupport_introspection_tests::msg::UnboundedSequences> Make() { auto message = std::make_unique<rosidl_typesupport_introspection_tests::msg::UnboundedSequences>(); message->bool_values.push_back(true); message->float64_values.push_back(1.234); message->int64_values.push_back(12341234ul); return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::srv::Arrays> { static auto MakeRequest() { using MessageT = rosidl_typesupport_introspection_tests::srv::Arrays::Request; auto message = std::make_unique<MessageT>(); message->bool_values[2] = true; message->float64_values[1] = 1.234; message->uint16_values[0] = 1234u; return message; } static auto MakeResponse() { using MessageT = rosidl_typesupport_introspection_tests::srv::Arrays::Response; auto message = std::make_unique<MessageT>(); message->byte_values[1] = 0xAB; message->char_values[0] = 'b'; message->int8_values[2] = 123; return message; } }; template<> struct Example<rosidl_typesupport_introspection_tests::srv::BasicTypes> { static auto MakeRequest() { using MessageT = rosidl_typesupport_introspection_tests::srv::BasicTypes::Request; auto message = std::make_unique<MessageT>(); message->char_value = 'c'; message->uint32_value = 1234u; message->float32_value = 1.234f; message->string_value = "foo"; return message; } static auto MakeResponse() { using MessageT = rosidl_typesupport_introspection_tests::srv::BasicTypes::Response; auto message = std::make_unique<MessageT>(); message->bool_value = true; message->byte_value = 0xAB; message->float64_value = -1.234; message->string_value = "bar"; return message; } }; } // namespace rosidl_typesupport_introspection_tests #endif // INTROSPECTION_LIBRARIES_UNDER_TEST_HPP_
39.663507
100
0.802814
454d3b48038a9b52fc0dc94df440bdb4ea5d76e7
8,056
cpp
C++
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
31
2018-04-20T13:47:38.000Z
2021-12-26T04:32:24.000Z
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
25
2018-02-19T17:15:32.000Z
2020-01-05T01:51:00.000Z
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
5
2018-09-25T18:37:23.000Z
2021-01-21T16:26:16.000Z
// // chaoticOscillator.cpp // example-basic // // Created by Eduard Frigola Bagué on 02/03/2020. // #include "chaoticOscillator.h" void chaoticOscillator::setup(){ color = ofColor(0, 200, 255); oldPhasor = vector<float>(1, 0); seedChanged = vector<bool>(true); baseChOsc.resize(1); result.resize(1); listeners.push(phaseOffset_Param.newListener([this](vector<float> &val){ if(val.size() != baseChOsc.size() && index_Param->size() == 1 && phasorIn->size() == 1){ resize(val.size()); } for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].phaseOffset_Param = getValueForPosition(val, i); } })); listeners.push(randomAdd_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].randomAdd_Param = getValueForPosition(val, i); } })); listeners.push(scale_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].scale_Param = getValueForPosition(val, i); } })); listeners.push(offset_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].offset_Param = getValueForPosition(val, i); } })); listeners.push(pow_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].pow_Param = getValueForPosition(val, i); baseChOsc[i].modulateNewRandom(); } })); listeners.push(biPow_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].biPow_Param = getValueForPosition(val, i); baseChOsc[i].modulateNewRandom(); } })); listeners.push(quant_Param.newListener([this](vector<int> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].quant_Param = getValueForPosition(val, i); baseChOsc[i].modulateNewRandom(); } })); listeners.push(pulseWidth_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].pulseWidth_Param = getValueForPosition(val, i); } })); listeners.push(skew_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].skew_Param = getValueForPosition(val, i); } })); listeners.push(amplitude_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].amplitude_Param = getValueForPosition(val, i); } })); listeners.push(invert_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].invert_Param = getValueForPosition(val, i); } })); listeners.push(roundness_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].roundness_Param = getValueForPosition(val, i); } })); listeners.push(index_Param.newListener([this](vector<float> &val){ if(val.size() != baseChOsc.size()){ resize(val.size()); } for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].setIndexNormalized(getValueForPosition(val, i)); } seedChanged = vector<bool>(baseChOsc.size(), true); })); listeners.push(customDiscreteDistribution_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].customDiscreteDistribution = val; } })); listeners.push(seed.newListener([this](vector<int> &val){ seedChanged = vector<bool>(baseChOsc.size(), true); })); listeners.push(length_Param.newListener([this](vector<float> &val){ for(int i = 0; i < baseChOsc.size(); i++){ baseChOsc[i].length_Param = getValueForPosition(val, i); } seedChanged = vector<bool>(baseChOsc.size(), true); })); addParameter(phasorIn.set("Phase", {0}, {0}, {1})); addParameter(index_Param.set("Index", {0}, {0}, {1})); addParameter(length_Param.set("Length", {1}, {0}, {100})); addParameter(phaseOffset_Param.set("Ph.Off", {0}, {0}, {1})); addParameter(roundness_Param.set("Round", {0.5}, {0}, {1})); addParameter(pulseWidth_Param.set("PulseW", {.5}, {0}, {1})); addParameter(skew_Param.set("Skew", {0}, {-1}, {1})); addParameter(pow_Param.set("Pow", {0}, {-1}, {1})); addParameter(biPow_Param.set("BiPow", {0}, {-1}, {1})); addParameter(quant_Param.set("Quant", {255}, {2}, {255})); addParameter(customDiscreteDistribution_Param.set("Dist" , {-1}, {0}, {1})); addParameter(seed.set("Seed", {-1}, {(INT_MIN+1)/2}, {(INT_MAX-1)/2})); addParameter(randomAdd_Param.set("Rnd Add", {0}, {-.5}, {.5})); addParameter(scale_Param.set("Scale", {1}, {0}, {2})); addParameter(offset_Param.set("Offset", {0}, {-1}, {1})); addParameter(amplitude_Param.set("Fader", {1}, {0}, {1})); addParameter(invert_Param.set("Invert", {0}, {0}, {1})); addOutputParameter(output.set("Output", {0}, {0}, {1})); listeners.push(phasorIn.newListener(this, &chaoticOscillator::phasorInListener)); desiredLength = 1; } void chaoticOscillator::resize(int newSize){ baseChOsc.resize(newSize); result.resize(newSize); phaseOffset_Param = phaseOffset_Param; roundness_Param = roundness_Param; pulseWidth_Param = pulseWidth_Param; skew_Param = skew_Param; randomAdd_Param = randomAdd_Param; scale_Param = scale_Param; offset_Param = offset_Param; pow_Param = pow_Param; biPow_Param = biPow_Param; quant_Param = quant_Param; amplitude_Param = amplitude_Param; invert_Param = invert_Param; customDiscreteDistribution_Param = customDiscreteDistribution_Param; seed = seed; seedChanged = vector<bool>(baseChOsc.size(), true); length_Param.setMax({static_cast<float>(newSize)}); string name = length_Param.getName(); parameterChangedMinMax.notify(name); if(length_Param->size() == 1){ if(desiredLength != -1 && desiredLength <= newSize){ length_Param = vector<float>(1, desiredLength); desiredLength = -1; } else{ if(length_Param->at(0) > length_Param.getMax()[0]){ desiredLength = length_Param->at(0); length_Param = vector<float>(1, length_Param.getMax()[0]); } length_Param = length_Param; } } }; void chaoticOscillator::presetRecallBeforeSettingParameters(ofJson &json){ if(json.count("Length") == 1){ desiredLength = (json["Length"]); } } void chaoticOscillator::phasorInListener(vector<float> &phasor){ if(phasor.size() != baseChOsc.size() && phasor.size() != 1 && index_Param->size() == 1){ resize(phasor.size()); } if(accumulate(seedChanged.begin(), seedChanged.end(), 0) != 0){ for(int i = 0; i < baseChOsc.size(); i++){ if(seedChanged[i] && getValueForPosition(phasor, i) < getValueForPosition(oldPhasor, i)){ if(getValueForPosition(seed.get(), i) == 0){ baseChOsc[i].deactivateSeed(); }else{ if(seed->size() == 1 && seed->at(0) < 0){ baseChOsc[i].setSeed(seed->at(0) - (10*getValueForPosition(index_Param.get(), i)*baseChOsc.size())); }else{ baseChOsc[i].setSeed(getValueForPosition(seed.get(), i)); baseChOsc[i].computeFunc(0); } } seedChanged[i] = false; } } } for(int i = 0; i < baseChOsc.size(); i++){ result[i] = baseChOsc[i].computeFunc(getValueForPosition(phasor, i)); } oldPhasor = phasor; output = result; }
39.881188
124
0.585775
4550737c359bb091ea8ee21f4d83027f6d7f4768
709
cpp
C++
main.cpp
rivergillis/sdl2-starter
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
[ "MIT" ]
null
null
null
main.cpp
rivergillis/sdl2-starter
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
[ "MIT" ]
null
null
null
main.cpp
rivergillis/sdl2-starter
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
[ "MIT" ]
null
null
null
#include "common.h" #include "sdl_viewer.h" #include "image.h" constexpr int w = 640; constexpr int h = 480; int main(void) { SDLViewer viewer("Hello World", w, h); Image img(w, h); img.SetAll({248, 240, 227}); // Honda championship white background bool quit = false; int i = 0; while (!quit) { // Animate some colorful diagonal lines. img.SetPixel(i % w, i % h, {static_cast<uint8_t>(i % 256), static_cast<uint8_t>(i*2 % 256), static_cast<uint8_t>(i*3 % 256)}); i++; viewer.SetImage(img); auto events = viewer.Update(); for (const auto& e : events) { if (e.type == SDL_QUIT) { quit = true; break; } } } return 0; }
20.852941
70
0.57969
45523fb4a50faa6e4e59570ed6c5b2e26dfd7279
3,757
hpp
C++
src/riscv_devices.hpp
msyksphinz/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
33
2015-08-23T02:45:07.000Z
2019-11-06T23:34:51.000Z
src/riscv_devices.hpp
msyksphinz-self/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
11
2015-10-11T15:52:42.000Z
2019-09-20T14:30:35.000Z
src/riscv_devices.hpp
msyksphinz/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
5
2015-02-14T10:07:44.000Z
2019-09-20T06:37:38.000Z
/* * Copyright (c) 2015, msyksphinz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <vector> #include "mem_body.hpp" #include "riscv_pe_thread.hpp" // static uint8_t DEVICE (uint64_t command) { return command >> 56; } // static uint8_t COMMAND(uint64_t command) { return command >> 48; } // static uint64_t PAYLOAD(uint64_t command) { return command << 16 >> 16; } #define DEVICE(cmd) ((cmd >> 56) & 0xff) #define COMMAND(cmd) ((cmd >> 48) & 0xff) #define PAYLOAD(cmd) (cmd & 0xffffffffffffULL) #define MAKE_COMMAND(dev, cmd, payload) (static_cast<uint64_t>(dev) << 56 | static_cast<uint64_t>(cmd) << 48 | static_cast<uint64_t>(payload) & 0x0ffff) class RiscvDevice_t { uint32_t m_dev_id; RiscvPeThread *m_pe_thread; public: virtual void HandleCommand (UDWord_t cmd) = 0; virtual void Tick() = 0; RiscvPeThread *GetPeThread() { return m_pe_thread; } RiscvDevice_t (uint32_t dev_id, RiscvPeThread *pe_thread) : m_dev_id(dev_id), m_pe_thread(pe_thread) {} virtual ~RiscvDevice_t () {} inline uint32_t GetDevId() { return m_dev_id; } }; class RiscvMMDevice_t { private: Addr_t m_base_addr; Addr_t m_size; public: RiscvPeThread *m_pe_thread; virtual MemResult Load (Addr_t addr, size_t len, Byte_t *data) = 0; virtual MemResult Store (Addr_t addr, size_t size, Byte_t *data) = 0; Addr_t GetBaseAddr () { return m_base_addr; } Addr_t GetSize () { return m_size; } RiscvMMDevice_t (RiscvPeThread *pe_thread, Addr_t base_addr, Addr_t size) { m_pe_thread = pe_thread; m_base_addr = base_addr; m_size = size; } virtual ~RiscvMMDevice_t () {} }; class RiscvDeviceList_t { private: std::vector<RiscvDevice_t*> m_devices; public: void RegisterDevice (RiscvDevice_t* dev) { m_devices.push_back(dev); } void HandleCommand (UDWord_t cmd) { if (DEVICE(cmd) >= m_devices.size()) { fprintf (stderr, "<Info: HandleCommand not found %ld>\n", DEVICE(cmd)); return; } m_devices[DEVICE(cmd)]->HandleCommand(cmd); } void Tick () { for (RiscvDevice_t *device : m_devices) { device->Tick(); } } ~RiscvDeviceList_t () { for (RiscvDevice_t *device : m_devices) { delete device; } } };
31.571429
152
0.711206
4553d6ae9ba2a19514b48790bd32758952cea8fc
9,001
cpp
C++
platform_linux.cpp
Vector35/platform-linux
fd71fca50ba193517df0f7c828d824f57fbc158f
[ "Apache-2.0" ]
null
null
null
platform_linux.cpp
Vector35/platform-linux
fd71fca50ba193517df0f7c828d824f57fbc158f
[ "Apache-2.0" ]
1
2021-06-25T18:49:42.000Z
2021-06-25T18:49:42.000Z
platform_linux.cpp
Vector35/platform-linux
fd71fca50ba193517df0f7c828d824f57fbc158f
[ "Apache-2.0" ]
null
null
null
#include "binaryninjaapi.h" using namespace BinaryNinja; using namespace std; class LinuxX86Platform: public Platform { public: LinuxX86Platform(Architecture* arch): Platform(arch, "linux-x86") { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("cdecl"); if (cc) { RegisterDefaultCallingConvention(cc); RegisterCdeclCallingConvention(cc); } cc = arch->GetCallingConventionByName("regparm"); if (cc) RegisterFastcallCallingConvention(cc); cc = arch->GetCallingConventionByName("stdcall"); if (cc) RegisterStdcallCallingConvention(cc); cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxPpc32Platform: public Platform { public: LinuxPpc32Platform(Architecture* arch, const std::string& name): Platform(arch, name) { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("svr4"); if (cc) { RegisterDefaultCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxPpc64Platform: public Platform { public: LinuxPpc64Platform(Architecture* arch, const std::string& name): Platform(arch, name) { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("svr4"); if (cc) { RegisterDefaultCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxX64Platform: public Platform { public: LinuxX64Platform(Architecture* arch): Platform(arch, "linux-x86_64") { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("sysv"); if (cc) { RegisterDefaultCallingConvention(cc); RegisterCdeclCallingConvention(cc); RegisterFastcallCallingConvention(cc); RegisterStdcallCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxArmv7Platform: public Platform { public: LinuxArmv7Platform(Architecture* arch, const std::string& name): Platform(arch, name) { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("cdecl"); if (cc) { RegisterDefaultCallingConvention(cc); RegisterCdeclCallingConvention(cc); RegisterFastcallCallingConvention(cc); RegisterStdcallCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxArm64Platform: public Platform { public: LinuxArm64Platform(Architecture* arch): Platform(arch, "linux-aarch64") { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("cdecl"); if (cc) { RegisterDefaultCallingConvention(cc); RegisterCdeclCallingConvention(cc); RegisterFastcallCallingConvention(cc); RegisterStdcallCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; class LinuxMipsPlatform: public Platform { public: LinuxMipsPlatform(Architecture* arch, const std::string& name): Platform(arch, name) { Ref<CallingConvention> cc; cc = arch->GetCallingConventionByName("o32"); if (cc) { RegisterDefaultCallingConvention(cc); RegisterCdeclCallingConvention(cc); RegisterFastcallCallingConvention(cc); RegisterStdcallCallingConvention(cc); } cc = arch->GetCallingConventionByName("linux-syscall"); if (cc) SetSystemCallConvention(cc); } }; extern "C" { BN_DECLARE_CORE_ABI_VERSION #ifndef DEMO_VERSION BINARYNINJAPLUGIN void CorePluginDependencies() { AddOptionalPluginDependency("arch_x86"); AddOptionalPluginDependency("arch_armv7"); AddOptionalPluginDependency("arch_arm64"); AddOptionalPluginDependency("arch_mips"); AddOptionalPluginDependency("arch_ppc"); } #endif #ifdef DEMO_VERSION bool LinuxPluginInit() #else BINARYNINJAPLUGIN bool CorePluginInit() #endif { Ref<Architecture> x86 = Architecture::GetByName("x86"); if (x86) { Ref<Platform> platform; platform = new LinuxX86Platform(x86); Platform::Register("linux", platform); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, x86, platform); BinaryViewType::RegisterPlatform("ELF", 3, x86, platform); } Ref<Architecture> x64 = Architecture::GetByName("x86_64"); if (x64) { Ref<Platform> platform; platform = new LinuxX64Platform(x64); Platform::Register("linux", platform); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, x64, platform); BinaryViewType::RegisterPlatform("ELF", 3, x64, platform); } Ref<Architecture> armv7 = Architecture::GetByName("armv7"); Ref<Architecture> armv7eb = Architecture::GetByName("armv7eb"); Ref<Architecture> thumb2 = Architecture::GetByName("thumb2"); Ref<Architecture> thumb2eb = Architecture::GetByName("thumb2eb"); if (armv7 && armv7eb && thumb2 && thumb2eb) { Ref<Platform> armPlatform, armebPlatform, thumbPlatform, thumbebPlatform; armPlatform = new LinuxArmv7Platform(armv7, "linux-armv7"); armebPlatform = new LinuxArmv7Platform(armv7eb, "linux-armv7eb"); thumbPlatform = new LinuxArmv7Platform(thumb2, "linux-thumb2"); thumbebPlatform = new LinuxArmv7Platform(thumb2eb, "linux-thumb2eb"); armPlatform->AddRelatedPlatform(thumb2, thumbPlatform); armebPlatform->AddRelatedPlatform(thumb2eb, thumbebPlatform); thumbPlatform->AddRelatedPlatform(armv7, armPlatform); thumbebPlatform->AddRelatedPlatform(armv7eb, armebPlatform); Platform::Register("linux", armPlatform); Platform::Register("linux", thumbPlatform); Platform::Register("linux", armebPlatform); Platform::Register("linux", thumbebPlatform); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, armv7, armPlatform); BinaryViewType::RegisterPlatform("ELF", 3, armv7, armPlatform); BinaryViewType::RegisterPlatform("ELF", 0, armv7eb, armebPlatform); BinaryViewType::RegisterPlatform("ELF", 3, armv7eb, armebPlatform); } Ref<Architecture> arm64 = Architecture::GetByName("aarch64"); if (arm64) { Ref<Platform> platform; platform = new LinuxArm64Platform(arm64); Platform::Register("linux", platform); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, arm64, platform); BinaryViewType::RegisterPlatform("ELF", 3, arm64, platform); } Ref<Architecture> ppc = Architecture::GetByName("ppc"); Ref<Architecture> ppcle = Architecture::GetByName("ppc_le"); if (ppc && ppcle) { Ref<Platform> platform; Ref<Platform> platformle; platform = new LinuxPpc32Platform(ppc, "linux-ppc32"); platformle = new LinuxPpc32Platform(ppcle, "linux-ppc32_le"); Platform::Register("linux", platform); Platform::Register("linux", platformle); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, ppc, platform); BinaryViewType::RegisterPlatform("ELF", 3, ppc, platform); BinaryViewType::RegisterPlatform("ELF", 0, ppcle, platformle); BinaryViewType::RegisterPlatform("ELF", 3, ppcle, platformle); } Ref<Architecture> ppc64 = Architecture::GetByName("ppc64"); Ref<Architecture> ppc64le = Architecture::GetByName("ppc64_le"); if (ppc64 && ppc64le) { Ref<Platform> platform; Ref<Platform> platformle; platform = new LinuxPpc64Platform(ppc64, "linux-ppc64"); platformle = new LinuxPpc64Platform(ppc64le, "linux-ppc64_le"); Platform::Register("linux", platform); Platform::Register("linux", platformle); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, ppc64, platform); BinaryViewType::RegisterPlatform("ELF", 3, ppc64, platform); BinaryViewType::RegisterPlatform("ELF", 0, ppc64le, platformle); BinaryViewType::RegisterPlatform("ELF", 3, ppc64le, platformle); } Ref<Architecture> mipsel = Architecture::GetByName("mipsel32"); Ref<Architecture> mipseb = Architecture::GetByName("mips32"); if (mipsel && mipseb) { Ref<Platform> platformLE, platformBE; platformLE = new LinuxMipsPlatform(mipsel, "linux-mipsel"); platformBE = new LinuxMipsPlatform(mipseb, "linux-mips"); Platform::Register("linux", platformLE); Platform::Register("linux", platformBE); // Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one BinaryViewType::RegisterPlatform("ELF", 0, mipsel, platformLE); BinaryViewType::RegisterPlatform("ELF", 0, mipseb, platformBE); BinaryViewType::RegisterPlatform("ELF", 3, mipsel, platformLE); BinaryViewType::RegisterPlatform("ELF", 3, mipseb, platformBE); } return true; } }
29.511475
94
0.736363
4555a728416e55f68c46303cbf1c1a6c81eb918c
593
cpp
C++
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
Shiv-sharma-111/jubilant-sniffle
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
[ "MIT" ]
null
null
null
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
Shiv-sharma-111/jubilant-sniffle
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
[ "MIT" ]
null
null
null
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
Shiv-sharma-111/jubilant-sniffle
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int T; cin>>T; while(T--) { int n1,n2; cin>>n1>>n2; int arr1[n1],arr2[n2]; for(int i=0;i<n1;i++) { cin>>arr1[i]; } for(int i=0;i<n2;i++) { cin>>arr2[i]; } int count=0,sum; unordered_set<int> mp; for(int i=0;i<n1;i++) { for(int j=0;j<n2;j++) { sum = arr1[i]+arr2[j]; mp.insert(sum); } } //int k = mp.size(); cout<<mp.size()<<"\n"; } return 0; }
16.027027
35
0.468803