hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3ce07682a7675348821658eed791d68f3fb84485
705
cpp
C++
Cplus/FindKClosestElements.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/FindKClosestElements.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/FindKClosestElements.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <vector> using namespace std; /* user defined comp must meets the requirement comp(a,b)=true then must comp(b,a)=false heap comp is quiet different from sort */ class Solution { public: vector<int> findClosestElements(vector<int> &arr, int k, int x) { vector<int> res(k); for (auto &n : arr) n -= x; make_heap(arr.begin(), arr.end(), *this); for (int i = 0; i < k; ++i) { pop_heap(arr.begin(), arr.end() - i, *this); res[i] = *(arr.end() - i - 1); res[i] += x; } sort(res.begin(), res.end()); return res; } bool operator()(int l, int r) { if (abs(l) == abs(r)) return l >= 0 || r <= 0; return abs(l) > abs(r); } };
19.583333
85
0.585816
JumHorn
c9e530ef0c6abc1ee26d229f30a47cd02010ea87
1,315
cpp
C++
core/src/Buffer.cpp
marlinprotocol/OpenWeaver
7a8c668cccc933d652fabe8a141e702b8a0fd066
[ "MIT" ]
60
2020-07-01T17:37:34.000Z
2022-02-16T03:56:55.000Z
core/src/Buffer.cpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
5
2020-10-12T05:17:49.000Z
2021-05-25T15:47:01.000Z
core/src/Buffer.cpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
18
2020-07-01T17:43:18.000Z
2022-01-09T14:29:08.000Z
#include "marlin/core/Buffer.hpp" #include "marlin/core/Endian.hpp" #include <cstring> #include <cassert> #include <algorithm> namespace marlin { namespace core { Buffer::Buffer(size_t size) : BaseBuffer(new uint8_t[size], size) {} Buffer::Buffer(std::initializer_list<uint8_t> il, size_t size) : BaseBuffer(new uint8_t[size], size) { assert(il.size() <= size); std::copy(il.begin(), il.end(), buf); } Buffer::Buffer(uint8_t *buf, size_t size) : BaseBuffer(buf, size) {} Buffer::Buffer(Buffer &&b) noexcept : BaseBuffer(static_cast<BaseBuffer&&>(std::move(b))) { b.buf = nullptr; b.capacity = 0; b.start_index = 0; b.end_index = 0; } Buffer &Buffer::operator=(Buffer &&b) noexcept { // Destroy old delete[] buf; // Assign from new buf = b.buf; capacity = b.capacity; start_index = b.start_index; end_index = b.end_index; b.buf = nullptr; b.capacity = 0; b.start_index = 0; b.end_index = 0; return *this; } Buffer::~Buffer() { delete[] buf; } WeakBuffer Buffer::payload_buffer() & { return *this; } WeakBuffer const Buffer::payload_buffer() const& { return *this; } Buffer Buffer::payload_buffer() && { return std::move(*this); } uint8_t* Buffer::payload() { return data(); } uint8_t const* Buffer::payload() const { return data(); } } // namespace core } // namespace marlin
17.77027
64
0.676806
marlinprotocol
c9e575ea04e3456f55c807006ae051c5563336a5
913
cpp
C++
tests/fixtures.cpp
quotekio/quotek-ig
df27a3a5c7295f8652482b54d20c2f7462cbdad8
[ "BSD-3-Clause" ]
1
2019-04-27T08:20:15.000Z
2019-04-27T08:20:15.000Z
tests/fixtures.cpp
quotekio/quotek-ig
df27a3a5c7295f8652482b54d20c2f7462cbdad8
[ "BSD-3-Clause" ]
null
null
null
tests/fixtures.cpp
quotekio/quotek-ig
df27a3a5c7295f8652482b54d20c2f7462cbdad8
[ "BSD-3-Clause" ]
null
null
null
#include "fixtures.hpp" igConnector* get_igconnector(string broker_params) { return new igConnector(broker_params, false, false, "poll"); } igConnector* get_igconnector_connected_pollmode(string broker_params) { igConnector* c = new igConnector(broker_params, false, false, "poll"); c->connect(); return c; } igConnector* get_igconnector_connected_pushmode(string broker_params, std::vector<std::string> ilist) { igConnector* c = new igConnector(broker_params, false, false, "push"); c->setIndicesList(ilist); c->connect(); return c; } igConnector* get_igconnector_connected_logging(string broker_params) { igConnector* c = new igConnector(broker_params, true, false, "pull"); c->connect(); return c; } igConnector* get_igconnector_connected_profiling(string broker_params) { igConnector* c = new igConnector(broker_params, false, true, "pull"); c->connect(); return c; }
29.451613
103
0.743702
quotekio
c9e6b6668fb2c26603ed8054076c27ecf4ed5a62
816
cpp
C++
sandbox/src1/TCSE3-3rd-examples/src/py/mixed/Grid2D/C++/notes/test.cpp
sniemi/SamPy
e048756feca67197cf5f995afd7d75d8286e017b
[ "BSD-2-Clause" ]
5
2016-05-28T14:12:28.000Z
2021-04-22T10:23:12.000Z
sandbox/src1/TCSE3-3rd-examples/src/py/mixed/Grid2D/C++/notes/test.cpp
sniemi/SamPy
e048756feca67197cf5f995afd7d75d8286e017b
[ "BSD-2-Clause" ]
null
null
null
sandbox/src1/TCSE3-3rd-examples/src/py/mixed/Grid2D/C++/notes/test.cpp
sniemi/SamPy
e048756feca67197cf5f995afd7d75d8286e017b
[ "BSD-2-Clause" ]
2
2015-07-13T10:04:10.000Z
2021-04-22T10:23:23.000Z
// This program does not work properly #include <NumPyArray.h> #define PY_ARRAY_UNIQUE_SYMBOL mytest #include <iostream> extern "C" { void test() { npy_intp dim1[1]; dim1[0] = 3; PyArrayObject* a = (PyArrayObject*) PyArray_FromDims(1, dim1, NPY_DOUBLE); } } int main() { std::cout << "H1" << std::endl; import_array(); /* required NumPy initialization */ std::cout << "H1" << std::endl; test(); std::cout << "H1" << std::endl; NumPyArray_Float x0; x0.create(3); NumPyArray_Float x1(3); x1(0) = -1; x1(1) = 0; x1(2) = 5; dump(std::cout, x1); NumPyArray_Float x2(3,1); x2(0,0) = -1; x2(1,0) = 0; x2(2,0) = 5; dump(std::cout, x2); NumPyArray_Float x3(3,1,2); x3(0,0,0) = -1; x3(1,0,0) = 0; x3(2,0,0) = 5; x3(0,0,1) = -1; x3(1,0,1) = 0; x3(2,0,1) = 5; dump(std::cout, x3); }
22.666667
76
0.583333
sniemi
c9e90f4638a387a1a8b0c70f4d25ad0e598e5754
2,022
hpp
C++
libs/muddle/internal/routing_message.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/muddle/internal/routing_message.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/muddle/internal/routing_message.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/serializers/map_interface.hpp" #include <cstdint> namespace fetch { namespace muddle { struct RoutingMessage { enum class Type { PING = 0, PONG, ROUTING_REQUEST, ROUTING_ACCEPTED, DISCONNECT_REQUEST, MAX_NUM_TYPES }; Type type{Type::PING}; }; } // namespace muddle namespace serializers { template <typename D> struct MapSerializer<muddle::RoutingMessage, D> { public: using Type = muddle::RoutingMessage; using DriverType = D; using EnumType = uint64_t; static const uint8_t TYPE = 1; template <typename T> static void Serialize(T &map_constructor, Type const &msg) { auto map = map_constructor(1); map.Append(TYPE, static_cast<EnumType>(msg.type)); } template <typename T> static void Deserialize(T &map, Type &msg) { static constexpr auto MAX_TYPE_VALUE = static_cast<EnumType>(Type::Type::MAX_NUM_TYPES); EnumType raw_type{0}; map.ExpectKeyGetValue(TYPE, raw_type); // validate the type enum if (raw_type >= MAX_TYPE_VALUE) { throw std::runtime_error("Invalid type value"); } msg.type = static_cast<Type::Type>(raw_type); } }; } // namespace serializers } // namespace fetch
24.071429
92
0.637982
devjsc
c9ea29fbc34909304d6ef9fd554c3785101d4a3d
17,753
cpp
C++
SampleFramework12/v1.02/Graphics/Sampling.cpp
BalazsJako/DXRPathTracer
948693d73c7f9474d98482e99e85416750b29286
[ "MIT" ]
456
2018-10-29T03:51:23.000Z
2022-03-21T02:26:20.000Z
SampleFramework12/v1.02/Graphics/Sampling.cpp
BalazsJako/DXRPathTracer
948693d73c7f9474d98482e99e85416750b29286
[ "MIT" ]
8
2018-10-31T05:31:19.000Z
2020-03-31T21:00:27.000Z
SampleFramework12/v1.02/Graphics/Sampling.cpp
BalazsJako/DXRPathTracer
948693d73c7f9474d98482e99e85416750b29286
[ "MIT" ]
48
2018-10-29T05:36:41.000Z
2022-02-10T23:42:25.000Z
//================================================================================================= // // MJP's DX12 Sample Framework // http://mynameismjp.wordpress.com/ // // All code licensed under the MIT license // //================================================================================================= #include "PCH.h" #include "Sampling.h" namespace SampleFramework12 { #define RadicalInverse_(base) \ { \ const float radical = 1.0f / float(base); \ uint64 value = 0; \ float factor = 1.0f; \ while(sampleIdx) { \ uint64 next = sampleIdx / base; \ uint64 digit = sampleIdx - next * base; \ value = value * base + digit; \ factor *= radical; \ sampleIdx = next; \ } \ inverse = float(value) * factor; \ } static const float OneMinusEpsilon = 0.9999999403953552f; float RadicalInverseFast(uint64 baseIdx, uint64 sampleIdx) { Assert_(baseIdx < 64); float inverse = 0.0f; switch (baseIdx) { case 0: RadicalInverse_(2); break; case 1: RadicalInverse_(3); break; case 2: RadicalInverse_(5); break; case 3: RadicalInverse_(7); break; case 4: RadicalInverse_(11); break; case 5: RadicalInverse_(13); break; case 6: RadicalInverse_(17); break; case 7: RadicalInverse_(19); break; case 8: RadicalInverse_(23); break; case 9: RadicalInverse_(29); break; case 10: RadicalInverse_(31); break; case 11: RadicalInverse_(37); break; case 12: RadicalInverse_(41); break; case 13: RadicalInverse_(43); break; case 14: RadicalInverse_(47); break; case 15: RadicalInverse_(53); break; case 16: RadicalInverse_(59); break; case 17: RadicalInverse_(61); break; case 18: RadicalInverse_(67); break; case 19: RadicalInverse_(71); break; case 20: RadicalInverse_(73); break; case 21: RadicalInverse_(79); break; case 22: RadicalInverse_(83); break; case 23: RadicalInverse_(89); break; case 24: RadicalInverse_(97); break; case 25: RadicalInverse_(101); break; case 26: RadicalInverse_(103); break; case 27: RadicalInverse_(107); break; case 28: RadicalInverse_(109); break; case 29: RadicalInverse_(113); break; case 30: RadicalInverse_(127); break; case 31: RadicalInverse_(131); break; case 32: RadicalInverse_(137); break; case 33: RadicalInverse_(139); break; case 34: RadicalInverse_(149); break; case 35: RadicalInverse_(151); break; case 36: RadicalInverse_(157); break; case 37: RadicalInverse_(163); break; case 38: RadicalInverse_(167); break; case 39: RadicalInverse_(173); break; case 40: RadicalInverse_(179); break; case 41: RadicalInverse_(181); break; case 42: RadicalInverse_(191); break; case 43: RadicalInverse_(193); break; case 44: RadicalInverse_(197); break; case 45: RadicalInverse_(199); break; case 46: RadicalInverse_(211); break; case 47: RadicalInverse_(223); break; case 48: RadicalInverse_(227); break; case 49: RadicalInverse_(229); break; case 50: RadicalInverse_(233); break; case 51: RadicalInverse_(239); break; case 52: RadicalInverse_(241); break; case 53: RadicalInverse_(251); break; case 54: RadicalInverse_(257); break; case 55: RadicalInverse_(263); break; case 56: RadicalInverse_(269); break; case 57: RadicalInverse_(271); break; case 58: RadicalInverse_(277); break; case 59: RadicalInverse_(281); break; case 60: RadicalInverse_(283); break; case 61: RadicalInverse_(293); break; case 62: RadicalInverse_(307); break; case 63: RadicalInverse_(311); break; } return std::min(inverse, OneMinusEpsilon); } // Maps a value inside the square [0,1]x[0,1] to a value in a disk of radius 1 using concentric squares. // This mapping preserves area, bi continuity, and minimizes deformation. // Based off the algorithm "A Low Distortion Map Between Disk and Square" by Peter Shirley and // Kenneth Chiu. Also includes polygon morphing modification from "CryEngine3 Graphics Gems" // by Tiago Sousa Float2 SquareToConcentricDiskMapping(float x, float y, float numSides, float polygonAmount) { float phi, r; // -- (a,b) is now on [-1,1]ˆ2 float a = 2.0f * x - 1.0f; float b = 2.0f * y - 1.0f; if(a > -b) // region 1 or 2 { if(a > b) // region 1, also |a| > |b| { r = a; phi = (Pi / 4.0f) * (b / a); } else // region 2, also |b| > |a| { r = b; phi = (Pi / 4.0f) * (2.0f - (a / b)); } } else // region 3 or 4 { if(a < b) // region 3, also |a| >= |b|, a != 0 { r = -a; phi = (Pi / 4.0f) * (4.0f + (b / a)); } else // region 4, |b| >= |a|, but a==0 and b==0 could occur. { r = -b; if(b != 0) phi = (Pi / 4.0f) * (6.0f - (a / b)); else phi = 0; } } const float N = numSides; float polyModifier = std::cos(Pi / N) / std::cos(phi - (Pi2 / N) * std::floor((N * phi + Pi) / Pi2)); r *= Lerp(1.0f, polyModifier, polygonAmount); Float2 result; result.x = r * std::cos(phi); result.y = r * std::sin(phi); return result; } // Maps a value inside the square [0,1]x[0,1] to a value in a disk of radius 1 using concentric squares. // This mapping preserves area, bi continuity, and minimizes deformation. // Based off the algorithm "A Low Distortion Map Between Disk and Square" by Peter Shirley and // Kenneth Chiu. Float2 SquareToConcentricDiskMapping(float x, float y) { float phi = 0.0f; float r = 0.0f; // -- (a,b) is now on [-1,1]ˆ2 float a = 2.0f * x - 1.0f; float b = 2.0f * y - 1.0f; if(a > -b) // region 1 or 2 { if(a > b) // region 1, also |a| > |b| { r = a; phi = (Pi / 4.0f) * (b / a); } else // region 2, also |b| > |a| { r = b; phi = (Pi / 4.0f) * (2.0f - (a / b)); } } else // region 3 or 4 { if(a < b) // region 3, also |a| >= |b|, a != 0 { r = -a; phi = (Pi / 4.0f) * (4.0f + (b / a)); } else // region 4, |b| >= |a|, but a==0 and b==0 could occur. { r = -b; if(b != 0) phi = (Pi / 4.0f) * (6.0f - (a / b)); else phi = 0; } } Float2 result; result.x = r * std::cos(phi); result.y = r * std::sin(phi); return result; } // Returns a random direction for sampling a GGX distribution. // Does everything in world space. Float3 SampleDirectionGGX(const Float3& v, const Float3& n, float roughness, const Float3x3& tangentToWorld, float u1, float u2) { float theta = std::atan2(roughness * std::sqrt(u1), std::sqrt(1 - u1)); float phi = 2 * Pi * u2; Float3 h; h.x = std::sin(theta) * std::cos(phi); h.y = std::sin(theta) * std::sin(phi); h.z = std::cos(theta); h = Float3::Normalize(Float3::Transform(h, tangentToWorld)); float hDotV = Float3::Dot(h, v); Float3 sampleDir = 2.0f * hDotV * h - v; return Float3::Normalize(sampleDir); } // Returns a point inside of a unit sphere Float3 SampleSphere(float x1, float x2, float x3, float u1) { Float3 xyz = Float3(x1, x2, x3) * 2.0f - 1.0f; float scale = std::pow(u1, 1.0f / 3.0f) / Float3::Length(xyz); return xyz * scale; } // Returns a random direction on the unit sphere Float3 SampleDirectionSphere(float u1, float u2) { float z = u1 * 2.0f - 1.0f; float r = std::sqrt(std::max(0.0f, 1.0f - z * z)); float phi = 2 * Pi * u2; float x = r * std::cos(phi); float y = r * std::sin(phi); return Float3(x, y, z); } // Returns a random direction on the hemisphere around z = 1 Float3 SampleDirectionHemisphere(float u1, float u2) { float z = u1; float r = std::sqrt(std::max(0.0f, 1.0f - z * z)); float phi = 2 * Pi * u2; float x = r * std::cos(phi); float y = r * std::sin(phi); return Float3(x, y, z); } // Returns a random cosine-weighted direction on the hemisphere around z = 1 Float3 SampleDirectionCosineHemisphere(float u1, float u2) { Float2 uv = SquareToConcentricDiskMapping(u1, u2); float u = uv.x; float v = uv.y; // Project samples on the disk to the hemisphere to get a // cosine weighted distribution Float3 dir; float r = u * u + v * v; dir.x = u; dir.y = v; dir.z = std::sqrt(std::max(0.0f, 1.0f - r)); return dir; } // Returns a random direction from within a cone with angle == theta Float3 SampleDirectionCone(float u1, float u2, float cosThetaMax) { float cosTheta = (1.0f - u1) + u1 * cosThetaMax; float sinTheta = std::sqrt(1.0f - cosTheta * cosTheta); float phi = u2 * 2.0f * Pi; return Float3(std::cos(phi) * sinTheta, std::sin(phi) * sinTheta, cosTheta); } // Returns a direction that samples a rectangular area light Float3 SampleDirectionRectangularLight(float u1, float u2, const Float3& sourcePos, const Float2& lightSize, const Float3& lightPos, const Quaternion lightOrientation, float& distanceToLight) { float x = u1 - 0.5f; float y = u2 - 0.5f; Float3x3 lightBasis = lightOrientation.ToFloat3x3(); Float3 lightBasisX = lightBasis.Right(); Float3 lightBasisY = lightBasis.Up(); Float3 lightBasisZ = lightBasis.Forward(); // Pick random sample point Float3 samplePos = lightPos + lightBasisX * x * lightSize.x + lightBasisY * y * lightSize.y; Float3 sampleDir = samplePos - sourcePos; distanceToLight = Float3::Length(sampleDir); if(distanceToLight > 0.0f) sampleDir /= distanceToLight; return sampleDir; } // Returns the PDF for a particular GGX sample float SampleDirectionGGX_PDF(const Float3& n, const Float3& h, const Float3& v, float roughness) { float nDotH = Saturate(Float3::Dot(n, h)); float hDotV = Saturate(Float3::Dot(h, v)); float m2 = roughness * roughness; float d = m2 / (Pi * Square(nDotH * nDotH * (m2 - 1) + 1)); float pM = d * nDotH; return pM / (4 * hDotV); } // Returns the (constant) PDF of sampling uniform directions on the unit sphere float SampleDirectionSphere_PDF() { return 1.0f / (Pi * 4.0f); } // Returns the (constant) PDF of sampling uniform directions on a unit hemisphere float SampleDirectionHemisphere_PDF() { return 1.0f / (Pi * 2.0f); } // Returns the PDF of of a single sample on a cosine-weighted hemisphere float SampleDirectionCosineHemisphere_PDF(float cosTheta) { return cosTheta / Pi; } // Returns the PDF of of a single sample on a cosine-weighted hemisphere float SampleDirectionCosineHemisphere_PDF(const Float3& normal, const Float3& sampleDir) { return Saturate(Float3::Dot(normal, sampleDir)) / Pi; } // Returns the PDF of of a single uniform sample within a cone float SampleDirectionCone_PDF(float cosThetaMax) { return 1.0f / (2.0f * Pi * (1.0f - cosThetaMax)); } // Returns the PDF of of a single sample on a rectangular area light float SampleDirectionRectangularLight_PDF(const Float2& lightSize, const Float3& sampleDir, const Quaternion lightOrientation, float distanceToLight) { Float3 lightBasisZ = Float3::Transform(Float3(0.0f, 0.0f, -1.0f), lightOrientation); float areaNDotL = Saturate(Float3::Dot(sampleDir, lightBasisZ)); return (distanceToLight * distanceToLight) / (areaNDotL * lightSize.x * lightSize.y); } // Computes a radical inverse with base 2 using crazy bit-twiddling from "Hacker's Delight" float RadicalInverseBase2(uint32 bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10f; // / 0x100000000 } // Returns a single 2D point in a Hammersley sequence of length "numSamples", using base 1 and base 2 Float2 Hammersley2D(uint64 sampleIdx, uint64 numSamples) { return Float2(float(sampleIdx) / float(numSamples), RadicalInverseBase2(uint32(sampleIdx))); } static uint32 CMJPermute(uint32 i, uint32 l, uint32 p) { uint32 w = l - 1; w |= w >> 1; w |= w >> 2; w |= w >> 4; w |= w >> 8; w |= w >> 16; do { i ^= p; i *= 0xe170893d; i ^= p >> 16; i ^= (i & w) >> 4; i ^= p >> 8; i *= 0x0929eb3f; i ^= p >> 23; i ^= (i & w) >> 1; i *= 1 | p >> 27; i *= 0x6935fa69; i ^= (i & w) >> 11; i *= 0x74dcb303; i ^= (i & w) >> 2; i *= 0x9e501cc3; i ^= (i & w) >> 2; i *= 0xc860a3df; i &= w; i ^= i >> 5; } while (i >= l); return (i + p) % l; } static float CMJRandFloat(uint32 i, uint32 p) { i ^= p; i ^= i >> 17; i ^= i >> 10; i *= 0xb36534e5; i ^= i >> 12; i ^= i >> 21; i *= 0x93fc4795; i ^= 0xdf6e307f; i ^= i >> 17; i *= 1 | p >> 18; return i * (1.0f / 4294967808.0f); } // Returns a 2D sample from a particular pattern using correlated multi-jittered sampling [Kensler 2013] Float2 SampleCMJ2D(uint32 sampleIdx, uint32 numSamplesX, uint32 numSamplesY, uint32 pattern) { uint32 N = numSamplesX * numSamplesY; sampleIdx = CMJPermute(sampleIdx, N, pattern * 0x51633e2d); uint32 sx = CMJPermute(sampleIdx % numSamplesX, numSamplesX, pattern * 0x68bc21eb); uint32 sy = CMJPermute(sampleIdx / numSamplesX, numSamplesY, pattern * 0x02e5be93); float jx = CMJRandFloat(sampleIdx, pattern * 0x967a889b); float jy = CMJRandFloat(sampleIdx, pattern * 0x368cc8b7); return Float2((sx + (sy + jx) / numSamplesY) / numSamplesX, (sampleIdx + jy) / N); } void GenerateRandomSamples2D(Float2* samples, uint64 numSamples, Random& randomGenerator) { for(uint64 i = 0; i < numSamples; ++i) samples[i] = randomGenerator.RandomFloat2(); } void GenerateStratifiedSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY, Random& randomGenerator) { const Float2 delta = Float2(1.0f / numSamplesX, 1.0f / numSamplesY); uint64 sampleIdx = 0; for(uint64 y = 0; y < numSamplesY; ++y) { for(uint64 x = 0; x < numSamplesX; ++x) { Float2& currSample = samples[sampleIdx]; currSample = Float2(float(x), float(y)) + randomGenerator.RandomFloat2(); currSample *= delta; currSample = Float2::Clamp(currSample, 0.0f, OneMinusEpsilon); ++sampleIdx; } } } void GenerateGridSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY) { const Float2 delta = Float2(1.0f / numSamplesX, 1.0f / numSamplesY); uint64 sampleIdx = 0; for(uint64 y = 0; y < numSamplesY; ++y) { for(uint64 x = 0; x < numSamplesX; ++x) { Float2& currSample = samples[sampleIdx]; currSample = Float2(float(x), float(y)); currSample *= delta; ++sampleIdx; } } } // Generates hammersley using base 1 and 2 void GenerateHammersleySamples2D(Float2* samples, uint64 numSamples) { for(uint64 i = 0; i < numSamples; ++i) samples[i] = Hammersley2D(i, numSamples); } // Generates hammersley using arbitrary bases void GenerateHammersleySamples2D(Float2* samples, uint64 numSamples, uint64 dimIdx) { if(dimIdx == 0) { GenerateHammersleySamples2D(samples, numSamples); } else { uint64 baseIdx0 = dimIdx * 2 - 1; uint64 baseIdx1 = baseIdx0 + 1; for(uint64 i = 0; i < numSamples; ++i) samples[i] = Float2(RadicalInverseFast(baseIdx0, i), RadicalInverseFast(baseIdx1, i)); } } void GenerateLatinHypercubeSamples2D(Float2* samples, uint64 numSamples, Random& rng) { // Generate LHS samples along diagonal const Float2 delta = Float2(1.0f / numSamples, 1.0f / numSamples); for(uint64 i = 0; i < numSamples; ++i) { Float2 currSample = Float2(float(i)) + rng.RandomFloat2(); currSample *= delta; samples[i] = Float2::Clamp(currSample, 0.0f, OneMinusEpsilon); } // Permute LHS samples in each dimension float* samples1D = reinterpret_cast<float*>(samples); const uint64 numDims = 2; for(uint64 i = 0; i < numDims; ++i) { for(uint64 j = 0; j < numSamples; ++j) { uint64 other = j + (rng.RandomUint() % (numSamples - j)); Swap(samples1D[numDims * j + i], samples1D[numDims * other + i]); } } } void GenerateCMJSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY, uint32 pattern) { const uint64 numSamples = numSamplesX * numSamplesY; for(uint64 i = 0; i < numSamples; ++i) samples[i] = SampleCMJ2D(int32(i), int32(numSamplesX), int32(numSamplesY), int32(pattern)); } }
33.559546
128
0.581198
BalazsJako
c9eaf4debea92386c086cef9890988a1e15e5b2a
1,859
hpp
C++
include/bptree/internal/map_traits.hpp
jason2506/bptree
388156024d4df32cc88c188e5801b1b460be083d
[ "MIT" ]
null
null
null
include/bptree/internal/map_traits.hpp
jason2506/bptree
388156024d4df32cc88c188e5801b1b460be083d
[ "MIT" ]
null
null
null
include/bptree/internal/map_traits.hpp
jason2506/bptree
388156024d4df32cc88c188e5801b1b460be083d
[ "MIT" ]
null
null
null
/************************************************ * map_traits.hpp * bptree * * Copyright (c) 2017, Chi-En Wu * Distributed under MIT License ************************************************/ #ifndef BPTREE_INTERNAL_MAP_TRAITS_HPP_ #define BPTREE_INTERNAL_MAP_TRAITS_HPP_ #include <functional> #include <utility> namespace bptree { namespace internal { /************************************************ * Declaration: struct map_traits<K, T, C> ************************************************/ template <typename Key, typename T, typename Compare = std::less<Key>> struct map_traits { public: // Public Type(s) using key_type = Key; using mapped_type = T; using value_type = std::pair<key_type const, mapped_type>; using key_compare = Compare; class value_compare : protected key_compare { protected: // Protected Method(s) explicit value_compare(key_compare comp) : key_compare(comp) { /* do nothing */ } public: // Public Method(s) bool operator()(value_type const& lhs, value_type const& rhs) const { return key_compare::operator()(lhs.first, rhs.first); } }; protected: // Protected Type(s) class core_compare { public: // Public Method(s) explicit core_compare(key_compare comp) : comp_(comp) { /* do nothing */ } template <typename K> bool operator()(K const& lhs, value_type const& rhs) const { return comp_(lhs, rhs.first); } template <typename K> bool operator()(value_type const& lhs, K const& rhs) const { return comp_(lhs.first, rhs); } private: // Private Method(s) key_compare const& comp_; }; }; } // namespace internal } // namespace bptree #endif // BPTREE_INTERNAL_MAP_TRAITS_HPP_
26.183099
77
0.56213
jason2506
c9ed8e108c6c92acbe0bdf17e9de649315336ad3
1,614
cc
C++
chrome/browser/ui/ash/notification_badge_color_cache_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/ui/ash/notification_badge_color_cache_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/ui/ash/notification_badge_color_cache_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2021 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 <memory> #include "chrome/browser/ui/ash/notification_badge_color_cache.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/image/image_skia.h" using NotificationBadgeTest = testing::Test; namespace ash { TEST_F(NotificationBadgeTest, NotificationBadgeColorTest) { const int width = 64; const int height = 64; SkBitmap all_black_icon; all_black_icon.allocN32Pixels(width, height); all_black_icon.eraseColor(SK_ColorBLACK); SkColor test_color = NotificationBadgeColorCache::GetInstance().GetBadgeColorForApp( "app_id1", gfx::ImageSkia::CreateFrom1xBitmap(all_black_icon)); // For an all black icon, a white notification badge is expected, since there // is no other light vibrant color to get from the icon. EXPECT_EQ(test_color, SK_ColorWHITE); // Create an icon that is half kGoogleRed300 and half kGoogleRed600. SkBitmap red_icon; red_icon.allocN32Pixels(width, height); red_icon.eraseColor(gfx::kGoogleRed300); red_icon.erase(gfx::kGoogleRed600, {0, 0, width, height / 2}); test_color = NotificationBadgeColorCache::GetInstance().GetBadgeColorForApp( "app_id2", gfx::ImageSkia::CreateFrom1xBitmap(red_icon)); // For the red icon, the notification badge should calculate and use the // kGoogleRed300 color as the light vibrant color taken from the icon. EXPECT_EQ(gfx::kGoogleRed300, test_color); } } // namespace ash
34.340426
79
0.760843
zealoussnow
c9ee362018ee1f85ad09dd40c1cdfa126a1a70b1
10,244
cpp
C++
tests/djvRender2DTest/FontSystemTest.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
tests/djvRender2DTest/FontSystemTest.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
tests/djvRender2DTest/FontSystemTest.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 Darby Johnston // All rights reserved. #include <djvRender2DTest/FontSystemTest.h> #include <djvRender2D/Data.h> #include <djvRender2D/FontSystem.h> #include <djvSystem/Context.h> #include <djvSystem/TimerFunc.h> #include <djvMath/VectorFunc.h> #include <djvCore/StringFunc.h> using namespace djv::Core; using namespace djv::Render2D; namespace djv { namespace Render2DTest { FontSystemTest::FontSystemTest( const System::File::Path& tempPath, const std::shared_ptr<System::Context>& context) : ITickTest("djv::Render2DTest::FontSystemTest", tempPath, context) {} void FontSystemTest::run() { _info(); _metrics(); _textLine(); _glyphInfo(); _glyph(); _system(); _operators(); } void FontSystemTest::_info() { { const Font::FontInfo fontInfo; DJV_ASSERT(1 == fontInfo.getFamily()); DJV_ASSERT(1 == fontInfo.getFace()); DJV_ASSERT(0 == fontInfo.getSize()); DJV_ASSERT(dpiDefault == fontInfo.getDPI()); } { const Font::FontInfo fontInfo(2, 3, 4, 5); DJV_ASSERT(2 == fontInfo.getFamily()); DJV_ASSERT(3 == fontInfo.getFace()); DJV_ASSERT(4 == fontInfo.getSize()); DJV_ASSERT(5 == fontInfo.getDPI()); } } void FontSystemTest::_metrics() { const Font::Metrics metrics; DJV_ASSERT(0 == metrics.ascender); DJV_ASSERT(0 == metrics.descender); DJV_ASSERT(0 == metrics.lineHeight); } void FontSystemTest::_textLine() { { const Font::TextLine textLine; DJV_ASSERT(textLine.text.empty()); DJV_ASSERT(0.F == textLine.size.x); DJV_ASSERT(0.F == textLine.size.y); } { const Font::TextLine textLine("line", glm::vec2(1.F, 2.F), {}); DJV_ASSERT(!textLine.text.empty()); DJV_ASSERT(1.F == textLine.size.x); DJV_ASSERT(2.F == textLine.size.y); DJV_ASSERT(0 == textLine.glyphs.size()); } } void FontSystemTest::_glyphInfo() { { const Font::GlyphInfo glyphInfo; DJV_ASSERT(0 == glyphInfo.code); DJV_ASSERT(Font::FontInfo() == glyphInfo.fontInfo); } { const Font::FontInfo fontInfo(2, 3, 4, 5); const Font::GlyphInfo glyphInfo(1, fontInfo); DJV_ASSERT(1 == glyphInfo.code); DJV_ASSERT(fontInfo == glyphInfo.fontInfo); } } void FontSystemTest::_glyph() { { auto glyph = Font::Glyph::create(); DJV_ASSERT(Font::GlyphInfo() == glyph->glyphInfo); DJV_ASSERT(!glyph->imageData); DJV_ASSERT(glm::vec2(0.F, 0.F) == glyph->offset); DJV_ASSERT(0 == glyph->lsbDelta); DJV_ASSERT(0 == glyph->rsbDelta); } } void FontSystemTest::_system() { if (auto context = getContext().lock()) { auto system = context->getSystemT<Render2D::Font::FontSystem>(); auto fontNamesObserver = Observer::Map<Font::FamilyID, std::string>::create( system->observeFontNames(), [this](const std::map<Font::FamilyID, std::string>& value) { for (const auto& i : value) { std::stringstream ss; ss << "Font: " << i.second; _print(ss.str()); } }); Font::FontInfo fontInfo(1, 1, 14, dpiDefault); auto metricsFuture = system->getMetrics(fontInfo); const std::string text = String::getRandomText(50); auto measureFuture = system->measure(text, fontInfo); auto measureGlyphsFuture = system->measureGlyphs(text, fontInfo); auto textLinesFuture = system->textLines(text, 100, fontInfo); auto glyphsFuture = system->getGlyphs(text, fontInfo); system->cacheGlyphs(text, fontInfo); Font::Metrics metrics; glm::vec2 measure = glm::vec2(0.F, 0.F); std::vector<Math::BBox2f> measureGlyphs; std::vector<Font::TextLine> textLines; std::vector<std::shared_ptr<Font::Glyph> > glyphs; while ( metricsFuture.valid() || measureFuture.valid() || measureGlyphsFuture.valid() || textLinesFuture.valid() || glyphsFuture.valid()) { _tickFor(System::getTimerDuration(System::TimerValue::Fast)); if (metricsFuture.valid() && metricsFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { metrics = metricsFuture.get(); } if (measureFuture.valid() && measureFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { measure = measureFuture.get(); } if (measureGlyphsFuture.valid() && measureGlyphsFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { measureGlyphs = measureGlyphsFuture.get(); } if (textLinesFuture.valid() && textLinesFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { textLines = textLinesFuture.get(); } if (glyphsFuture.valid() && glyphsFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { glyphs = glyphsFuture.get(); } } { std::stringstream ss; ss << "Ascender: " << metrics.ascender; _print(ss.str()); } { std::stringstream ss; ss << "Descender: " << metrics.descender; _print(ss.str()); } { std::stringstream ss; ss << "Line height: " << metrics.lineHeight; _print(ss.str()); } { std::stringstream ss; ss << "Measure: " << measure; _print(ss.str()); } for (const auto& i : textLines) { std::stringstream ss; ss << "Text line: " << i.text; _print(ss.str()); } system->setLCDRendering(true); system->setLCDRendering(true); const uint16_t elide = text.size() / 2; measureFuture = system->measure(text, fontInfo, elide); measureGlyphsFuture = system->measureGlyphs(text, fontInfo, elide); glyphsFuture = system->getGlyphs(text, fontInfo, elide); glyphs.clear(); measure = glm::vec2(0.F, 0.F); measureGlyphs.clear(); while ( measureFuture.valid() || measureGlyphsFuture.valid() || glyphsFuture.valid()) { _tickFor(System::getTimerDuration(System::TimerValue::Fast)); if (measureFuture.valid() && measureFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { measure = measureFuture.get(); } if (measureGlyphsFuture.valid() && measureGlyphsFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { measureGlyphs = measureGlyphsFuture.get(); } if (glyphsFuture.valid() && glyphsFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { glyphs = glyphsFuture.get(); } } { std::stringstream ss; ss << "Glyph cache size: " << system->getGlyphCacheSize(); _print(ss.str()); } { std::stringstream ss; ss << "Glyph cache percentage: " << system->getGlyphCachePercentage(); _print(ss.str()); } } } void FontSystemTest::_operators() { { const Font::FontInfo fontInfo(2, 3, 4, 5); DJV_ASSERT(fontInfo == fontInfo); DJV_ASSERT(Font::FontInfo() < fontInfo); } { const Font::FontInfo fontInfo(2, 3, 4, 5); const Font::GlyphInfo glyphInfo(1, fontInfo); DJV_ASSERT(glyphInfo == glyphInfo); DJV_ASSERT(Font::GlyphInfo() < glyphInfo); } } } // namespace Render2DTest } // namespace djv
37.661765
107
0.443479
pafri
c9f05ef3dbf4d1636a8b3ba4790e0e5ac37adc73
1,030
cpp
C++
Source/Rotary_Slider.cpp
Silver92/My-Delay
96afc7eab81d11c7b59b6a270c40741124afa9db
[ "MIT" ]
null
null
null
Source/Rotary_Slider.cpp
Silver92/My-Delay
96afc7eab81d11c7b59b6a270c40741124afa9db
[ "MIT" ]
null
null
null
Source/Rotary_Slider.cpp
Silver92/My-Delay
96afc7eab81d11c7b59b6a270c40741124afa9db
[ "MIT" ]
null
null
null
/* ============================================================================== Slider.cpp Created: 6 Sep 2019 7:11:44am Author: Silver ============================================================================== */ #include "Rotary_Slider.h" #include "UIDemensions.h" RotarySlider::RotarySlider(AudioProcessorValueTreeState& stateToControl, int parameterName) : juce::Slider(ParameterLabel[parameterName]) { setSliderStyle(SliderStyle::RotaryHorizontalVerticalDrag); setTextBoxStyle(Slider::NoTextBox, false, SLIDER_SIZE, SLIDER_SIZE / 3); setRange(0.0f, 1.0f, 0.001f); mAttachment.reset( new AudioProcessorValueTreeState::SliderAttachment(stateToControl, ParameterID[parameterName], *this)); } RotarySlider::~RotarySlider() { } void RotarySlider::setInterval() { setRange(0.0f, 1.0f, 1.f/ 13.f); }
28.611111
83
0.493204
Silver92
c9f1969fd6163e4256c57b21a89a18ac9443bc3f
412
cpp
C++
CodeForces.com/educational_rounds/er3/A.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
CodeForces.com/educational_rounds/er3/A.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
CodeForces.com/educational_rounds/er3/A.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> flashes; int main(){ ios::sync_with_stdio(false); int n,m,tmp; cin >> n >> m; for(int i = 0; i<n; i++) { cin >> tmp; flashes.push_back(tmp); } stable_sort(flashes.begin(), flashes.end()); int summ = 0,i; for(i = n-1;summ<m; i-- ){ summ+=flashes[i];} cout << (n-i-1); return 0; }
18.727273
47
0.572816
mstrechen
c9f836d17615390c1da31bb2e36b20ffc1cfaf1e
2,437
cpp
C++
export/release/windows/obj/src/webm/WebmEvent.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/webm/WebmEvent.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/webm/WebmEvent.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_openfl_events_Event #include <openfl/events/Event.h> #endif #ifndef INCLUDED_webm_WebmEvent #include <webm/WebmEvent.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_a611475ca79daef8_14_new,"webm.WebmEvent","new",0x3feaff7e,"webm.WebmEvent.new","webm/WebmEvent.hx",14,0x67547733) namespace webm{ void WebmEvent_obj::__construct(::String type,::hx::Null< bool > __o_bubbles,::hx::Null< bool > __o_cancelable){ bool bubbles = __o_bubbles.Default(false); bool cancelable = __o_cancelable.Default(false); HX_STACKFRAME(&_hx_pos_a611475ca79daef8_14_new) HXDLIN( 14) super::__construct(type,bubbles,cancelable); } Dynamic WebmEvent_obj::__CreateEmpty() { return new WebmEvent_obj; } void *WebmEvent_obj::_hx_vtable = 0; Dynamic WebmEvent_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< WebmEvent_obj > _hx_result = new WebmEvent_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]); return _hx_result; } bool WebmEvent_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x08ec4c31) { return inClassId==(int)0x00000001 || inClassId==(int)0x08ec4c31; } else { return inClassId==(int)0x1af6f1a8; } } WebmEvent_obj::WebmEvent_obj() { } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *WebmEvent_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *WebmEvent_obj_sStaticStorageInfo = 0; #endif ::hx::Class WebmEvent_obj::__mClass; void WebmEvent_obj::__register() { WebmEvent_obj _hx_dummy; WebmEvent_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("webm.WebmEvent",8c,28,e2,64); __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(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< WebmEvent_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = WebmEvent_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = WebmEvent_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace webm
32.065789
143
0.74682
bobisdabbing
c9fb517c3105e4973b205960ccaff1c3bb645f86
5,439
cpp
C++
src/SpotLight.cpp
lemurni/Engine186-Linux
2c1569aecee76974078ffba1df2ac38e6b3f9238
[ "CC0-1.0" ]
3
2020-03-10T16:41:41.000Z
2021-12-13T11:36:12.000Z
src/SpotLight.cpp
lemurni/Engine186-Linux
2c1569aecee76974078ffba1df2ac38e6b3f9238
[ "CC0-1.0" ]
null
null
null
src/SpotLight.cpp
lemurni/Engine186-Linux
2c1569aecee76974078ffba1df2ac38e6b3f9238
[ "CC0-1.0" ]
1
2021-10-20T02:18:38.000Z
2021-10-20T02:18:38.000Z
#include "SpotLight.h" namespace e186 { const float SpotLight::k_max_outer_angle = glm::pi<float>() - 0.4f; SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction) : m_position(position), m_direction(glm::normalize(direction)), m_light_color(color), m_attenuation(1.0f, 0.1f, 0.01f, 0.0f), m_outer_angle(glm::half_pi<float>()), m_inner_angle(0.0f), m_falloff(1.0f), m_enabled{ true } { } SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction, float const_atten, float lin_atten, float quad_atten, float cub_atten, float outer_angle, float inner_angle, float falloff) : m_position(position), m_direction(glm::normalize(direction)), m_light_color(color), m_attenuation(const_atten, lin_atten, quad_atten, cub_atten), m_outer_angle(outer_angle), m_inner_angle(inner_angle), m_falloff(falloff), m_enabled{ true } { } SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction, const glm::vec4& attenuation, float outer_angle, float inner_angle, float falloff) : m_position(position), m_direction(glm::normalize(direction)), m_light_color(color), m_attenuation(attenuation), m_outer_angle(outer_angle), m_inner_angle(inner_angle), m_falloff(falloff), m_enabled{ true } { } SpotLight::SpotLight(const glm::vec3& color, Transform transform, float const_atten, float lin_atten, float quad_atten, float cub_atten, float outer_angle, float inner_angle, float falloff) : m_position(transform.GetPosition()), m_direction(transform.GetFrontVector()), m_light_color(color), m_attenuation(const_atten, lin_atten, quad_atten, cub_atten), m_outer_angle(outer_angle), m_inner_angle(inner_angle), m_falloff(falloff), m_enabled{ true } { } SpotLight::~SpotLight() { } void SpotLight::set_position(glm::vec3 position) { m_position = std::move(position); } void SpotLight::set_direction(glm::vec3 direction) { m_direction = std::move(glm::normalize(direction)); } void SpotLight::set_light_color(glm::vec3 color) { m_light_color = std::move(color); } void SpotLight::set_attenuation(glm::vec4 attenuation) { m_attenuation = std::move(attenuation); } void SpotLight::set_const_attenuation(float attenuation) { m_attenuation = glm::vec4(attenuation, m_attenuation[1], m_attenuation[2], m_attenuation[3]); } void SpotLight::set_linear_attenuation(float attenuation) { m_attenuation = glm::vec4(m_attenuation[0], attenuation, m_attenuation[2], m_attenuation[3]); } void SpotLight::set_quadratic_attenuation(float attenuation) { m_attenuation = glm::vec4(m_attenuation[0], m_attenuation[1], attenuation, m_attenuation[3]); } void SpotLight::set_cubic_attenuation(float attenuation) { m_attenuation = glm::vec4(m_attenuation[0], m_attenuation[1], m_attenuation[2], attenuation); } void SpotLight::set_outer_angle(float outer_angle) { m_outer_angle = outer_angle; m_outer_angle = glm::clamp(m_outer_angle, 0.0f, k_max_outer_angle); m_inner_angle = glm::min(m_inner_angle, m_outer_angle); } void SpotLight::set_inner_angle(float inner_angle) { m_inner_angle = inner_angle; m_inner_angle = glm::clamp(m_inner_angle, 0.0f, m_outer_angle); } void SpotLight::set_falloff(float falloff) { m_falloff = falloff; } void SpotLight::set_enabled(bool is_enabled) { m_enabled = is_enabled; } SpotLightGpuData SpotLight::GetGpuData() const { SpotLightGpuData gdata; FillGpuDataIntoTarget(gdata); return gdata; } SpotLightGpuData SpotLight::GetGpuData(const glm::mat4& mat) const { SpotLightGpuData gdata; FillGpuDataIntoTarget(gdata, mat); return gdata; } void SpotLight::FillGpuDataIntoTarget(SpotLightGpuData& target) const { if (m_enabled) { target.m_position_and_cos_outer_angle_half = glm::vec4(m_position, glm::cos(m_outer_angle / 2.0f)); target.m_direction_and_cos_inner_angle_half = glm::vec4(m_direction, glm::cos(m_inner_angle / 2.0f)); target.m_light_color_and_falloff = glm::vec4(m_light_color, m_falloff); target.m_attenuation = m_attenuation; } else { target.m_position_and_cos_outer_angle_half = glm::vec4(0.0f); target.m_direction_and_cos_inner_angle_half = glm::vec4(0.0f); target.m_light_color_and_falloff = glm::vec4(0.0f); target.m_attenuation = glm::vec4(1.0f); } } void SpotLight::FillGpuDataIntoTarget(SpotLightGpuData& target, const glm::mat4& mat) const { if (m_enabled) { target.m_position_and_cos_outer_angle_half = mat * glm::vec4(m_position, 1.0f); target.m_position_and_cos_outer_angle_half.w = glm::cos(m_outer_angle / 2.0f); target.m_direction_and_cos_inner_angle_half = glm::vec4(glm::mat3(mat) * m_direction, glm::cos(m_inner_angle / 2.0f)); target.m_light_color_and_falloff = glm::vec4(m_light_color, m_falloff); target.m_attenuation = m_attenuation; } else { target.m_position_and_cos_outer_angle_half = glm::vec4(0.0f); target.m_direction_and_cos_inner_angle_half = glm::vec4(0.0f); target.m_light_color_and_falloff = glm::vec4(0.0f); target.m_attenuation = glm::vec4(1.0f); } } SpotLight::operator SpotLightGpuData() const { return GetGpuData(); } }
29.721311
122
0.720169
lemurni
c9fbbdd94d4ae715b47a127a24e761c723b8f60a
11,246
cc
C++
third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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/public/common/scheduler/web_scheduler_tracked_feature.h" #include <map> namespace blink { namespace scheduler { namespace { struct FeatureNames { std::string short_name; std::string human_readable; }; FeatureNames FeatureToNames(WebSchedulerTrackedFeature feature) { switch (feature) { case WebSchedulerTrackedFeature::kWebSocket: return {"WebSocket", "WebSocket"}; case WebSchedulerTrackedFeature::kWebRTC: return {"WebRTC", "WebRTC"}; case WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoCache: return {"MainResourceHasCacheControlNoCache", "main resource has Cache-Control: No-Cache"}; case WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore: return {"MainResourceHasCacheControlNoStore", "main resource has Cache-Control: No-Store"}; case WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoCache: return {"SubresourceHasCacheControlNoCache", "subresource has Cache-Control: No-Cache"}; case WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoStore: return {"SubresourceHasCacheControlNoStore", "subresource has Cache-Control: No-Store"}; case WebSchedulerTrackedFeature::kPageShowEventListener: return {"PageShowEventListener", "onpageshow() event listener"}; case WebSchedulerTrackedFeature::kPageHideEventListener: return {"PageHideEventListener", "onpagehide() event listener"}; case WebSchedulerTrackedFeature::kBeforeUnloadEventListener: return {"BeforeUnloadEventListener", "onbeforeunload() event listener"}; case WebSchedulerTrackedFeature::kUnloadEventListener: return {"UnloadEventListener", "onunload() event listener"}; case WebSchedulerTrackedFeature::kFreezeEventListener: return {"FreezeEventListener", "onfreeze() event listener"}; case WebSchedulerTrackedFeature::kResumeEventListener: return {"ResumeEventListener", "onresume() event listener"}; case WebSchedulerTrackedFeature::kContainsPlugins: return {"ContainsPlugins", "page contains plugins"}; case WebSchedulerTrackedFeature::kDocumentLoaded: return {"DocumentLoaded", "document loaded"}; case WebSchedulerTrackedFeature::kDedicatedWorkerOrWorklet: return {"DedicatedWorkerOrWorklet", "Dedicated worker or worklet present"}; case WebSchedulerTrackedFeature::kSharedWorker: return {"SharedWorker", "Shared worker present"}; case WebSchedulerTrackedFeature::kOutstandingNetworkRequestFetch: return {"OutstandingNetworkRequestFetch", "outstanding network request (fetch)"}; case WebSchedulerTrackedFeature::kOutstandingNetworkRequestXHR: return {"OutstandingNetworkRequestXHR", "outstanding network request (XHR)"}; case WebSchedulerTrackedFeature::kOutstandingNetworkRequestOthers: return {"OutstandingNetworkRequestOthers", "outstanding network request (others)"}; case WebSchedulerTrackedFeature::kOutstandingIndexedDBTransaction: return {"OutstandingIndexedDBTransaction", "outstanding IndexedDB transaction"}; case WebSchedulerTrackedFeature::kRequestedGeolocationPermission: return {"RequestedGeolocationPermission", "requested geolocation permission"}; case WebSchedulerTrackedFeature::kRequestedNotificationsPermission: return {"RequestedNotificationsPermission", "requested notifications permission"}; case WebSchedulerTrackedFeature::kRequestedMIDIPermission: return {"RequestedMIDIPermission", "requested midi permission"}; case WebSchedulerTrackedFeature::kRequestedAudioCapturePermission: return {"RequestedAudioCapturePermission", "requested audio capture permission"}; case WebSchedulerTrackedFeature::kRequestedVideoCapturePermission: return {"RequestedVideoCapturePermission", "requested video capture permission"}; case WebSchedulerTrackedFeature::kRequestedBackForwardCacheBlockedSensors: return {"RequestedBackForwardCacheBlockedSensors", "requested sensors permission"}; case WebSchedulerTrackedFeature::kRequestedBackgroundWorkPermission: return {"RequestedBackgroundWorkPermission", "requested background work permission"}; case WebSchedulerTrackedFeature::kBroadcastChannel: return {"BroadcastChannel", "requested broadcast channel permission"}; case WebSchedulerTrackedFeature::kIndexedDBConnection: return {"IndexedDBConnection", "IndexedDB connection present"}; case WebSchedulerTrackedFeature::kWebVR: return {"WebVR", "WebVR"}; case WebSchedulerTrackedFeature::kWebXR: return {"WebXR", "WebXR"}; case WebSchedulerTrackedFeature::kWebLocks: return {"WebLocks", "WebLocks"}; case WebSchedulerTrackedFeature::kWebHID: return {"WebHID", "WebHID"}; case WebSchedulerTrackedFeature::kWebShare: return {"WebShare", "WebShare"}; case WebSchedulerTrackedFeature::kRequestedStorageAccessGrant: return {"RequestedStorageAccessGrant", "requested storage access permission"}; case WebSchedulerTrackedFeature::kWebNfc: return {"WebNfc", "WebNfc"}; case WebSchedulerTrackedFeature::kWebFileSystem: return {"WebFileSystem", "WebFileSystem"}; case WebSchedulerTrackedFeature::kAppBanner: return {"AppBanner", "AppBanner"}; case WebSchedulerTrackedFeature::kPrinting: return {"Printing", "Printing"}; case WebSchedulerTrackedFeature::kWebDatabase: return {"WebDatabase", "WebDatabase"}; case WebSchedulerTrackedFeature::kPictureInPicture: return {"PictureInPicture", "PictureInPicture"}; case WebSchedulerTrackedFeature::kPortal: return {"Portal", "Portal"}; case WebSchedulerTrackedFeature::kSpeechRecognizer: return {"SpeechRecognizer", "SpeechRecognizer"}; case WebSchedulerTrackedFeature::kIdleManager: return {"IdleManager", "IdleManager"}; case WebSchedulerTrackedFeature::kPaymentManager: return {"PaymentManager", "PaymentManager"}; case WebSchedulerTrackedFeature::kSpeechSynthesis: return {"SpeechSynthesis", "SpeechSynthesis"}; case WebSchedulerTrackedFeature::kKeyboardLock: return {"KeyboardLock", "KeyboardLock"}; case WebSchedulerTrackedFeature::kWebOTPService: return {"WebOTPService", "SMSService"}; case WebSchedulerTrackedFeature::kOutstandingNetworkRequestDirectSocket: return {"OutstandingNetworkRequestDirectSocket", "outstanding network request (direct socket)"}; case WebSchedulerTrackedFeature::kIsolatedWorldScript: return {"IsolatedWorldScript", "Isolated world ran script"}; case WebSchedulerTrackedFeature::kInjectedStyleSheet: return {"InjectedStyleSheet", "External systesheet injected"}; case WebSchedulerTrackedFeature::kMediaSessionImplOnServiceCreated: return {"MediaSessionImplOnServiceCreated", "MediaSessionImplOnServiceCreated"}; } return {}; } std::map<std::string, WebSchedulerTrackedFeature> MakeShortNameToFeature() { std::map<std::string, WebSchedulerTrackedFeature> short_name_to_feature; for (int i = 0; i <= static_cast<int>(WebSchedulerTrackedFeature::kMaxValue); i++) { WebSchedulerTrackedFeature feature = static_cast<WebSchedulerTrackedFeature>(i); FeatureNames strs = FeatureToNames(feature); if (strs.short_name.size()) short_name_to_feature[strs.short_name] = feature; } return short_name_to_feature; } const std::map<std::string, WebSchedulerTrackedFeature>& ShortStringToFeatureMap() { static const std::map<std::string, WebSchedulerTrackedFeature> short_name_to_feature = MakeShortNameToFeature(); return short_name_to_feature; } } // namespace std::string FeatureToHumanReadableString(WebSchedulerTrackedFeature feature) { return FeatureToNames(feature).human_readable; } absl::optional<WebSchedulerTrackedFeature> StringToFeature( const std::string& str) { auto map = ShortStringToFeatureMap(); auto it = map.find(str); if (it == map.end()) { return absl::nullopt; } return it->second; } bool IsFeatureSticky(WebSchedulerTrackedFeature feature) { return (FeatureToBit(feature) & StickyFeaturesBitmask()) > 0; } uint64_t StickyFeaturesBitmask() { return FeatureToBit( WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore) | FeatureToBit( WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoCache) | FeatureToBit( WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoStore) | FeatureToBit( WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoCache) | FeatureToBit(WebSchedulerTrackedFeature::kPageShowEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kPageHideEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kBeforeUnloadEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kUnloadEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kFreezeEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kResumeEventListener) | FeatureToBit(WebSchedulerTrackedFeature::kContainsPlugins) | FeatureToBit(WebSchedulerTrackedFeature::kDocumentLoaded) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedGeolocationPermission) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedNotificationsPermission) | FeatureToBit(WebSchedulerTrackedFeature::kRequestedMIDIPermission) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedAudioCapturePermission) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedVideoCapturePermission) | FeatureToBit(WebSchedulerTrackedFeature:: kRequestedBackForwardCacheBlockedSensors) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedBackgroundWorkPermission) | FeatureToBit(WebSchedulerTrackedFeature::kWebLocks) | FeatureToBit( WebSchedulerTrackedFeature::kRequestedStorageAccessGrant) | FeatureToBit(WebSchedulerTrackedFeature::kWebNfc) | FeatureToBit(WebSchedulerTrackedFeature::kWebFileSystem) | FeatureToBit(WebSchedulerTrackedFeature::kAppBanner) | FeatureToBit(WebSchedulerTrackedFeature::kPrinting) | FeatureToBit(WebSchedulerTrackedFeature::kPictureInPicture) | FeatureToBit(WebSchedulerTrackedFeature::kIdleManager) | FeatureToBit(WebSchedulerTrackedFeature::kPaymentManager) | FeatureToBit(WebSchedulerTrackedFeature::kKeyboardLock) | FeatureToBit(WebSchedulerTrackedFeature::kWebOTPService) | FeatureToBit(WebSchedulerTrackedFeature::kIsolatedWorldScript) | FeatureToBit(WebSchedulerTrackedFeature::kInjectedStyleSheet); } } // namespace scheduler } // namespace blink
47.855319
84
0.746221
DamieFC
c9fceef901b20ec1fb7883d7985fb2b7bb9020f2
360
cpp
C++
src/triangulo.cpp
Italo1994/Laboratorio2-IMD0030
ebe3df127ec78914d2feca77f92bf398e61c023c
[ "MIT" ]
null
null
null
src/triangulo.cpp
Italo1994/Laboratorio2-IMD0030
ebe3df127ec78914d2feca77f92bf398e61c023c
[ "MIT" ]
null
null
null
src/triangulo.cpp
Italo1994/Laboratorio2-IMD0030
ebe3df127ec78914d2feca77f92bf398e61c023c
[ "MIT" ]
null
null
null
#include "triangulo.h" Triangulo::Triangulo(int b, int a, int l1, int l2, int l3): base (b), altura(a), lado1(l1), lado2(l2), lado3(l3) { area = (base * altura) / 2; perimetro = lado1 + lado2 + lado3; } Triangulo::~Triangulo(){ } int Triangulo::getAreaTriangulo(){ return area; } int Triangulo::getPerimetroTriangulo(){ return perimetro; }
20
115
0.65
Italo1994
c9fcf751bcf9da261f8b409fd9bc9e802f0eabb5
15,449
cpp
C++
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
tallestorange/webrtc-apis
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
tallestorange/webrtc-apis
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
tallestorange/webrtc-apis
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
[ "BSD-3-Clause" ]
null
null
null
#include "impl_org_webRtc_WebRtcFactory.h" #include "impl_org_webRtc_WebRtcFactoryConfiguration.h" #include "impl_org_webRtc_WebRtcLib.h" #include "impl_org_webRtc_AudioBufferEvent.h" #include "impl_org_webRtc_AudioProcessingInitializeEvent.h" #include "impl_org_webRtc_AudioProcessingRuntimeSettingEvent.h" #include "impl_org_webRtc_helpers.h" #include "impl_webrtc_IAudioDeviceWasapi.h" #include "impl_org_webRtc_pre_include.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/peerconnectioninterface.h" #include "api/peerconnectionfactoryproxy.h" #include "api/test/fakeconstraints.h" #include "rtc_base/event_tracer.h" #include "third_party/winuwp_h264/winuwp_h264_factory.h" #include "media/engine/webrtcvideocapturerfactory.h" #include "pc/peerconnectionfactory.h" #include "modules/audio_device/include/audio_device.h" #include "impl_org_webRtc_post_include.h" #include <zsLib/eventing/IHelper.h> #include <zsLib/SafeInt.h> using ::zsLib::String; using ::zsLib::Optional; using ::zsLib::Any; using ::zsLib::AnyPtr; using ::zsLib::AnyHolder; using ::zsLib::Promise; using ::zsLib::PromisePtr; using ::zsLib::PromiseWithHolder; using ::zsLib::PromiseWithHolderPtr; using ::zsLib::eventing::SecureByteBlock; using ::zsLib::eventing::SecureByteBlockPtr; using ::std::shared_ptr; using ::std::weak_ptr; using ::std::make_shared; using ::std::list; using ::std::set; using ::std::map; // borrow definitions from class ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcFactory::WrapperImplType, WrapperImplType); ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::WrapperType, WrapperType); ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcLib, UseWebRtcLib); ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcFactoryConfiguration, UseFactoryConfiguration); typedef WrapperImplType::PeerConnectionFactoryInterfaceScopedPtr PeerConnectionFactoryInterfaceScopedPtr; typedef WrapperImplType::PeerConnectionFactoryScopedPtr PeerConnectionFactoryScopedPtr; ZS_DECLARE_TYPEDEF_PTR(::webrtc::PeerConnectionFactory, NativePeerConnectionFactory) ZS_DECLARE_TYPEDEF_PTR(::webrtc::PeerConnectionFactoryInterface, NativePeerConnectionFactoryInterface) ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseVideoDeviceCaptureFacrtory, UseVideoDeviceCaptureFacrtory); ZS_DECLARE_TYPEDEF_PTR(::cricket::WebRtcVideoDeviceCapturerFactory, UseWebrtcVideoDeviceCaptureFacrtory); ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioBufferEvent, UseAudioBufferEvent); ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioInitEvent, UseAudioInitEvent); ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioRuntimeEvent, UseAudioRuntimeEvent); namespace wrapper { namespace impl { namespace org { namespace webRtc { ZS_DECLARE_SUBSYSTEM(wrapper_org_webRtc); } } } } //------------------------------------------------------------------------------ WrapperImplType::WebrtcObserver::WebrtcObserver( WrapperImplTypePtr wrapper, zsLib::IMessageQueuePtr queue, std::function<void(UseAudioBufferEventPtr)> bufferEvent, std::function<void(UseAudioInitEventPtr)> initEvent, std::function<void(UseAudioRuntimeEventPtr)> runtimeEvent ) noexcept : outer_(wrapper), queue_(queue), bufferEvent_(std::move(bufferEvent)), initEvent_(std::move(initEvent)), runtimeEvent_(std::move(runtimeEvent)) { } //------------------------------------------------------------------------------ void WrapperImplType::WebrtcObserver::Initialize(int sample_rate_hz, int num_channels) { if (!enabled_) return; auto outer = outer_.lock(); if (!outer) return; WebrtcObserver *pThis = this; HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); std::function<void(void)> callback = [handle]() { ::SetEvent(handle); }; auto event = UseAudioInitEvent::toWrapper(std::move(callback), SafeInt<size_t>(sample_rate_hz), SafeInt<size_t>(num_channels)); queue_->postClosure([outer, event, pThis]() { pThis->initEvent_(event); }); event.reset(); ::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */); ::CloseHandle(handle); } //------------------------------------------------------------------------------ void WrapperImplType::WebrtcObserver::Process(NativeAudioBufferType* audio) { if (!enabled_) return; auto outer = outer_.lock(); if (!outer) return; WebrtcObserver *pThis = this; HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); std::function<void(void)> callback = [handle]() { ::SetEvent(handle); }; auto event = UseAudioBufferEvent::toWrapper(std::move(callback), audio); queue_->postClosure([outer, event, pThis]() { pThis->bufferEvent_(event); }); event.reset(); ::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */); ::CloseHandle(handle); } //------------------------------------------------------------------------------ std::string WrapperImplType::WebrtcObserver::ToString() const { return "WrapperImplType::WebrtcObserver"; } //------------------------------------------------------------------------------ void WrapperImplType::WebrtcObserver::SetRuntimeSetting(::webrtc::AudioProcessing::RuntimeSetting setting) { if (!enabled_) return; auto outer = outer_.lock(); if (!outer) return; WebrtcObserver *pThis = this; HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); std::function<void(void)> callback = [handle]() { ::SetEvent(handle); }; auto event = UseAudioRuntimeEvent::toWrapper(std::move(callback), setting); queue_->postClosure([outer, event, pThis]() { pThis->runtimeEvent_(event); }); event.reset(); ::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */); ::CloseHandle(handle); } //------------------------------------------------------------------------------ NativePeerConnectionFactoryInterface *unproxy(NativePeerConnectionFactoryInterface *native) { if (!native) return native; return WRAPPER_DEPROXIFY_CLASS(::webrtc::PeerConnectionFactory, ::webrtc::PeerConnectionFactory, native); } //------------------------------------------------------------------------------ wrapper::impl::org::webRtc::WebRtcFactory::WebRtcFactory() noexcept { } //------------------------------------------------------------------------------ wrapper::org::webRtc::WebRtcFactoryPtr wrapper::org::webRtc::WebRtcFactory::wrapper_create() noexcept { auto pThis = make_shared<wrapper::impl::org::webRtc::WebRtcFactory>(); pThis->thisWeak_ = pThis; return pThis; } //------------------------------------------------------------------------------ wrapper::impl::org::webRtc::WebRtcFactory::~WebRtcFactory() noexcept { thisWeak_.reset(); wrapper_dispose(); } //------------------------------------------------------------------------------ void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_dispose() noexcept { zsLib::AutoRecursiveLock lock(lock_); if (!peerConnectionFactory_) return; // Peer connection factory holds ownership of these objects so the observers // are no longer accessible. audioPostCapture_ = NULL; audioPreRender_ = NULL; // reset the factory (cannot be used anymore)... peerConnectionFactory_ = PeerConnectionFactoryInterfaceScopedPtr(); videoDeviceCaptureFactory_.reset(); #pragma ZS_BUILD_NOTE("TODO","(mosa) shutdown threads need something more?") networkThread.reset(); workerThread.reset(); signalingThread.reset(); configuration_.reset(); audioPostCaptureInit_.reset(); audioPreRenderInit_.reset(); } //------------------------------------------------------------------------------ void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_init_org_webRtc_WebRtcFactory(wrapper::org::webRtc::WebRtcFactoryConfigurationPtr inConfiguration) noexcept { configuration_ = UseFactoryConfiguration::clone(inConfiguration); audioPostCaptureInit_ = std::make_unique<WebrtcObserver>( thisWeak_.lock(), UseWebRtcLib::audioCaptureFrameProcessingQueue(), [this](UseAudioBufferEventPtr event) { this->onAudioPostCapture_Process(std::move(event)); }, [this](UseAudioInitEventPtr event) { this->onAudioPostCapture_Init(std::move(event)); }, [this](UseAudioRuntimeEventPtr event) { this->onAudioPostCapture_SetRuntimeSetting(std::move(event)); } ); audioPreRenderInit_ = std::make_unique<WebrtcObserver>( thisWeak_.lock(), UseWebRtcLib::audioRenderFrameProcessingQueue(), [this](UseAudioBufferEventPtr event) { this->onAudioPreRender_Process(std::move(event)); }, [this](UseAudioInitEventPtr event) { this->onAudioPreRender_Init(std::move(event)); }, [this](UseAudioRuntimeEventPtr event) { this->onAudioPreRender_SetRuntimeSetting(std::move(event)); } ); audioPostCapture_ = audioPostCaptureInit_.get(); audioPreRender_ = audioPreRenderInit_.get(); } //------------------------------------------------------------------------------ void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_onObserverCountChanged(size_t count) noexcept { zsLib::AutoRecursiveLock lock(lock_); if ((NULL == audioPostCapture_) || (NULL == audioPreRender_)) return; if ((configuration_) && (count > 0)) { configuration_->enableAudioBufferEvents = true; } audioPostCapture_->enabled(count > 0); audioPreRender_->enabled(count > 0); } //------------------------------------------------------------------------------ PeerConnectionFactoryInterfaceScopedPtr WrapperImplType::peerConnectionFactory() noexcept { zsLib::AutoRecursiveLock lock(lock_); setup(); return peerConnectionFactory_; } //------------------------------------------------------------------------------ PeerConnectionFactoryScopedPtr WrapperImplType::realPeerConnectionFactory() noexcept { zsLib::AutoRecursiveLock lock(lock_); setup(); auto realInterface = unproxy(peerConnectionFactory_); return dynamic_cast<NativePeerConnectionFactory *>(realInterface); } //------------------------------------------------------------------------------ UseVideoDeviceCaptureFacrtoryPtr WrapperImplType::videoDeviceCaptureFactory() noexcept { zsLib::AutoRecursiveLock lock(lock_); setup(); return videoDeviceCaptureFactory_; } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPostCapture_Init(UseAudioInitEventPtr event) { onAudioPostCaptureInitialize(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPostCapture_SetRuntimeSetting(UseAudioRuntimeEventPtr event) { onAudioPostCaptureRuntimeSetting(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPostCapture_Process(UseAudioBufferEventPtr event) { onAudioPostCapture(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPreRender_Init(UseAudioInitEventPtr event) { onAudioPreRenderInitialize(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPreRender_SetRuntimeSetting(UseAudioRuntimeEventPtr event) { onAudioPreRenderRuntimeSetting(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::onAudioPreRender_Process(UseAudioBufferEventPtr event) { onAudioPreRender(std::move(event)); } //------------------------------------------------------------------------------ void WrapperImplType::setup() noexcept { zsLib::AutoRecursiveLock lock(lock_); // already setup? if ((!audioPostCaptureInit_) || (!audioPreRenderInit_)) return; bool audioCapturingEnabled = configuration_ ? configuration_->audioCapturingEnabled : true; bool audioRenderingEnabled = configuration_ ? configuration_->audioRenderingEnabled : true; String audioCaptureDeviceId = configuration_ ? configuration_->audioCaptureDeviceId : String(); String audioRenderDeviceId = configuration_ ? configuration_->audioRenderDeviceId : String(); bool enableAudioProcessingEvents = configuration_ ? configuration_->enableAudioBufferEvents : false; networkThread = rtc::Thread::CreateWithSocketServer(); networkThread->Start(); workerThread = rtc::Thread::Create(); workerThread->Start(); signalingThread = rtc::Thread::Create(); signalingThread->Start(); auto encoderFactory = new ::webrtc::WinUWPH264EncoderFactory(); auto decoderFactory = new ::webrtc::WinUWPH264DecoderFactory(); rtc::scoped_refptr<::webrtc::AudioDeviceModule> audioDeviceModule; audioDeviceModule = workerThread->Invoke<rtc::scoped_refptr<::webrtc::AudioDeviceModule>>( RTC_FROM_HERE, [audioCapturingEnabled, audioRenderingEnabled]() { webrtc::IAudioDeviceWasapi::CreationProperties props; props.id_ = ""; props.playoutEnabled_ = audioRenderingEnabled; props.recordingEnabled_ = audioCapturingEnabled; return rtc::scoped_refptr<::webrtc::AudioDeviceModule>(webrtc::IAudioDeviceWasapi::create(props)); }); if (audioCaptureDeviceId.size() != 0) { int deviceCount = audioDeviceModule->RecordingDevices(); char deviceName[::webrtc::kAdmMaxDeviceNameSize]; char deviceId[::webrtc::kAdmMaxGuidSize]; uint16_t deviceIndex = USHRT_MAX; for (uint16_t i = 0; i < deviceCount; i++) { audioDeviceModule->RecordingDeviceName(i, deviceName, deviceId); if (strcmp(audioCaptureDeviceId.c_str(), deviceId) == 0) { deviceIndex = i; break; } } if (deviceIndex != USHRT_MAX) audioDeviceModule->SetRecordingDevice(deviceIndex); } if (audioRenderDeviceId.size() != 0) { int deviceCount = audioDeviceModule->PlayoutDevices(); char deviceName[::webrtc::kAdmMaxDeviceNameSize]; char deviceId[::webrtc::kAdmMaxGuidSize]; uint16_t deviceIndex = USHRT_MAX; for (uint16_t i = 0; i < deviceCount; i++) { audioDeviceModule->PlayoutDeviceName(i, deviceName, deviceId); if (strcmp(audioRenderDeviceId.c_str(), deviceId) == 0) { deviceIndex = i; break; } } if (deviceIndex != USHRT_MAX) audioDeviceModule->SetPlayoutDevice(deviceIndex); } rtc::scoped_refptr<::webrtc::AudioProcessing> audioProcessing; if (enableAudioProcessingEvents) audioProcessing = rtc::scoped_refptr<::webrtc::AudioProcessing>{::webrtc::AudioProcessingBuilder().SetCapturePostProcessing(std::move(audioPostCaptureInit_)).SetRenderPreProcessing(std::move(audioPreRenderInit_)).Create() }; audioPostCaptureInit_.reset(); audioPreRenderInit_.reset(); peerConnectionFactory_ = ::webrtc::CreatePeerConnectionFactory( networkThread.get(), workerThread.get(), signalingThread.get(), audioDeviceModule.release(), ::webrtc::CreateBuiltinAudioEncoderFactory(), ::webrtc::CreateBuiltinAudioDecoderFactory(), encoderFactory, decoderFactory, nullptr, enableAudioProcessingEvents ? audioProcessing : nullptr ); #ifdef _WIN32 videoDeviceCaptureFactory_ = make_shared<::cricket::WebRtcVideoDeviceCapturerFactory>(); #else #error PLATFORM REQUIRES FACTORY #endif //_WIN32 } //------------------------------------------------------------------------------ WrapperImplTypePtr WrapperImplType::toWrapper(WrapperTypePtr wrapper) noexcept { if (!wrapper) return WrapperImplTypePtr(); auto converted = ZS_DYNAMIC_PTR_CAST(WrapperImplType, wrapper); return converted; }
36.609005
228
0.677131
tallestorange
c9fdfafe4c4b3e567b497ef5910d12fe02001249
3,901
cc
C++
paddle/fluid/framework/ir/memory_optimize_pass/while_op_eager_deletion_pass.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
17,085
2016-11-18T06:40:52.000Z
2022-03-31T22:52:32.000Z
paddle/fluid/framework/ir/memory_optimize_pass/while_op_eager_deletion_pass.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
29,769
2016-11-18T06:35:22.000Z
2022-03-31T16:46:15.000Z
paddle/fluid/framework/ir/memory_optimize_pass/while_op_eager_deletion_pass.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
4,641
2016-11-18T07:43:33.000Z
2022-03-31T15:15:02.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/computation_op_handle.h" #include "paddle/fluid/framework/details/multi_devices_helper.h" #include "paddle/fluid/framework/ir/graph_helper.h" #include "paddle/fluid/operators/controlflow/op_variant.h" #include "paddle/fluid/operators/controlflow/while_op_helper.h" namespace paddle { namespace framework { namespace ir { using OpVariant = operators::OpVariant; class WhileOpEagerDeletionPass : public ir::Pass { protected: void ApplyImpl(ir::Graph *graph) const override { if (!graph->IsMainGraph()) { // TODO(zhhsplendid): the WhileOpEagerDeletionPass is based on old Graph, // which only applies to the main block graph. The new Eager Deletion // Technical can be added after we write new while_op based on SubGraph // instead of SubBlock return; } auto all_ops = ir::FilterByNodeWrapper<details::OpHandleBase>(*graph); // Find all while_op and while_grad_op. In case of @to_static, graph // may be constructed only by forward or backward program, so we use // OpVariant here instead of OperatorBase. std::unordered_map< size_t, std::pair<std::vector<OpVariant>, std::vector<OpVariant>>> target_ops; for (auto *op : all_ops) { auto compute_op = dynamic_cast<details::ComputationOpHandle *>(op); if (compute_op == nullptr) continue; if (compute_op->Name() == "while") { target_ops[compute_op->GetScopeIdx()].first.emplace_back( compute_op->GetOp()); } else if (compute_op->Name() == "while_grad") { target_ops[compute_op->GetScopeIdx()].second.emplace_back( compute_op->GetOp()); } } if (graph->IsConstructedByPartialProgram()) { VLOG(4) << "Is Paritial Program"; PADDLE_ENFORCE_LE( target_ops.size(), 1, platform::errors::InvalidArgument( "Unsupported multi device if graph is constructed by " "partial program.")); size_t scope_idx = 0; auto &while_ops = target_ops[scope_idx].first; auto &while_grad_ops = target_ops[scope_idx].second; auto all_ops = graph->OriginProgram().Block(0).AllOps(); if (while_ops.empty()) { operators::AppendOpVariantByOpName(all_ops, std::string("while"), &while_ops); } else if (while_grad_ops.empty()) { operators::AppendOpVariantByOpName(all_ops, std::string("while_grad"), &while_grad_ops); } else { PADDLE_THROW("One of while_ops or while_grad_ops should be empty."); } } for (auto &ops_pair : target_ops) { VLOG(4) << "Scope Idx = " << ops_pair.first; auto &while_ops = ops_pair.second.first; VLOG(4) << "while_ops.size() = " << while_ops.size(); auto &while_grad_ops = ops_pair.second.second; VLOG(4) << "while_grad_ops.size() = " << while_grad_ops.size(); operators::PrepareSafeEagerDeletionOnWhileOpAndWhileGradOp( graph->OriginProgram(), while_ops, while_grad_ops); } } }; } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(while_op_eager_deletion_pass, paddle::framework::ir::WhileOpEagerDeletionPass);
40.216495
79
0.66829
zmxdream
a00293545a9fb8ed884163cac2906093759d1645
4,969
cc
C++
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
// Copyright 2020 The v8App Authors. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. #include "CppBridge/V8NativeObject.h" #include "CppBridge/V8ObjectTemplateBuilder.h" namespace v8App { namespace JSRuntime { namespace CppBridge { V8NativeObjectInfo *V8NativeObjectInfo::From(v8::Local<v8::Object> inObject) { if (inObject->InternalFieldCount() != kMaxReservedInternalFields) { return nullptr; } V8NativeObjectInfo *info = static_cast<V8NativeObjectInfo *>( inObject->GetAlignedPointerFromInternalField(kV8NativeObjectInfo)); return info; } V8NativeObjectBase::V8NativeObjectBase() = default; V8NativeObjectBase::~V8NativeObjectBase() { m_Object.Reset(); } V8ObjectTemplateBuilder V8NativeObjectBase::GetObjectTemplateBuilder(v8::Isolate *inIsolate) { return V8ObjectTemplateBuilder(inIsolate, GetTypeName()); } v8::Local<v8::ObjectTemplate> V8NativeObjectBase::GetOrCreateObjectTemplate(v8::Isolate *inIsolate, V8NativeObjectInfo *inInfo) { JSRuntime *runtime = JSRuntime::GetRuntime(inIsolate); v8::Local<v8::ObjectTemplate> objTemplate = runtime->GetObjectTemplate(inInfo); if (objTemplate.IsEmpty()) { objTemplate = GetObjectTemplateBuilder(inIsolate).Build(); CHECK_FALSE(objTemplate.IsEmpty()); runtime->SetObjectTemplate(inInfo, objTemplate); } CHECK_EQ(kMaxReservedInternalFields, objTemplate->InternalFieldCount()); return objTemplate; } const char *V8NativeObjectBase::GetTypeName() { return nullptr; } void V8NativeObjectBase::FirstWeakCallback(const v8::WeakCallbackInfo<V8NativeObjectBase> &inInfo) { V8NativeObjectBase *baseObject = inInfo.GetParameter(); baseObject->m_Destrying = true; baseObject->m_Object.Reset(); inInfo.SetSecondPassCallback(SecondWeakCallback); } void V8NativeObjectBase::SecondWeakCallback(const v8::WeakCallbackInfo<V8NativeObjectBase> &inInfo) { V8NativeObjectBase *baseObject = inInfo.GetParameter(); delete baseObject; } v8::MaybeLocal<v8::Object> V8NativeObjectBase::GetV8NativeObjectInternal(v8::Isolate *inIsolate, V8NativeObjectInfo *inInfo) { if (m_Object.IsEmpty() == false) { return v8::MaybeLocal<v8::Object>(v8::Local<v8::Object>::New(inIsolate, m_Object)); } if (m_Destrying) { return v8::MaybeLocal<v8::Object>(); } v8::Local<v8::ObjectTemplate> objTemplate = GetOrCreateObjectTemplate(inIsolate, inInfo); v8::Local<v8::Object> object; if (objTemplate->NewInstance(inIsolate->GetCurrentContext()).ToLocal(&object) == false) { delete this; return v8::MaybeLocal<v8::Object>(object); } int indexes[] = {kV8NativeObjectInfo, kV8NativeObjectInstance}; void *values[] = {inInfo, this}; object->SetAlignedPointerInInternalFields(2, indexes, values); m_Object.Reset(inIsolate, object); m_Object.SetWeak(this, FirstWeakCallback, v8::WeakCallbackType::kParameter); return v8::MaybeLocal<v8::Object>(object); } void *FromV8NativeObjectInternal(v8::Isolate *inIsolate, v8::Local<v8::Value> inValue, V8NativeObjectInfo *inInfo) { if (inValue->IsObject() == false) { return nullptr; } v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(inValue); //we should at a min have kMaxReservedInternalFields fields if (object->InternalFieldCount() < kMaxReservedInternalFields) { return nullptr; } V8NativeObjectInfo *info = V8NativeObjectInfo::From(object); if (info == nullptr) { return nullptr; } if (info != inInfo) { return nullptr; } return object->GetAlignedPointerFromInternalField(kV8NativeObjectInstance); } } } }
37.643939
139
0.546388
v8App
a0037d69dffd17fb983fcbb45ab1fdc85f09292b
827
cpp
C++
serverapp/src/db/SystemPlan.cpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
serverapp/src/db/SystemPlan.cpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
serverapp/src/db/SystemPlan.cpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
#include "SystemPlan.hpp" #include "SystemProvider.hpp" #include "CardProvider.hpp" using namespace db; SystemPlan::SystemPlan() : m_systemId(data::SystemData::universal), m_cards() {} SystemPlan::SystemPlan(const System& system) : m_systemId(system.id()), m_cards() { fillCards(system); } void SystemPlan::fillCards(const System& system) { m_cards.resize(system.size()); std::transform(system.cards().cbegin(), system.cards().cend(), m_cards.begin(), [](const Card& card) { return card.id(); }); } db::SystemPlan::System_ptr SystemPlan::load(const SystemProvider& sp, const CardProvider& cp) { auto system = std::make_unique<System>(sp.get(m_systemId)); for (const auto& cardId : m_cards) { if (!system->tryAddCard(cp.get(cardId))) return nullptr; } return std::move(system); } // end load
27.566667
80
0.697703
mjgerdes
a006086cc4e575c937f9df394afc6c76d7b60e8b
3,603
cpp
C++
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/abc070/tasks/abc070_d D - Transit Tree PathEditorial // ソースコードの引用元 : https://atcoder.jp/contests/abc070/submissions/7677426 // 提出ID : 7677426 // 問題ID : abc070_d // コンテストID : abc070 // ユーザID : xryuseix // コード長 : 3404 // 実行時間 : 232 */ #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <cctype> #include <climits> #include <string> #include <bitset> #include <cfloat> using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<int> vi; typedef vector<char> vc; typedef vector<double> vd; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pair<int, int>> vpii; typedef vector<vector<int>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; typedef vector<vector<ll>> vvll; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rrep(i, n) for (int i = 1; i <= (n); ++i) #define drep(i, n) for (int i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << endl #define STI(s) atoi(s.c_str()) #define mp(p, q) make_pair(p, q) #define pb(n) push_back(n) #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define Sort(a) sort(a.begin(), a.end()) #define Rort(a) sort(a.rbegin(), a.rend()) template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } const int P = 1000000007; const int INF = INT_MAX; const ll LLINF = 1LL << 60; class DIJKSTRA { public: int V; struct dk_edge { int to; ll cost; }; typedef pair<ll, int> PI; // firstは最短距離、secondは頂点の番号 vector<vector<dk_edge> > G; vector<ll> d; //これ答え。d[i]:=V[i]までの最短距離 vector<int> prev; //経路復元 DIJKSTRA(int size) { V = size; G = vector<vector<dk_edge> >(V); prev = vector<int>(V, -1); } void add(int from, int to, ll cost) { dk_edge e = {to, cost}; G[from].push_back(e); } void dijkstra(int s) { // greater<P>を指定することでfirstが小さい順に取り出せるようにする priority_queue<PI, vector<PI>, greater<PI> > que; d = vector<ll>(V, LLINF); d[s] = 0; que.push(PI(0, s)); while (!que.empty()) { PI p = que.top(); que.pop(); int v = p.second; if (d[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { dk_edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; prev[e.to] = v; que.push(PI(d[e.to], e.to)); } } } } vector<int> get_path(int t) { vector<int> path; for (; t != -1; t = prev[t]) { // tがsになるまでprev[t]をたどっていく path.push_back(t); } //このままだとt->sの順になっているので逆順にする reverse(path.begin(), path.end()); return path; } void show(void) { for (int i = 0; i < d.size() - 1; i++) { cout << d[i] << " "; } cout << d[d.size() - 1] << endl; } }; int main(void) { ios::sync_with_stdio(false); cin.tie(0); ////////////////////////////////////////////////////// ll n; cin >> n; ll a, b, c; DIJKSTRA wa(n); rep(i, n - 1) { cin >> a >> b >> c; a--; b--; wa.add(a, b, c); wa.add(b, a, c); } ll q, k; cin >> q >> k; ll x, y; k--; wa.dijkstra(k); // wa.show(); rep(i, q) { cin >> x >> y; x--; y--; fin((ll)wa.d[x] + (ll)wa.d[y]); } ////////////////////////////////////////////////////// return 0; }
21.070175
70
0.541216
xryuseix
a0093081a33b7c151b80af4a84cfecacdc5dd687
3,068
cpp
C++
apps/JAWS3/jaws3/THYBRID_Concurrency.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
apps/JAWS3/jaws3/THYBRID_Concurrency.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
apps/JAWS3/jaws3/THYBRID_Concurrency.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: THYBRID_Concurrency.cpp 91813 2010-09-17 07:52:52Z johnnyw $ #include "ace/OS_NS_stdlib.h" #include "ace/Message_Block.h" #ifndef JAWS_BUILD_DLL #define JAWS_BUILD_DLL #endif #include "jaws3/Concurrency.h" #include "jaws3/THYBRID_Concurrency.h" #include "jaws3/Protocol_Handler.h" #include "jaws3/Options.h" JAWS_THYBRID_Concurrency::JAWS_THYBRID_Concurrency (void) : getting_ (0) , min_number_of_threads_ (1) , max_number_of_threads_ (-1) , shutdown_task_ (0) , error_ (0) { const char *value; value = JAWS_Options::instance ()->getenv ("JAWS_MIN_THYBRID_THREADS"); if (value != 0) this->min_number_of_threads_ = ACE_OS::atoi (value); else this->min_number_of_threads_ = ACE_OS::atoi (JAWS_DEFAULT_MIN_THYBRID_THREADS); if (this->min_number_of_threads_ <= 0) this->min_number_of_threads_ = 1; value = JAWS_Options::instance ()->getenv ("JAWS_MAX_THYBRID_THREADS"); if (value != 0) this->max_number_of_threads_ = ACE_OS::atoi (value); else this->max_number_of_threads_ = ACE_OS::atoi (JAWS_DEFAULT_MAX_THYBRID_THREADS); if (this->max_number_of_threads_ <= 0) this->max_number_of_threads_ = -1; else if (this->max_number_of_threads_ < this->min_number_of_threads_) this->max_number_of_threads_ = this->min_number_of_threads_; int r; r = this->activate (THR_BOUND | THR_JOINABLE, this->min_number_of_threads_); if (r < 0) { this->shutdown_task_ = 1; this->error_ = 1; } } int JAWS_THYBRID_Concurrency::putq (JAWS_Protocol_Handler *ph) { if (this->error_) return -1; JAWS_CONCURRENCY_TASK *task = this; int result = task->putq (& ph->mb_); if (result != -1) { if (this->getting_ < this->min_number_of_threads_ && (this->max_number_of_threads_ < 0 || this->thr_count () < (size_t) this->max_number_of_threads_)) { int r; r = this->activate ( THR_BOUND | THR_JOINABLE , 1 // number of threads , 1 // force active ); if (r < 0) { // ACE_ERROR return -1; } } } return result; } int JAWS_THYBRID_Concurrency::getq (JAWS_Protocol_Handler *&ph) { ph = 0; JAWS_CONCURRENCY_TASK *task = this; if (this->shutdown_task_ && task->msg_queue ()->message_count () == 0) return -1; int getting = ++(this->getting_); if (getting > this->min_number_of_threads_) { if (task->msg_queue ()->message_count () == 0) { --(this->getting_); return -1; } } ACE_Message_Block *mb = 0; int result = task->getq (mb); if (result != -1) { ph = (JAWS_Protocol_Handler *) mb->base (); if (ph == 0) { // Shutdown this task; this->shutdown_task_ = 1; if (this->getting_ > 1) { task->putq (mb); result = -1; } } } --(this->getting_); return result; }
23.419847
78
0.594524
cflowe
a00ad16a9c56394bfeb58832cc16f4bbf7192940
179
cpp
C++
avs_dx/DxVisualsShaders/dummy.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
33
2019-01-28T03:32:17.000Z
2022-02-12T18:17:26.000Z
avs_dx/DxVisualsShaders/dummy.cpp
visbot/vis_avs_dx
03e55f8932a97ad845ff223d3602ff2300c3d1d4
[ "MIT" ]
2
2019-11-18T17:54:58.000Z
2020-07-21T18:11:21.000Z
avs_dx/DxVisualsShaders/dummy.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
5
2019-02-16T23:00:11.000Z
2022-03-27T15:22:10.000Z
// A dummy function to make linker happy. This project doesn't contain any C++ code, it's workaround for the build system to compile HLSL shaders. void dxVisualsShadersDummy() { }
89.5
146
0.77095
Const-me
a0122b244080bddb8d9dd5a1bfd0dfabc0393fdf
18,257
cpp
C++
groups/bal/ball/ball_categorymanager.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/bal/ball/ball_categorymanager.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/bal/ball/ball_categorymanager.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// ball_categorymanager.cpp -*-C++-*- #include <ball_categorymanager.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(ball_categorymanager_cpp,"$Id$ $CSID$") #include <ball_severity.h> #include <ball_thresholdaggregate.h> #include <bdlb_bitutil.h> #include <bslmt_lockguard.h> #include <bslmt_readlockguard.h> #include <bslmt_writelockguard.h> #include <bsls_assert.h> #include <bsls_platform.h> #include <bsl_algorithm.h> #include <bsl_map.h> #include <bsl_utility.h> #include <bsl_vector.h> // Note: on Windows -> WinDef.h:#define max(a,b) ... #if defined(BSLS_PLATFORM_CMP_MSVC) && defined(max) #undef max #endif namespace BloombergLP { namespace ball { namespace { // ===================== // class CategoryProctor // ===================== class CategoryProctor { // This class facilitates exception neutrality by proctoring memory // management for 'Category' objects. // // This class should *not* be used directly by client code. It is an // implementation detail of the 'ball' logging system. // PRIVATE TYPES typedef bsl::vector<ball::Category *> CategoryVector; // DATA Category *d_category_p; // category object to delete on failure CategoryVector *d_categories_p; // category collection to rollback on // failure bslma::Allocator *d_allocator_p; // allocator for the category object private: // NOT IMPLEMENTED CategoryProctor(const CategoryProctor&); CategoryProctor& operator=(const CategoryProctor&); public: // CREATORS CategoryProctor(Category *category, bslma::Allocator *allocator); // Create a proctor to manage the specified 'category' object, // allocated with the specified 'allocator'. On this proctor's // destruction, unless release has been called, the 'category' will be // destroyed and its footprint deallocated. ~CategoryProctor(); // Rollback the owned objects to their initial state on failure. // MANIPULATORS void setCategories(CategoryVector *categories); // Take ownership of the 'categories' object to roll it back on // failure. void release(); // Release the ownership of all objects currently managed by this // proctor. }; // --------------------- // class CategoryProctor // --------------------- // CREATORS inline CategoryProctor::CategoryProctor(Category *category, bslma::Allocator *allocator) : d_category_p(category) , d_categories_p(0) , d_allocator_p(allocator) { } inline CategoryProctor::~CategoryProctor() { if (d_category_p) { d_category_p->~Category(); d_allocator_p->deallocate(d_category_p); } if (d_categories_p) { d_categories_p->pop_back(); } } // MANIPULATORS inline void CategoryProctor::setCategories(CategoryVector *categories) { d_categories_p = categories; } inline void CategoryProctor::release() { d_category_p = 0; d_categories_p = 0; } } // close unnamed namespace // For convenience, 'CategoryMap' defines the type of a 'CategoryManager' data // member. typedef bsl::map<const char *, int> CategoryMap; // --------------------- // class CategoryManager // --------------------- // PRIVATE MANIPULATORS Category *CategoryManager::addNewCategory(const char *categoryName, int recordLevel, int passLevel, int triggerLevel, int triggerAllLevel) { // Create a new category and add it to the collection of categories // and the category registry. Category *category = new (*d_allocator_p) Category(categoryName, recordLevel, passLevel, triggerLevel, triggerAllLevel, d_allocator_p); // rollback on failure CategoryProctor proctor(category, d_allocator_p); d_categories.push_back(category); proctor.setCategories(&d_categories); d_registry[category->categoryName()] = static_cast<int>(d_categories.size() - 1); proctor.release(); return category; } // CREATORS CategoryManager::~CategoryManager() { BSLS_ASSERT(d_allocator_p); for (int i = 0; i < length(); ++i) { d_categories[i]->~Category(); d_allocator_p->deallocate(d_categories[i]); } } // MANIPULATORS Category *CategoryManager::addCategory(const char *categoryName, int recordLevel, int passLevel, int triggerLevel, int triggerAllLevel) { return addCategory(0, categoryName, recordLevel, passLevel, triggerLevel, triggerAllLevel); } Category *CategoryManager::addCategory(CategoryHolder *categoryHolder, const char *categoryName, int recordLevel, int passLevel, int triggerLevel, int triggerAllLevel) { BSLS_ASSERT(categoryName); if (!Category::areValidThresholdLevels(recordLevel, passLevel, triggerLevel, triggerAllLevel)) { return 0; // RETURN } bslmt::WriteLockGuard<bslmt::ReaderWriterLock> registryGuard( &d_registryLock); CategoryMap::const_iterator iter = d_registry.find(categoryName); if (iter != d_registry.end()) { return 0; // RETURN } else { Category *category = addNewCategory(categoryName, recordLevel, passLevel, triggerLevel, triggerAllLevel); if (categoryHolder) { CategoryManagerImpUtil::linkCategoryHolder(category, categoryHolder); } registryGuard.release()->unlock(); bslmt::LockGuard<bslmt::Mutex> ruleSetGuard(&d_ruleSetMutex); for (int i = 0; i < RuleSet::maxNumRules(); ++i) { const Rule *rule = d_ruleSet.getRuleById(i); if (rule && rule->isMatch(category->categoryName())) { CategoryManagerImpUtil::enableRule(category, i); int threshold = ThresholdAggregate::maxLevel( rule->recordLevel(), rule->passLevel(), rule->triggerLevel(), rule->triggerAllLevel()); if (threshold > category->ruleThreshold()) { CategoryManagerImpUtil::setRuleThreshold(category, threshold); } } } // We have a 'writeLock' on 'd_registryLock' so the supplied category // holder is the only category holder for the created category. if (categoryHolder) { categoryHolder->setThreshold(bsl::max(category->threshold(), category->ruleThreshold())); } return category; // RETURN } } Category *CategoryManager::lookupCategory(const char *categoryName) { bslmt::ReadLockGuard<bslmt::ReaderWriterLock> registryGuard( &d_registryLock); CategoryMap::const_iterator iter = d_registry.find(categoryName); return iter != d_registry.end() ? d_categories[iter->second] : 0; } Category *CategoryManager::lookupCategory(CategoryHolder *categoryHolder, const char *categoryName) { d_registryLock.lockReadReserveWrite(); bslmt::WriteLockGuard<bslmt::ReaderWriterLock> registryGuard( &d_registryLock, 1); Category *category = 0; CategoryMap::const_iterator iter = d_registry.find(categoryName); if (iter != d_registry.end()) { category = d_categories[iter->second]; if (categoryHolder && !categoryHolder->category()) { d_registryLock.upgradeToWriteLock(); CategoryManagerImpUtil::linkCategoryHolder(category, categoryHolder); } } return category; } void CategoryManager::resetCategoryHolders() { // Intentionally not locking. This method should only be called just prior // to destroying the category manager. const int numCategories = length(); for (int i = 0; i < numCategories; ++i) { CategoryManagerImpUtil::resetCategoryHolders(d_categories[i]); } } Category *CategoryManager::setThresholdLevels(const char *categoryName, int recordLevel, int passLevel, int triggerLevel, int triggerAllLevel) { BSLS_ASSERT(categoryName); if (!Category::areValidThresholdLevels(recordLevel, passLevel, triggerLevel, triggerAllLevel)) { return 0; // RETURN } d_registryLock.lockReadReserveWrite(); bslmt::WriteLockGuard<bslmt::ReaderWriterLock> registryGuard( &d_registryLock, 1); CategoryMap::iterator iter = d_registry.find(categoryName); if (iter != d_registry.end()) { Category *category = d_categories[iter->second]; category->setLevels(recordLevel, passLevel, triggerLevel, triggerAllLevel); return category; // RETURN } else { d_registryLock.upgradeToWriteLock(); Category *category = addNewCategory(categoryName, recordLevel, passLevel, triggerLevel, triggerAllLevel); registryGuard.release(); d_registryLock.unlock(); bslmt::LockGuard<bslmt::Mutex> ruleSetGuard(&d_ruleSetMutex); for (int i = 0; i < RuleSet::maxNumRules(); ++i) { const Rule *rule = d_ruleSet.getRuleById(i); if (rule && rule->isMatch(category->categoryName())) { CategoryManagerImpUtil::enableRule(category, i); int threshold = ThresholdAggregate::maxLevel( rule->recordLevel(), rule->passLevel(), rule->triggerLevel(), rule->triggerAllLevel()); if (threshold > category->ruleThreshold()) { CategoryManagerImpUtil::setRuleThreshold(category, threshold); } } } // No need to update holders since the category was just newly created // and thus does not have any linked holders. return category; // RETURN } } int CategoryManager::addRule(const Rule& value) { bslmt::LockGuard<bslmt::Mutex> guard(&d_ruleSetMutex); int ruleId = d_ruleSet.addRule(value); if (ruleId < 0) { return 0; // RETURN } ++d_ruleSequenceNum; const Rule *rule = d_ruleSet.getRuleById(ruleId); for (int i = 0; i < length(); ++i) { Category *category = d_categories[i]; if (rule->isMatch(category->categoryName())) { CategoryManagerImpUtil::enableRule(category, ruleId); int threshold = ThresholdAggregate::maxLevel( rule->recordLevel(), rule->passLevel(), rule->triggerLevel(), rule->triggerAllLevel()); if (threshold > category->ruleThreshold()) { CategoryManagerImpUtil::setRuleThreshold(category, threshold); CategoryManagerImpUtil::updateThresholdForHolders(category); } } } return 1; } int CategoryManager::addRules(const RuleSet& ruleSet) { int count = 0; for (int i = 0; i < ruleSet.maxNumRules(); ++i) { const Rule *rule = ruleSet.getRuleById(i); if (rule) { count += addRule(*rule); } } return count; } int CategoryManager::removeRule(const Rule& value) { bslmt::LockGuard<bslmt::Mutex> guard(&d_ruleSetMutex); int ruleId = d_ruleSet.ruleId(value); if (ruleId < 0) { return 0; // RETURN } ++d_ruleSequenceNum; const Rule *rule = d_ruleSet.getRuleById(ruleId); for (int i = 0; i < length(); ++i) { Category *category = d_categories[i]; if (rule->isMatch(category->categoryName())) { CategoryManagerImpUtil::disableRule(category, ruleId); CategoryManagerImpUtil::setRuleThreshold(category, 0); RuleSet::MaskType relevantRuleMask = category->relevantRuleMask(); int j = 0; int numBits = bdlb::BitUtil::sizeInBits(relevantRuleMask); BSLS_ASSERT(numBits == RuleSet::maxNumRules()); while ((j = bdlb::BitUtil::numTrailingUnsetBits(relevantRuleMask)) != numBits) { relevantRuleMask = bdlb::BitUtil::withBitCleared(relevantRuleMask, j); const Rule *r = d_ruleSet.getRuleById(j); int threshold = ThresholdAggregate::maxLevel( r->recordLevel(), r->passLevel(), r->triggerLevel(), r->triggerAllLevel()); if (threshold > category->ruleThreshold()) { CategoryManagerImpUtil::setRuleThreshold(category, threshold); } } CategoryManagerImpUtil::updateThresholdForHolders(category); } } d_ruleSet.removeRuleById(ruleId); return 1; } int CategoryManager::removeRules(const RuleSet& ruleSet) { int count = 0; for (int i = 0; i < ruleSet.maxNumRules(); ++i) { const Rule *rule = ruleSet.getRuleById(i); if (rule) { count += removeRule(*rule); } } return count; } void CategoryManager::removeAllRules() { bslmt::LockGuard<bslmt::Mutex> guard(&d_ruleSetMutex); ++d_ruleSequenceNum; for (int i = 0; i < length(); ++i) { if (d_categories[i]->relevantRuleMask()) { CategoryManagerImpUtil::setRelevantRuleMask(d_categories[i], 0); CategoryManagerImpUtil::setRuleThreshold(d_categories[i], 0); CategoryManagerImpUtil::updateThresholdForHolders(d_categories[i]); } } d_ruleSet.removeAllRules(); } // ACCESSORS const Category *CategoryManager::lookupCategory(const char *categoryName) const { bslmt::ReadLockGuard<bslmt::ReaderWriterLock> registryGuard( &d_registryLock); CategoryMap::const_iterator iter = d_registry.find(categoryName); return iter != d_registry.end() ? d_categories[iter->second] : 0; } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
36.296223
79
0.502821
apaprocki
a0154cad5ee3f14c61a484da48ca2e2c15880a50
751
hpp
C++
src/common/transformations/include/transformations/common_optimizations/remove_multi_subgraph_op_dangling_params.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
null
null
null
src/common/transformations/include/transformations/common_optimizations/remove_multi_subgraph_op_dangling_params.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
null
null
null
src/common/transformations/include/transformations/common_optimizations/remove_multi_subgraph_op_dangling_params.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <openvino/pass/graph_rewrite.hpp> #include <transformations_visibility.hpp> #include <vector> namespace ov { namespace pass { class TRANSFORMATIONS_API RemoveMultiSubGraphOpDanglingParams; } // namespace pass } // namespace ov /* * @ingroup ie_transformation_common_api * @brief RemoveMultiSubGraphOpDanglingParams transformation * removed MultiSubGraphOp inputs which are not connected to other nodes * in the bodies of a MultiSubGraphOp */ class ov::pass::RemoveMultiSubGraphOpDanglingParams : public ov::pass::MatcherPass { public: NGRAPH_RTTI_DECLARATION; RemoveMultiSubGraphOpDanglingParams(); };
23.46875
84
0.782956
ryanloney
a0159dc3a92d4ff6155b45e980387d2581dc446c
2,110
cpp
C++
solutions/find_median_from_data_stream.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/find_median_from_data_stream.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/find_median_from_data_stream.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
// Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. // For example, // [2,3,4], the median is 3 // [2,3], the median is (2 + 3) / 2 = 2.5 // Design a data structure that supports the following two operations: // void addNum(int num) - Add a integer number from the data stream to the data structure. // double findMedian() - Return the median of all elements so far. // Example: // addNum(1) // addNum(2) // findMedian() -> 1.5 // addNum(3) // findMedian() -> 2 // Follow up: // If all integer numbers from the stream are between 0 and 100, how would you optimize it? // If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? // solution: heap class MedianFinder { public: /** initialize your data structure here. */ priority_queue<int> maxHeap; priority_queue<int,vector<int>,greater<int>> minHeap; int maxHeapSize = 0, minHeapSize = 0; MedianFinder() { } void addNum(int num) { if (maxHeapSize == 0 || maxHeap.top() >= num) { maxHeap.push(num); ++maxHeapSize; if (maxHeapSize>minHeapSize+1) { int topItem = maxHeap.top(); maxHeap.pop(); minHeap.push(topItem); --maxHeapSize; ++minHeapSize; } } else { minHeap.push(num); ++minHeapSize; if (minHeapSize>maxHeapSize) { int topItem = minHeap.top(); minHeap.pop(); maxHeap.push(topItem); ++maxHeapSize; --minHeapSize; } } } double findMedian() { if (maxHeapSize == minHeapSize) return (1.0*(maxHeap.top() + minHeap.top()))/2; return maxHeap.top(); } }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */
27.051282
167
0.574882
kmykoh97
a0173ef17d8c9b06cfdb019689f2eb2661e49b6f
807
cc
C++
Tests/KinematicLineFit_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
2
2020-04-21T18:24:55.000Z
2020-09-24T19:01:47.000Z
Tests/KinematicLineFit_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
45
2020-03-16T18:27:59.000Z
2022-01-13T05:18:35.000Z
Tests/KinematicLineFit_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
15
2020-02-21T01:10:49.000Z
2022-03-24T12:13:35.000Z
/* Original Author: S Middleton 2020 */ #include "KinKal/Trajectory/KinematicLine.hh" #include "KinKal/Tests/FitTest.hh" int main(int argc, char *argv[]){ KinKal::DVEC sigmas(0.5, 0.004, 0.5, 0.002, 0.4, 0.05); // expected parameter sigmas if(argc == 1){ cout << "Adding momentum constraint" << endl; std::vector<std::string> arguments; arguments.push_back(argv[0]); arguments.push_back("--constrainpar"); arguments.push_back("5"); arguments.push_back("--Bz"); arguments.push_back("0.0"); std::vector<char*> myargv; for (const auto& arg : arguments) myargv.push_back((char*)arg.data()); myargv.push_back(nullptr); return FitTest<KinematicLine>(myargv.size()-1,myargv.data(),sigmas); } else return FitTest<KinematicLine>(argc,argv,sigmas); }
32.28
86
0.665428
orionning676
a0174acc6305ac4def91ae9040c200768e5cf6db
630
cpp
C++
dotNetInstallerLib/Schema.cpp
baSSiLL/dotnetinstaller
2a983649553cd322f674fe06685f0c1d47f638b2
[ "MIT" ]
null
null
null
dotNetInstallerLib/Schema.cpp
baSSiLL/dotnetinstaller
2a983649553cd322f674fe06685f0c1d47f638b2
[ "MIT" ]
null
null
null
dotNetInstallerLib/Schema.cpp
baSSiLL/dotnetinstaller
2a983649553cd322f674fe06685f0c1d47f638b2
[ "MIT" ]
1
2020-04-30T10:25:58.000Z
2020-04-30T10:25:58.000Z
#include "StdAfx.h" #include "Schema.h" #include "InstallerLog.h" Schema::Schema() : generator(L"dotNetInstaller InstallerEditor") , version(L"1") { } void Schema::Load(TiXmlElement * node) { CHECK_BOOL(node != NULL, L"Expected 'schema' node"); CHECK_BOOL(0 == strcmp(node->Value(), "schema"), L"Expected 'schema' node, got '" << DVLib::string2wstring(node->Value()) << L"'"); version = DVLib::UTF8string2wstring(node->Attribute("version")); generator = DVLib::UTF8string2wstring(node->Attribute("generator")); LOG(L"Loaded schema: version=" << version << L", generator=" << generator); }
25.2
85
0.653968
baSSiLL
a01903a488a67c23fda4047cd668a16ad59506b9
7,238
hpp
C++
xvm/xvm.hpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
15
2018-11-10T11:30:09.000Z
2022-02-28T06:00:57.000Z
xvm/xvm.hpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
null
null
null
xvm/xvm.hpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
10
2019-06-19T03:33:53.000Z
2021-08-20T01:24:42.000Z
#ifndef __XSCRIPT_XVM_HPP__ #define __XSCRIPT_XVM_HPP__ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdarg.h> #include <time.h> #include <ctype.h> #include <assert.h> #include <vector> #include "xvm_interface.hpp" #include "../common/instruction.hpp" #include "../common/utility.hpp" namespace xscript { namespace xvm { //script loading #define EXEC_FILE_EXT ".XSE" #define XSE_ID_STRING "XSE0" #define MAJOR_VERSION 0 #define MINOR_VERSION 8 #define MAX_THREAD_COUNT 1024//the maximum number of scripts that can be loaded at once. #define DEF_STACK_SIZE 1024 #define MAX_COERCION_STRING_SIZE 64//the maximum allocated space for a string coercion #define MAX_HOST_API_SIZE 1024//maximum number of functions in the host API #define MAX_FUNC_NAME_SIZE 256 //multithreading #define THREAD_PRIORITY_DUR_LOW 20//low-priority thread timeslice #define THREAD_PRIORITY_DUR_MED 40 #define THREAD_PRIORITY_DUR_HIGH 80 enum XVM_THREAD_MODE { THREAD_MODE_MULTI = 0, THREAD_MODE_SINGLE, }; //runtime value struct xvm_value { int type; union { int int_literal; float float_literal; //char* string_literal; int string_index; int stack_index; int instruction_index; int function_index; int host_api_index; int reg; }; int offset_index; }; typedef std::vector<xvm_value> value_vector; //runtime stack struct runtime_stack { value_vector elements; int size; int top; int frame; }; //functions struct function { int entry_point; int param_count; int local_data_size; int stack_frame_size; string name; }; typedef std::vector<function> function_vector; //instruction struct xvm_code { int opcode; int opcount; value_vector oplist; }; typedef std::vector<xvm_code> xvm_code_vector; struct xvm_code_stream { xvm_code_vector codes; int current_code; }; //host API call typedef std::vector<std::string> string_vector; //script struct script { bool is_active;//is this script structure in use //header data int global_data_size; int is_main_function_present; int main_function_index; //runtime tracking bool is_running; bool is_paused; int pause_end_time; //threading int timeslice_duration; //register file xvm_value _RetVal; //script data function_vector function_table; xvm_code_stream code_stream; string_vector host_api_table; string_vector string_table; runtime_stack stack; }; //host API struct host_api_function { int is_active; int thread_index; string name; host_api_function_ptr function; }; //Macros #define resolve_stack_index(index) (index < 0 ? index += scripts[current_thread].stack.frame : index) #define is_valid_thread_index(index) (index < 0 || index > MAX_THREAD_COUNT ? false : true) #define is_thread_active(index) (is_valid_thread_index(index) && scripts[index].is_active ? true : false) class xvm : public xvm_interface { public: xvm(); ~xvm(); //------------script interface---------------// void xvm_init(); void xvm_shutdown(); int xvm_load_script(const char* script_name, int& script_index, int thread_timeslice); void xvm_unload_script(int script_index); void xvm_reset_script(int script_index); void xvm_run_script(int timeslice_duration); void xvm_start_script(int script_index); void xvm_stop_script(int script_index); void xvm_pause_script(int script_index, int duration); void xvm_unpause_script(int script_index); void xvm_pass_int_param(int script_index, int v); void xvm_pass_float_param(int script_index, float v); void xvm_pass_string_param(int script_index, const char* str); int xvm_get_return_as_int(int script_index); float xvm_get_return_as_float(int script_index); string xvm_get_return_as_string(int script_index); void xvm_call_script_function(int script_index, const char* fname); void xvm_invoke_script_function(int script_index, const char* fname); //------------host API interface---------------// void xvm_register_host_api(int script_index, const char* fname, host_api_function_ptr fn); int xvm_get_param_as_int(int script_index, int param_index); float xvm_get_param_as_float(int script_index, int param_index); string xvm_get_param_as_string(int script_index, int param_index); void xvm_return_from_host(int script_index, int param_count); void xvm_return_int_from_host(int script_index, int param_count, int v); void xvm_return_float_from_host(int script_index, int param_count, float v); void xvm_return_string_from_host(int script_index, int param_count, char* str); private: //------------operand interface----------------// int cast_value_to_int(const xvm_value& v); float cast_value_to_float(const xvm_value& v); string cast_value_to_string(const xvm_value& v); void copy_value(xvm_value* dest, const xvm_value& source); int get_operand_type(int index); int resolve_operand_stack_index(int index); xvm_value resolve_operand_value(int index); int resolve_operand_type(int index); int resolve_operand_as_int(int index); float resolve_operand_as_float(int index); string resolve_operand_as_string(int index); int resolve_operand_as_instruction_index(int index); int resolve_operand_as_function_index(int index); string resolve_operand_as_host_api(int index); xvm_value* resolve_operand_ptr(int index); //------------runtime stack interface-------------// xvm_value get_stack_value(int script_index, int index); void set_stack_value(int script_index, int index, const xvm_value& v); void push(int script_index, const xvm_value& v); xvm_value pop(int script_index); void push_frame(int script_index, int size); void pop_frame(int size); //------------function table interface------------// int get_function_index_by_name(int script_index, const char* str); function get_function(int script_index, int index); //------------host API interface-----------------// string get_host_api(int index); //------------time-------------------------------// int get_current_time(); //------------function---------------------------// void call_function(int script_index, int index); //------------string table-----------------------// int add_string_if_new(const string& str); string get_string(int sindex); private: script scripts[MAX_THREAD_COUNT]; host_api_function host_apis[MAX_HOST_API_SIZE]; //threading int current_thread; int current_thread_mode; int current_thread_active_time; }; }//namespace xvm }//namespace xscript #endif //__XSCRIPT_XVM_HPP__
28.952
106
0.668002
kiven-li
a01de795ae2657ed39ae4096188e7469caf791cd
9,362
hpp
C++
kernel/src/dispatch_syscall_callback_op.hpp
kangdazhi/hypervisor
95848672b1b2907f37f91343ae139d1bbd858b9d
[ "MIT" ]
null
null
null
kernel/src/dispatch_syscall_callback_op.hpp
kangdazhi/hypervisor
95848672b1b2907f37f91343ae139d1bbd858b9d
[ "MIT" ]
null
null
null
kernel/src/dispatch_syscall_callback_op.hpp
kangdazhi/hypervisor
95848672b1b2907f37f91343ae139d1bbd858b9d
[ "MIT" ]
null
null
null
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #ifndef DISPATCH_SYSCALL_CALLBACK_OP_HPP #define DISPATCH_SYSCALL_CALLBACK_OP_HPP #include <bf_constants.hpp> #include <ext_t.hpp> #include <tls_t.hpp> #include <bsl/convert.hpp> #include <bsl/debug.hpp> #include <bsl/likely.hpp> #include <bsl/safe_integral.hpp> #include <bsl/touch.hpp> #include <bsl/unlikely.hpp> namespace mk { /// <!-- description --> /// @brief Implements the bf_callback_op_register_bootstrap syscall /// /// <!-- inputs/outputs --> /// @param mut_tls the current TLS block /// @param mut_ext the extension that made the syscall /// @return Returns a bf_status_t containing success or failure /// [[nodiscard]] constexpr auto syscall_callback_op_register_bootstrap(tls_t &mut_tls, ext_t &mut_ext) noexcept -> syscall::bf_status_t { bsl::safe_uintmax const callback{mut_tls.ext_reg1}; if (bsl::unlikely(callback.is_zero())) { bsl::error() << "the bootstrap callback cannot be null" // -- << bsl::endl // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } if (bsl::unlikely(mut_ext.bootstrap_ip())) { bsl::error() << "mut_ext " // -- << bsl::hex(mut_ext.id()) // -- << " already registered a bootstrap callback\n" // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } mut_ext.set_bootstrap_ip(callback); return syscall::BF_STATUS_SUCCESS; } /// <!-- description --> /// @brief Implements the bf_callback_op_register_vmexit syscall /// /// <!-- inputs/outputs --> /// @param mut_tls the current TLS block /// @param mut_ext the extension that made the syscall /// @return Returns a bf_status_t containing success or failure /// [[nodiscard]] constexpr auto syscall_callback_op_register_vmexit(tls_t &mut_tls, ext_t &mut_ext) noexcept -> syscall::bf_status_t { bsl::safe_uintmax const callback{mut_tls.ext_reg1}; if (bsl::unlikely(callback.is_zero())) { bsl::error() << "the vmexit callback cannot be null" // -- << bsl::endl // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } if (bsl::unlikely(mut_ext.vmexit_ip())) { bsl::error() << "mut_ext " // -- << bsl::hex(mut_ext.id()) // -- << " already registered a vmexit callback\n" // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } if (bsl::unlikely(nullptr != mut_tls.ext_vmexit)) { bsl::error() << "mut_ext " // -- << bsl::hex(static_cast<ext_t *>(mut_tls.ext_vmexit)->id()) // -- << " already registered a vmexit callback\n" // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } mut_ext.set_vmexit_ip(callback); mut_tls.ext_vmexit = &mut_ext; return syscall::BF_STATUS_SUCCESS; } /// <!-- description --> /// @brief Implements the bf_callback_op_register_fail syscall /// /// <!-- inputs/outputs --> /// @param mut_tls the current TLS block /// @param mut_ext the extension that made the syscall /// @return Returns a bf_status_t containing success or failure /// [[nodiscard]] constexpr auto syscall_callback_op_register_fail(tls_t &mut_tls, ext_t &mut_ext) noexcept -> syscall::bf_status_t { bsl::safe_uintmax const callback{mut_tls.ext_reg1}; if (bsl::unlikely(callback.is_zero())) { bsl::error() << "the fast fail callback cannot be null" // -- << bsl::endl // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } if (bsl::unlikely(mut_ext.fail_ip())) { bsl::error() << "mut_ext " // -- << bsl::hex(mut_ext.id()) // -- << " already registered a fast fail callback\n" // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } if (bsl::unlikely(nullptr != mut_tls.ext_fail)) { bsl::error() << "mut_ext " // -- << bsl::hex(static_cast<ext_t *>(mut_tls.ext_fail)->id()) // -- << " already registered a fast fail callback\n" // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_UNKNOWN; } mut_ext.set_fail_ip(callback); mut_tls.ext_fail = &mut_ext; return syscall::BF_STATUS_SUCCESS; } /// <!-- description --> /// @brief Dispatches the bf_callback_op syscalls /// /// <!-- inputs/outputs --> /// @param mut_tls the current TLS block /// @param mut_ext the extension that made the syscall /// @return Returns a bf_status_t containing success or failure /// [[nodiscard]] constexpr auto dispatch_syscall_callback_op(tls_t &mut_tls, ext_t &mut_ext) noexcept -> syscall::bf_status_t { if (bsl::unlikely(!mut_ext.is_handle_valid(bsl::to_umax(mut_tls.ext_reg0)))) { bsl::error() << "invalid handle " // -- << bsl::hex(mut_tls.ext_reg0) // -- << bsl::endl // -- << bsl::here(); // -- return syscall::BF_STATUS_FAILURE_INVALID_HANDLE; } switch (syscall::bf_syscall_index(bsl::to_umax(mut_tls.ext_syscall)).get()) { case syscall::BF_CALLBACK_OP_REGISTER_BOOTSTRAP_IDX_VAL.get(): { auto const ret{syscall_callback_op_register_bootstrap(mut_tls, mut_ext)}; if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) { bsl::print<bsl::V>() << bsl::here(); return ret; } return ret; } case syscall::BF_CALLBACK_OP_REGISTER_VMEXIT_IDX_VAL.get(): { auto const ret{syscall_callback_op_register_vmexit(mut_tls, mut_ext)}; if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) { bsl::print<bsl::V>() << bsl::here(); return ret; } return ret; } case syscall::BF_CALLBACK_OP_REGISTER_FAIL_IDX_VAL.get(): { auto const ret{syscall_callback_op_register_fail(mut_tls, mut_ext)}; if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) { bsl::print<bsl::V>() << bsl::here(); return ret; } return ret; } default: { break; } } bsl::error() << "unknown syscall " //-- << bsl::hex(mut_tls.ext_syscall) //-- << bsl::endl //-- << bsl::here(); //-- return syscall::BF_STATUS_FAILURE_UNSUPPORTED; } } #endif
40.528139
97
0.508118
kangdazhi
a022ac19edb278e205ce512be3d327b5683c5499
3,060
cpp
C++
examples/mongocxx/document_validation.cpp
CURG-old/mongo-cxx-driver
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
[ "Apache-2.0" ]
null
null
null
examples/mongocxx/document_validation.cpp
CURG-old/mongo-cxx-driver
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
[ "Apache-2.0" ]
null
null
null
examples/mongocxx/document_validation.cpp
CURG-old/mongo-cxx-driver
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
[ "Apache-2.0" ]
1
2021-06-18T05:00:10.000Z
2021-06-18T05:00:10.000Z
// Copyright 2016 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/stdx/string_view.hpp> #include <mongocxx/client.hpp> #include <mongocxx/exception/exception.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/uri.hpp> using bsoncxx::builder::stream::document; using bsoncxx::builder::stream::open_document; using bsoncxx::builder::stream::close_document; using mongocxx::stdx::string_view; using mongocxx::collection; using mongocxx::validation_criteria; int main(int, char**) { mongocxx::instance inst{}; mongocxx::client conn{mongocxx::uri{}}; auto db = conn["test"]; // Create a collection with document validation enabled. { // @begin: cpp-create-collection-with-document-validation validation_criteria validation; validation.level(validation_criteria::validation_level::k_strict); validation.action(validation_criteria::validation_action::k_error); // Add a validation rule: all zombies need to eat some brains. document rule; rule << "brains" << open_document << "$gt" << 0 << close_document; validation.rule(rule.extract()); mongocxx::options::create_collection opts; opts.validation_criteria(validation); // Clean up any old collections with this name if (db.has_collection("zombies")) { db["zombies"].drop(); } collection zombies = db.create_collection("zombies", opts); try { // Insert a document passing validation document betty; betty << "name" << "Bloody Betty" << "brains" << 3; auto res = zombies.insert_one(betty.extract()); std::cout << "Bloody Betty passed document validation!" << std::endl; // Insert a document failing validation document fred; fred << "name" << "Undead Fred" << "brains" << 0; // Inserting a failing document should throw auto res2 = zombies.insert_one(fred.extract()); std::cout << "ERROR: server does not support document validation." << std::endl; } catch (const mongocxx::exception& e) { std::cout << "Some zombie needs to eat more brains:" << std::endl; std::cout << e.what() << std::endl; } // @end: cpp-create-collection-with-document-validation } }
34
92
0.643137
CURG-old
a0248e1851cfb8395910016eba296900989e99b4
1,917
cpp
C++
17. Game_Routes.cpp
Anksus/CSES-Graph-solutions
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
[ "MIT" ]
null
null
null
17. Game_Routes.cpp
Anksus/CSES-Graph-solutions
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
[ "MIT" ]
null
null
null
17. Game_Routes.cpp
Anksus/CSES-Graph-solutions
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
[ "MIT" ]
null
null
null
// While recurring to the destination node, we set all the nodes to 0. // but the last one to 1 and getting this values pass to all the routes back, // so that they can be collected back at 1st node. // act[mxN] is for detecting cycle, just a bellman ford stuff. // There are 2 approach to solve this problem (according to my knowledge). // 1. Traditional BFS (gives TLE for large N) // 2. DP + DFS (works like a charm) #include <bits/stdc++.h> using namespace std; #define pii pair<int,int> #define int64 int64_t #define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define ll long long #define pb push_back #define str string #define ri(x) int x;cin>>x; #define rl(x) ll x; cin>>x; #define rs(x) str x; cin>>x; #define rd(x) d x; cin>>x; #define w(x) cout<<x; #define vec(x) std::vector<x> #define nl '\n' #define all(x) x.begin(),x.end() #define map_traverse(it,x) for(auto it = BN(x); it!= ED(x); it++) #define debug(x) for(auto y : x) {cout<<y<<" ";} cout<<nl; #define PI 3.14159265358979323846264338327950L #define rep(i,a,b) for(int i=a;i<b;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define vi vector<int> const unsigned int M = 1000000007; int n,m,k,q; const int mxN=2e5; const int N = 100031; bool bad = false; std::vector<int>a[N],par(mxN,0),vis(mxN,0); int dp[mxN]; vi adj[mxN]; int act[mxN]; vector<pii> g[mxN]; void dfs(int u){ dp[u] = u==n?1:0; vis[u]=1; act[u]=1; for(auto x: adj[u]){ if(act[x]){ cout<<"IMPOSSIBLE"; exit(0); }else if(!vis[x]){ par[x]=u; dfs(x); } dp[u] = (dp[x]+dp[u])%M; } act[u]=0; } void solve(){ cin>>n>>m; rep(i,0,m){ int a,b; cin>>a>>b; adj[a].pb(b); } par[1]=-1; rep(i,1,n+1){ if(!vis[i]){ dfs(i); } } cout<<dp[1]; } int main(){ IOS; solve(); }
23.378049
77
0.573292
Anksus
a02565115fb30ef33bab0959829b930788072e17
2,730
hxx
C++
com/oleutest/balls/common/cballs.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/oleutest/balls/common/cballs.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/oleutest/balls/common/cballs.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1992. // // File: cballs.hxx // // Contents: Class to encapsulate demo of distributed binding interface // // Classes: CBall // // History: 06-Aug-92 Ricksa Created // //-------------------------------------------------------------------------- #ifndef __BALLS__ #define __BALLS__ #include <sem.hxx> #include <otrack.hxx> #include <iballs.h> #include <ballscf.hxx> #define BALL_UNDEF 0xFFFFFFFF #define BALL_DIAMETER 10 //+------------------------------------------------------------------------- // // Class: CBall // // Purpose: Class to demostrate remote binding functionality // // Interface: QueryInterface // AddRef // Release // CreateBall - create a ball // MoveBall - move a ball // GetBallPos - get the ball position (x,y) // IsOverLapped - see if other ball is overlapped with this ball // IsContainedIn - see if ball is inside given cube // Clone - make a new ball at the same position as this // Echo - returns the same interface passed in // // History: 06-Aug-92 Ricksa Created // //-------------------------------------------------------------------------- class CBall : public IBalls { public: CBall(IUnknown *punkOuter); ~CBall(void); STDMETHOD(QueryInterface)(REFIID riid, void **ppunk); STDMETHOD_(ULONG, AddRef)(void); STDMETHOD_(ULONG, Release)(void); STDMETHOD(QueryInternalIface)(REFIID riid, void **ppunk); STDMETHOD(CreateBall)(ULONG xPos, ULONG yPos); STDMETHOD(MoveBall)(ULONG xPos, ULONG yPos); STDMETHOD(GetBallPos)(ULONG *xPos, ULONG *yPos); STDMETHOD(IsOverLapped)(IBalls *pIBall); STDMETHOD(IsContainedIn)(ICube *pICube); STDMETHOD(Clone)(IBalls **ppIBall); STDMETHOD(Echo)(IUnknown *punkIn, IUnknown **ppunkOut); private: ULONG _xPos; ULONG _yPos; IUnknown * _punkOuter; }; //+------------------------------------------------------------------------- // // Class: CBallCtrlUnk // // Purpose: Class to demostrate remote binding functionality // // Interface: QueryInterface // AddRef // Release // // History: 06-Aug-92 Ricksa Created // //-------------------------------------------------------------------------- class CBallCtrlUnk : INHERIT_TRACKING, public IUnknown { public: CBallCtrlUnk(IUnknown *punkOuter); STDMETHOD(QueryInterface)(REFIID riid, void **ppunk); DECLARE_STD_REFCOUNTING; private: ~CBallCtrlUnk(void); CBall _ball; }; #endif // __BALLS__
25.277778
77
0.538095
npocmaka
a028105f6e3e6e5d7a78a3bd808b5bc8619bff86
1,249
inl
C++
ZEngine/include/zengine/Debug/Assert.inl
AarnoldGad/ZucchiniEngine
cb27d2a534a3f21ec59eaa116f052a169a811c06
[ "Zlib" ]
1
2020-12-04T17:56:22.000Z
2020-12-04T17:56:22.000Z
ZEngine/include/zengine/Debug/Assert.inl
AarnoldGad/ZEngine
cb27d2a534a3f21ec59eaa116f052a169a811c06
[ "Zlib" ]
1
2022-02-02T23:24:34.000Z
2022-02-02T23:24:34.000Z
ZEngine/include/zengine/Debug/Assert.inl
AarnoldGad/ZucchiniEngine
cb27d2a534a3f21ec59eaa116f052a169a811c06
[ "Zlib" ]
null
null
null
#include <zengine/Memory/New.hpp> // Inspired by https://www.foonathan.net/2016/09/assertions/ [[noreturn]] inline void ze::AssertHandler::handle(SourceLocation const& location, char const* expression, char const* message) noexcept { LOG_TRACE(location.file, "::", location.function, " (", location.line, ") : Assertion failed \"", expression, "\"", (message ? " : " : ""), (message ? message : "")); std::abort(); } template<typename EvaluatorFn, typename HandlerType, typename... Args, std::enable_if_t<HandlerType::enabled, int> > inline void ze::Assert(EvaluatorFn const& evaluator, SourceLocation const& location, char const* expression, HandlerType handler, Args&&... args) noexcept { if (!evaluator()) { handler.handle(location, expression, std::forward<Args>(args)...); std::abort(); } } template<typename EvaluatorFn, typename HandlerType, typename... Args, std::enable_if_t<!HandlerType::enabled, int> > inline void ze::Assert([[maybe_unused]] EvaluatorFn const& evaluator, [[maybe_unused]] SourceLocation const& location, [[maybe_unused]] char const* expression, [[maybe_unused]] HandlerType handler, [[maybe_unused]] Args&&... args) noexcept {} #include <zengine/Memory/NewOff.hpp>
46.259259
169
0.698959
AarnoldGad
a02f68e17ca378ce63bfbdc9931fb683cd610aa4
1,950
cpp
C++
engine/source/wide/ui/property/basic/ui_property_image.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/wide/ui/property/basic/ui_property_image.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/wide/ui/property/basic/ui_property_image.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------// /// @file wide/ui/property/basic/ui_property_image.cpp //------------------------------------------------------------------------------------------------// //-INCLUDES---------------------------------------------------------------------------------------// #include "wide/ui/property/basic/ui_property_image.h" #include "wide/ui/window/ui_window_manager.h" //------------------------------------------------------------------------------------------------// namespace coffee { //-META---------------------------------------------------------------------------------------// COFFEE_BeginType(ui::PropertyImage); COFFEE_Ancestor(ui::Property); COFFEE_EndType(); namespace ui { //-CONSTRUCTORS-------------------------------------------------------------------------------// PropertyImage::PropertyImage() : _Image(NULL) { } //--------------------------------------------------------------------------------------------// PropertyImage::~PropertyImage() { } //-OPERATIONS---------------------------------------------------------------------------------// void PropertyImage::CreateContent() { basic::Image* image = (basic::Image*)GetData(); GetLayout().SetStyle(LAYOUT_STYLE_VerticalCanvas | LAYOUT_STYLE_StickChildren | LAYOUT_STYLE_HorizontalExpand | LAYOUT_STYLE_VerticalShrink); _Image = COFFEE_New(widget::Image); _Image->Create(this, basic::Vector2i(), basic::Vector2i(), widget::IMAGE_STYLE_AutoSize | widget::IMAGE_STYLE_DrawFrame); _Image->GetLayout().SetStyle(LAYOUT_STYLE_HorizontalCanvas | LAYOUT_STYLE_HorizontalExpand); _Image->SetImage(*image); } } } //------------------------------------------------------------------------------------------------//
36.111111
100
0.372308
skarab
a036b667983dbdbeaca972ec404cf0132a4ea5a3
3,348
cpp
C++
game/source/Behaviour/SplashProjectile.cpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
3
2015-04-25T22:57:58.000Z
2019-11-05T18:36:31.000Z
game/source/Behaviour/SplashProjectile.cpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
1
2016-06-23T15:22:41.000Z
2016-06-23T15:22:41.000Z
game/source/Behaviour/SplashProjectile.cpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
null
null
null
#include "Behaviour/SplashProjectile.hpp" #include <Engine/Audio.hpp> #include <Engine/Event/CreateGameObjectEvent.hpp> #include <Engine/Event/DestroyGameObjectEvent.hpp> #include "ExplosionFactory.hpp" #include "Attribute/Tags.hpp" #include "Event/InflictDamageEvent.hpp" namespace Behaviour { SplashProjectile::SplashProjectile(std::shared_ptr<Engine::Window> window, std::shared_ptr<Engine::ResourceManager> resourceManager, std::shared_ptr<Engine::EventDispatcher> sceneEventDispatcher, std::shared_ptr<Engine::EventDispatcher> gameObjectEventDispatcher, std::weak_ptr<Engine::GameObject> gameObject, std::shared_ptr<Engine::Attribute::Transform> transformAttribute, const PlayingSurface& playingSurface, std::string tag, float damage) : IBehaviour(window, resourceManager, sceneEventDispatcher, gameObjectEventDispatcher, gameObject) , m_transformAttribute(transformAttribute) , m_playingSurface(playingSurface) , m_tag(tag) , m_damage(damage) , m_explosionFactory(std::make_shared<ExplosionFactory>()) , m_inRange() , m_collisionSubscription(0) { // Subscribe to receive CollisionEvents. m_collisionSubscription = GetGameObjectEventDispatcher()->Subscribe<Engine::Event::CollisionEvent>( [this](const Engine::Event::CollisionEvent& event) { std::shared_ptr<Engine::GameObject> otherGameObject = event.GetOtherGameObject(); if (!otherGameObject->IsDead() && otherGameObject->HasAttribute<Attribute::Tags>()) { std::shared_ptr<Attribute::Tags> tagsAttribute = otherGameObject->GetAttribute<Attribute::Tags>(); if (tagsAttribute->HasTag(m_tag)) { m_inRange.push_back(otherGameObject); } } } ); } SplashProjectile::~SplashProjectile() { // Unsubscribe for CollisionEvents. GetGameObjectEventDispatcher()->Unsubscribe<Engine::Event::CollisionEvent>(m_collisionSubscription); } void SplashProjectile::Update(double deltaTime) { const glm::vec3 position = m_transformAttribute->GetPosition(); const glm::vec2 playingSurfaceHalfDimensions = m_playingSurface.GetDimensions() * 0.5f; // TODO: Add check for elevation above ground. if (position.x < - playingSurfaceHalfDimensions.x || position.x > playingSurfaceHalfDimensions.x || position.z < - playingSurfaceHalfDimensions.y || position.z > playingSurfaceHalfDimensions.y || position.y < 0.0f) { // If the projectile has hit the ground, then inflict damage on // the Game Objects within range. if (position.y < 0.0f) { for (std::shared_ptr<Engine::GameObject> gameObject : m_inRange) { gameObject->BroadcastEnqueue<Event::InflictDamageEvent>(m_damage); } // Play a large explosion sound. Engine::Audio::GetInstance().Play(GetResourceManager()->GetAudio("resources/audio/MissileExplosion.wav")); } GetSceneEventDispatcher()->Enqueue<Engine::Event::CreateGameObjectEvent>( m_explosionFactory, [this](std::shared_ptr<Engine::GameObject> explosion) { std::shared_ptr<Engine::Attribute::Transform> transform = explosion->GetAttribute<Engine::Attribute::Transform>(); transform->SetPosition(m_transformAttribute->GetPosition()); } ); GetGameObjectEventDispatcher()->Enqueue<Engine::Event::DestroyGameObjectEvent>(); } // Clear the list of Game Objects in range. m_inRange.clear(); } }
33.818182
110
0.744325
kermado
a03d8ed258004936ac8f44675099ff97e78181fb
5,341
cpp
C++
modules/juce_audio_devices/native/juce_emscripten_Midi.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
80
2019-12-31T15:16:19.000Z
2022-02-17T22:52:25.000Z
modules/juce_audio_devices/native/juce_emscripten_Midi.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
1
2020-07-17T04:26:19.000Z
2020-07-17T06:56:19.000Z
modules/juce_audio_devices/native/juce_emscripten_Midi.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
9
2019-12-26T12:18:29.000Z
2021-12-27T18:51:38.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #if ! defined(JUCE_WEBMIDI) #define JUCE_WEBMIDI 1 #endif #if JUCE_WEBMIDI #define __WEB_MIDI_API__ 1 #endif #include "emscripten/RtMidi.cpp" #undef __WEB_MIDI_API__ namespace juce { struct JuceRtMidiContext { RtMidiIn* rtmidi; MidiInput* midiIn; MidiInputCallback* callback{nullptr}; }; //============================================================================== MidiInput::MidiInput (const String& deviceName, const String& deviceID) : deviceInfo (deviceName, deviceID) { auto ctx = new JuceRtMidiContext(); ctx->rtmidi = new RtMidiIn(); ctx->midiIn = this; internal = ctx; } MidiInput::~MidiInput() { delete (RtMidiIn*) internal; } void MidiInput::start() { } void MidiInput::stop() { } Array<MidiDeviceInfo> MidiInput::getAvailableDevices() { Array<MidiDeviceInfo> ret{}; RtMidiIn rtmidi{}; for (int i = 0; i < rtmidi.getPortCount(); i++) ret.add(MidiDeviceInfo(rtmidi.getPortName(i), String::formatted("MidiIn_%d", i))); return ret; } MidiDeviceInfo MidiInput::getDefaultDevice() { return getAvailableDevices()[getDefaultDeviceIndex()]; } void rtmidiCallback(double timeStamp, std::vector<unsigned char> *message, void *userData) { auto ctx = (JuceRtMidiContext*) userData; auto callback = ctx->callback; auto midiIn = ctx->midiIn; const void* data = message->data(); int numBytes = message->size(); // JUCE does not accept zero timestamp value, but RtMidi is supposed to send 0 for the first // message. To resolve that conflict, we offset 0.0 to slightly positive time. MidiMessage midiMessage{data, numBytes, timeStamp > 0.0 ? timeStamp : 0.00000001}; callback->handleIncomingMidiMessage(midiIn, midiMessage); } std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback) { RtMidiIn rtmidiStatic{}; std::unique_ptr<MidiInput> ret{nullptr}; for (int i = 0; i < rtmidiStatic.getPortCount(); i++) if (String::formatted("MidiIn_%d", i) == deviceIdentifier) { ret.reset(new MidiInput(rtmidiStatic.getPortName(i), deviceIdentifier)); auto ctx = (JuceRtMidiContext*) ret->internal; ctx->callback = callback; auto rtmidi = ctx->rtmidi; rtmidi->setCallback(rtmidiCallback, ctx); rtmidi->openPort(i); return std::move(ret); } jassertfalse; return nullptr; } StringArray MidiInput::getDevices() { StringArray ret{}; for (auto dev : getAvailableDevices()) ret.add(dev.name); return {}; } int MidiInput::getDefaultDeviceIndex() { return 0; } std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback) { return openDevice(getAvailableDevices()[index].identifier, callback); } //============================================================================== MidiOutput::~MidiOutput() { delete (RtMidiOut*) internal; } void MidiOutput::sendMessageNow (const MidiMessage& message) { ((RtMidiOut *) internal)->sendMessage(message.getRawData(), message.getRawDataSize()); } Array<MidiDeviceInfo> MidiOutput::getAvailableDevices() { Array<MidiDeviceInfo> ret{}; RtMidiOut rtmidi{}; for (int i = 0; i < rtmidi.getPortCount(); i++) ret.add(MidiDeviceInfo(rtmidi.getPortName(i), String::formatted("MidiOut_%d", i))); return ret; } MidiDeviceInfo MidiOutput::getDefaultDevice() { return getAvailableDevices()[getDefaultDeviceIndex()]; } std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier) { RtMidiOut rtmidi{}; std::unique_ptr<MidiOutput> ret{nullptr}; for (int i = 0; i < rtmidi.getPortCount(); i++) { if (String::formatted("MidiOut_%d", i) == deviceIdentifier) { auto midiOut = new MidiOutput(rtmidi.getPortName(i), deviceIdentifier); ret.reset(midiOut); midiOut->internal = new RtMidiOut(); ((RtMidiOut *) ret->internal)->openPort(i); return std::move(ret); } } jassertfalse; return nullptr; } StringArray MidiOutput::getDevices() { StringArray ret{}; for (auto dev : getAvailableDevices()) ret.add(dev.name); return {}; } int MidiOutput::getDefaultDeviceIndex() { return 0; } std::unique_ptr<MidiOutput> MidiOutput::openDevice (int index) { return openDevice(getAvailableDevices()[index].identifier); } } // namespace juce
31.052326
112
0.646134
genkiinstruments
a03f729b1293946b3523fc84442e7876160610fa
7,024
cxx
C++
main/extensions/source/bibliography/bibview.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/extensions/source/bibliography/bibview.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/extensions/source/bibliography/bibview.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_extensions.hxx" #ifndef BIB_HRC #include "bib.hrc" #endif #include "bibcont.hxx" #include "bibbeam.hxx" #include "bibmod.hxx" #include "general.hxx" #include "bibview.hxx" #include "datman.hxx" #include "bibresid.hxx" #include "bibmod.hxx" #include "sections.hrc" #include "bibconfig.hxx" #include <vcl/svapp.hxx> #include <com/sun/star/sdbc/XResultSetUpdate.hpp> #include <com/sun/star/form/XLoadable.hpp> #include <vcl/msgbox.hxx> #include <tools/debug.hxx> using namespace ::com::sun::star; using namespace ::com::sun::star::form; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; #define C2U( cChar ) ::rtl::OUString::createFromAscii( cChar ) //......................................................................... namespace bib { //......................................................................... // ----------------------------------------------------------------------- BibView::BibView( Window* _pParent, BibDataManager* _pManager, WinBits _nStyle ) :BibWindow( _pParent, _nStyle ) ,m_pDatMan( _pManager ) ,m_xDatMan( _pManager ) ,m_pGeneralPage( NULL ) { if ( m_xDatMan.is() ) connectForm( m_xDatMan ); } // ----------------------------------------------------------------------- BibView::~BibView() { BibGeneralPage* pGeneralPage = m_pGeneralPage; m_pGeneralPage = NULL; pGeneralPage->CommitActiveControl(); Reference< XForm > xForm = m_pDatMan->getForm(); Reference< XPropertySet > xProps( xForm, UNO_QUERY ); Reference< sdbc::XResultSetUpdate > xResUpd( xProps, UNO_QUERY ); DBG_ASSERT( xResUpd.is(), "BibView::~BibView: invalid form!" ); if ( xResUpd.is() ) { Any aModified = xProps->getPropertyValue( C2U( "IsModified" ) ); sal_Bool bFlag = sal_False; if ( ( aModified >>= bFlag ) && bFlag ) { try { Any aNew = xProps->getPropertyValue( C2U( "IsNew" ) ); aNew >>= bFlag; if ( bFlag ) xResUpd->insertRow(); else xResUpd->updateRow(); } catch( const uno::Exception& rEx) { (void) rEx; } } } if ( isFormConnected() ) disconnectForm(); pGeneralPage->RemoveListeners(); m_xGeneralPage = NULL; } /* -----------------16.11.99 13:13------------------- --------------------------------------------------*/ void BibView::UpdatePages() { // TODO: // this is _strange_: Why not updating the existent general page? // I consider the current behaviour a HACK. // frank.schoenheit@sun.com if ( m_pGeneralPage ) { m_pGeneralPage->Hide(); m_pGeneralPage->RemoveListeners(); m_xGeneralPage = 0; } m_xGeneralPage = m_pGeneralPage = new BibGeneralPage( this, m_pDatMan ); Resize(); if( HasFocus() ) // "delayed" GetFocus() because GetFocus() is initially called before GeneralPage is created m_pGeneralPage->GrabFocus(); String sErrorString( m_pGeneralPage->GetErrorString() ); if ( sErrorString.Len() ) { sal_Bool bExecute = BibModul::GetConfig()->IsShowColumnAssignmentWarning(); if(!m_pDatMan->HasActiveConnection()) { //no connection is available -> the data base has to be assigned m_pDatMan->DispatchDBChangeDialog(); bExecute = sal_False; } else if(bExecute) { sErrorString += '\n'; sErrorString += String( BibResId( RID_MAP_QUESTION ) ); QueryBox aQuery( this, WB_YES_NO, sErrorString ); aQuery.SetDefaultCheckBoxText(); short nResult = aQuery.Execute(); BibModul::GetConfig()->SetShowColumnAssignmentWarning( !aQuery.GetCheckBoxState()); if( RET_YES != nResult ) { bExecute = sal_False; } } if(bExecute) { Application::PostUserEvent( STATIC_LINK( this, BibView, CallMappingHdl ) ); } } } //--------------------------------------------------------------------- //--- 19.10.01 16:55:49 ----------------------------------------------- void BibView::_loaded( const EventObject& _rEvent ) { UpdatePages(); FormControlContainer::_loaded( _rEvent ); } void BibView::_reloaded( const EventObject& _rEvent ) { UpdatePages(); FormControlContainer::_loaded( _rEvent ); } /* -----------------------------02.02.00 16:49-------------------------------- ---------------------------------------------------------------------------*/ IMPL_STATIC_LINK( BibView, CallMappingHdl, BibView*, EMPTYARG ) { pThis->m_pDatMan->CreateMappingDialog( pThis ); return 0; } /* -----------------------------13.04.00 16:12-------------------------------- ---------------------------------------------------------------------------*/ void BibView::Resize() { if ( m_pGeneralPage ) { ::Size aSz( GetOutputSizePixel() ); m_pGeneralPage->SetSizePixel( aSz ); } Window::Resize(); } //--------------------------------------------------------------------- //--- 18.10.01 18:52:45 ----------------------------------------------- Reference< awt::XControlContainer > BibView::getControlContainer() { Reference< awt::XControlContainer > xReturn; if ( m_pGeneralPage ) xReturn = m_pGeneralPage->GetControlContainer(); return xReturn; } void BibView::GetFocus() { if( m_pGeneralPage ) m_pGeneralPage->GrabFocus(); } sal_Bool BibView::HandleShortCutKey( const KeyEvent& rKeyEvent ) { return m_pGeneralPage? m_pGeneralPage->HandleShortCutKey( rKeyEvent ) : sal_False; } //......................................................................... } // namespace bib //.........................................................................
30.672489
95
0.528474
Grosskopf
a0406ccdce644546f2185d212f0c2f34a8cf96ba
354
hpp
C++
src/communication.hpp
linyinfeng/n-body
e40c859689d76a3f36cd08e072d7ee24685e8be4
[ "MIT" ]
1
2021-11-28T15:13:06.000Z
2021-11-28T15:13:06.000Z
src/communication.hpp
linyinfeng/n-body
e40c859689d76a3f36cd08e072d7ee24685e8be4
[ "MIT" ]
null
null
null
src/communication.hpp
linyinfeng/n-body
e40c859689d76a3f36cd08e072d7ee24685e8be4
[ "MIT" ]
1
2019-11-10T14:01:55.000Z
2019-11-10T14:01:55.000Z
#ifndef N_BODY_COMMUNICATION_HPP #define N_BODY_COMMUNICATION_HPP #include <boost/mpi.hpp> #include <cstddef> namespace n_body::communication { struct Division { std::size_t count; std::size_t begin; std::size_t end; explicit Division(const boost::mpi::communicator &comm, std::size_t total); }; } // namespace n_body::communication #endif
17.7
77
0.751412
linyinfeng
a04202528f03e4f290ab1977f6fae7c936e73feb
3,449
cc
C++
src/camera/bin/device/stream_impl_client.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/camera/bin/device/stream_impl_client.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
src/camera/bin/device/stream_impl_client.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/async-loop/default.h> #include <lib/async/cpp/task.h> #include <lib/syslog/cpp/logger.h> #include <sstream> #include "src/camera/bin/device/messages.h" #include "src/camera/bin/device/stream_impl.h" StreamImpl::Client::Client(StreamImpl& stream, uint64_t id, fidl::InterfaceRequest<fuchsia::camera3::Stream> request) : stream_(stream), id_(id), loop_(&kAsyncLoopConfigNoAttachToCurrentThread), binding_(this, std::move(request), loop_.dispatcher()) { FX_LOGS(DEBUG) << "Stream client " << id << " connected."; binding_.set_error_handler(fit::bind_member(this, &StreamImpl::Client::OnClientDisconnected)); std::ostringstream oss; oss << "Camera Stream Thread (Client ID = " << id << ")"; ZX_ASSERT(loop_.StartThread(oss.str().c_str()) == ZX_OK); } StreamImpl::Client::~Client() { loop_.Shutdown(); } void StreamImpl::Client::PostSendFrame(fuchsia::camera3::FrameInfo frame) { ZX_ASSERT(async::PostTask(loop_.dispatcher(), [this, frame = std::move(frame)]() mutable { frame_callback_(std::move(frame)); frame_callback_ = nullptr; }) == ZX_OK); } void StreamImpl::Client::PostReceiveBufferCollection( fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token) { ZX_ASSERT(async::PostTask(loop_.dispatcher(), [this, token = std::move(token)]() mutable { buffers_.Set(std::move(token)); }) == ZX_OK); } bool& StreamImpl::Client::Participant() { return participant_; } void StreamImpl::Client::OnClientDisconnected(zx_status_t status) { FX_PLOGS(DEBUG, status) << "Stream client " << id_ << " disconnected."; stream_.PostRemoveClient(id_); } void StreamImpl::Client::CloseConnection(zx_status_t status) { binding_.Close(status); stream_.PostRemoveClient(id_); } void StreamImpl::Client::SetCropRegion(std::unique_ptr<fuchsia::math::RectF> region) { CloseConnection(ZX_ERR_NOT_SUPPORTED); } void StreamImpl::Client::WatchCropRegion(WatchCropRegionCallback callback) { CloseConnection(ZX_ERR_NOT_SUPPORTED); } void StreamImpl::Client::SetResolution(fuchsia::math::Size coded_size) { CloseConnection(ZX_ERR_NOT_SUPPORTED); } void StreamImpl::Client::WatchResolution(WatchResolutionCallback callback) { CloseConnection(ZX_ERR_NOT_SUPPORTED); } void StreamImpl::Client::SetBufferCollection( fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token) { stream_.PostSetBufferCollection(id_, std::move(token)); } void StreamImpl::Client::WatchBufferCollection(WatchBufferCollectionCallback callback) { if (buffers_.Get(std::move(callback))) { CloseConnection(ZX_ERR_BAD_STATE); } } void StreamImpl::Client::GetNextFrame(GetNextFrameCallback callback) { if (stream_.max_camping_buffers_ == 0) { FX_LOGS(INFO) << Messages::kNoCampingBuffers; } if (frame_callback_) { FX_PLOGS(INFO, ZX_ERR_BAD_STATE) << "Client called GetNextFrame while a previous call was still pending."; CloseConnection(ZX_ERR_BAD_STATE); return; } frame_callback_ = std::move(callback); stream_.PostAddFrameSink(id_); } void StreamImpl::Client::Rebind(fidl::InterfaceRequest<Stream> request) { request.Close(ZX_ERR_NOT_SUPPORTED); CloseConnection(ZX_ERR_NOT_SUPPORTED); }
33.485437
96
0.724848
casey
a04221971486748c6703dd6b1138f6b3e6465e7b
4,217
cpp
C++
src/interpreter.cpp
nirvanasupermind/pocketlisp
2a4b5aca245c547d88f581fefd89cca5473d8a1f
[ "MIT" ]
1
2022-03-18T18:43:04.000Z
2022-03-18T18:43:04.000Z
src/interpreter.cpp
nirvanasupermind/pocketlisp
2a4b5aca245c547d88f581fefd89cca5473d8a1f
[ "MIT" ]
null
null
null
src/interpreter.cpp
nirvanasupermind/pocketlisp
2a4b5aca245c547d88f581fefd89cca5473d8a1f
[ "MIT" ]
null
null
null
#include "./parser.cpp" #include "./scopes.cpp" #include "./utils.cpp" namespace lispy { class Interpreter { public: std::string file; Interpreter(std::string file) { this->file = file; } Value visit(Node node, Scope *scope) { std::cout << node.str() << '\n'; switch (node.type) { case NumberNode: return visit_number_node(node, scope); case SymbolNode: return visit_symbol_node(node, scope); default: return visit_list_node(node, scope); } } Value visit_number_node(Node node, Scope *scope) { return Value(ValueType::Number, node.value); } Value visit_symbol_node(Node node, Scope *scope) { Value *result = scope->get(node.symbol); if(result == NULL) { std::cout << file << ':' << node.ln << ": " << "unbound variable '"+node.symbol+"'" << '\n'; std::exit(EXIT_FAILURE); } return *result; } Value visit_list_node(Node node, Scope *scope) { if(node.nodes.size() == 0) return Value(); std::string tag = node.nodes[0].symbol; // std::cout << node.nodes[1].str() << '\n'; if (tag == "def") { add_variable(node.ln, node.nodes[1], node.nodes[2], scope); } else if (tag == "let") { if (node.nodes[1].type != NodeType::ListNode || node.nodes[2].type != NodeType::ListNode) { std::cout << file << ':' << node.ln << ": " << "bad let expression" << '\n'; std::exit(EXIT_FAILURE); } Scope *child_scope = new Scope(scope); for (int i = 0; i < node.nodes[1].nodes.size(); i++) { if (node.nodes[1].nodes[i].type != NodeType::ListNode) { std::cout << file << ':' << node.ln << ": " << "bad let expression" << '\n'; std::exit(EXIT_FAILURE); } add_variable(node.ln, node.nodes[1].nodes[i].nodes[0], node.nodes[1].nodes[i].nodes[1], child_scope); } for (int i = 0; i < node.nodes[2].nodes.size() - 1; i++) { visit(node.nodes[2].nodes[i], child_scope); } if(node.nodes[2].nodes.size() == 0) return Value(); return visit(node.nodes[2].nodes[node.nodes[2].nodes.size() - 1], child_scope); } else { Value func = visit(node.nodes[0], scope); if (func.type != ValueType::Function) { std::cout << file << ':' << node.ln << ": " << "call of non-function: " << func.str() << '\n'; std::exit(EXIT_FAILURE); } std::vector<Value> args; for (int i = 1; i < node.nodes.size(); i++) { args.push_back(visit(node.nodes[i], scope)); } return func.function(file, node.ln, args); } } // In a seperate utility function as this code is repeated several times throughout the visit_list_node method Value add_variable(int ln, Node name_node, Node val_node, Scope *scope) { if (name_node.type != NodeType::SymbolNode) { std::cout << file << ':' << ln << ": " << "bad variable definition" << '\n'; std::exit(EXIT_FAILURE); } std::string name = name_node.symbol; Value value = visit(val_node, scope); scope->set(name, &value); return value; } }; }
31.007353
121
0.417595
nirvanasupermind
a043887263fac9b983f96da13c7c3292e444f870
257
cpp
C++
3.Stacks and Queues/Queue_STL.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
3.Stacks and Queues/Queue_STL.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
3.Stacks and Queues/Queue_STL.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
#include<iostream> #include<queue> using namespace std; int main() { queue<int> q; for(int i=0; i<5; i++){ q.push(i); } while(!q.empty()){ cout<<q.front()<<" <-"; q.pop(); } return 0; }
12.85
32
0.424125
suraj0803
a049820edb55dcd6be4a699bd20a58ebd84d510e
3,618
cpp
C++
src/C/Security-57031.40.6/SecurityTests/clxutils/dotMacArchive/identSearch.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/SecurityTests/clxutils/dotMacArchive/identSearch.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/SecurityTests/clxutils/dotMacArchive/identSearch.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* * Copyright (c) 2004-2005 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * identSearch.cpp - search for identity whose cert has specified email address */ #include "identSearch.h" #include <Security/SecKeychainItemPriv.h> /* for kSecAlias */ /* * Does the specified identity's cert have the specified email address? Returns * true if so. */ bool idHasEmail( SecIdentityRef idRef, const void *emailAddress, // UTF8 encoded email address unsigned emailAddressLen) { SecCertificateRef certRef; OSStatus ortn; bool ourRtn = false; ortn = SecIdentityCopyCertificate(idRef, &certRef); if(ortn) { /* should never happen */ cssmPerror("SecIdentityCopyCertificate", ortn); return ortn; } /* * Fetch one attribute - the alias (which is always the "best attempt" at * finding an email address within a cert). */ UInt32 oneTag = kSecAlias; SecKeychainAttributeInfo attrInfo; attrInfo.count = 1; attrInfo.tag = &oneTag; attrInfo.format = NULL; SecKeychainAttributeList *attrList = NULL; SecKeychainAttribute *attr = NULL; ortn = SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)certRef, &attrInfo, NULL, // itemClass &attrList, NULL, // length - don't need the data NULL); // outData if(ortn || (attrList == NULL) || (attrList->count != 1)) { /* I don't *think* this should ever happen... */ cssmPerror("SecKeychainItemCopyAttributesAndData", ortn); goto errOut; } attr = attrList->attr; if(attr->length == emailAddressLen) { if(!memcmp(attr->data, emailAddress, emailAddressLen)) { ourRtn = true; } } errOut: SecKeychainItemFreeAttributesAndData(attrList, NULL); CFRelease(certRef); return ourRtn; } /* public function */ OSStatus findIdentity( const void *emailAddress, // UTF8 encoded email address unsigned emailAddressLen, SecKeychainRef kcRef, // keychain to search, or NULL to search all SecIdentityRef *idRef) // RETURNED { OSStatus ortn; /* Search for all identities */ SecIdentitySearchRef srchRef = nil; ortn = SecIdentitySearchCreate(kcRef, 0, // keyUsage - any &srchRef); if(ortn) { /* should never happen */ cssmPerror("SecIdentitySearchCreate", ortn); return ortn; } SecIdentityRef foundId = NULL; do { SecIdentityRef thisId; ortn = SecIdentitySearchCopyNext(srchRef, &thisId); if(ortn != noErr) { break; } /* email addres match? */ if(idHasEmail(thisId, emailAddress, emailAddressLen)) { foundId = thisId; break; } else { /* we're done with thie identity */ CFRelease(thisId); } } while(ortn == noErr); CFRelease(srchRef); if(foundId) { *idRef = foundId; return noErr; } else { return errSecItemNotFound; } }
27.203008
79
0.712272
GaloisInc
a04992790c1b99c1b77e7f32a3d8c02b1009cae9
3,464
cpp
C++
package/win32/android/gameplay/src/Layout.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
1
2021-06-17T02:16:22.000Z
2021-06-17T02:16:22.000Z
package/win32/android/gameplay/src/Layout.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
null
null
null
package/win32/android/gameplay/src/Layout.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
1
2021-06-17T02:16:23.000Z
2021-06-17T02:16:23.000Z
#include "Base.h" #include "Layout.h" #include "Control.h" #include "Container.h" namespace gameplay { void Layout::align(Control* control, const Container* container) { GP_ASSERT(control); GP_ASSERT(container); if (control->_alignment != Control::ALIGN_TOP_LEFT || control->_isAlignmentSet || control->_autoWidth || control->_autoHeight) { Rectangle controlBounds = control->getBounds(); const Theme::Margin& controlMargin = control->getMargin(); const Rectangle& containerBounds = container->getBounds(); const Theme::Border& containerBorder = container->getBorder(container->getState()); const Theme::Padding& containerPadding = container->getPadding(); float clipWidth; float clipHeight; if (container->getScroll() != Container::SCROLL_NONE) { const Rectangle& verticalScrollBarBounds = container->getImageRegion("verticalScrollBar", container->getState()); const Rectangle& horizontalScrollBarBounds = container->getImageRegion("horizontalScrollBar", container->getState()); clipWidth = containerBounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right - verticalScrollBarBounds.width; clipHeight = containerBounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom - horizontalScrollBarBounds.height; } else { clipWidth = containerBounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right; clipHeight = containerBounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom; } if (control->_autoWidth) { controlBounds.width = clipWidth - controlMargin.left - controlMargin.right; } if (control->_autoHeight) { controlBounds.height = clipHeight - controlMargin.top - controlMargin.bottom; } // Vertical alignment if ((control->_alignment & Control::ALIGN_BOTTOM) == Control::ALIGN_BOTTOM) { controlBounds.y = clipHeight - controlBounds.height - controlMargin.bottom; } else if ((control->_alignment & Control::ALIGN_VCENTER) == Control::ALIGN_VCENTER) { controlBounds.y = clipHeight * 0.5f - controlBounds.height * 0.5f; } else if ((control->_alignment & Control::ALIGN_TOP) == Control::ALIGN_TOP) { controlBounds.y = controlMargin.top; } // Horizontal alignment if ((control->_alignment & Control::ALIGN_RIGHT) == Control::ALIGN_RIGHT) { controlBounds.x = clipWidth - controlBounds.width - controlMargin.right; } else if ((control->_alignment & Control::ALIGN_HCENTER) == Control::ALIGN_HCENTER) { controlBounds.x = clipWidth * 0.5f - controlBounds.width * 0.5f; } else if ((control->_alignment & Control::ALIGN_LEFT) == Control::ALIGN_LEFT) { controlBounds.x = controlMargin.left; } control->setBounds(controlBounds); } } bool Layout::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex) { return false; } }
40.27907
180
0.637413
sharkpp
a04c7ab0203bbceaa445fee1a93471cb65575331
1,474
cpp
C++
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace ktl; using namespace TxnReplicator; RuntimeFolders::RuntimeFolders(__in LPCWSTR workDirectory) : KObject() , KShared() , workDirectory_() { NTSTATUS status = KString::Create( workDirectory_, GetThisAllocator(), workDirectory); THROW_ON_FAILURE(status); } RuntimeFolders::~RuntimeFolders() { } IRuntimeFolders::SPtr RuntimeFolders::Create( __in IFabricCodePackageActivationContext & codePackage, __in KAllocator& allocator) { RuntimeFolders * pointer = _new(RUNTIMEFOLDERS_TAG, allocator)RuntimeFolders(codePackage.get_WorkDirectory()); THROW_ON_ALLOCATION_FAILURE(pointer); return IRuntimeFolders::SPtr(pointer); } IRuntimeFolders::SPtr RuntimeFolders::Create( __in IFabricTransactionalReplicatorRuntimeConfigurations & runtimeConfigurations, __in KAllocator& allocator) { RuntimeFolders * pointer = _new(RUNTIMEFOLDERS_TAG, allocator)RuntimeFolders(runtimeConfigurations.get_WorkDirectory()); THROW_ON_ALLOCATION_FAILURE(pointer); return IRuntimeFolders::SPtr(pointer); } LPCWSTR RuntimeFolders::get_WorkDirectory() const { return *workDirectory_; }
28.346154
124
0.694708
vishnuk007
a05100200dbd0ae514766364c276a2c3061690f4
13,826
cpp
C++
src/snmp/session.cpp
Aseman-Land/QtSnmp
4e04214d94324d4ed43d15ea77950b026bfd9b3b
[ "MIT" ]
null
null
null
src/snmp/session.cpp
Aseman-Land/QtSnmp
4e04214d94324d4ed43d15ea77950b026bfd9b3b
[ "MIT" ]
null
null
null
src/snmp/session.cpp
Aseman-Land/QtSnmp
4e04214d94324d4ed43d15ea77950b026bfd9b3b
[ "MIT" ]
null
null
null
#include "session.h" #include "qtsnmpdata.h" #include "requestvaluesjob.h" #include "requestsubvaluesjob.h" #include "setvaluejob.h" #include "defines.h" #include <QDateTime> #include <QHostAddress> #include <math.h> namespace qtsnmpclient { namespace { const int default_response_timeout = 10000; const quint16 SnmpPort = 161; QString errorStatusText( const int val ) { switch( val ) { case 0: return "No errors"; case 1: return "Too big"; case 2: return "No such name"; case 3: return "Bad value"; case 4: return "Read only"; case 5: return "Other errors"; default: Q_ASSERT( false ); break; } return QString( "Unsupported error(%1)" ).arg( val ); } } Session::Session( QObject*const parent ) : QObject( parent ) , m_community( "public" ) , m_socket( new QUdpSocket( this ) ) , m_response_wait_timer( new QTimer( this ) ) { connect( m_socket, SIGNAL(readyRead()), SLOT(onReadyRead()) ); connect( m_response_wait_timer, SIGNAL(timeout()), SLOT(cancelWork()) ); m_response_wait_timer->setInterval( default_response_timeout ); } QHostAddress Session::agentAddress() const { return m_agent_address; } void Session::setAgentAddress( const QHostAddress& value ) { bool ok = !value.isNull(); ok = ok && ( QHostAddress( QHostAddress::Any ) != value ); if( ok ) { m_agent_address = value; m_socket->close(); m_socket->bind(); } else { qWarning() << Q_FUNC_INFO << "attempt to set invalid agent address( " << value << ")"; } } QByteArray Session::community() const { return m_community; } void Session::setCommunity( const QByteArray& value ) { m_community = value; } int Session::responseTimeout() const { return m_response_wait_timer->interval(); } void Session::setResponseTimeout( const int value ) { if( value != m_response_wait_timer->interval() ) { m_response_wait_timer->setInterval( value ); } } bool Session::isBusy() const { return !m_current_work.isNull() || !m_work_queue.isEmpty(); } qint32 Session::requestValues( const QStringList& oid_list ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new RequestValuesJob( this, work_id, oid_list) ) ); return work_id; } qint32 Session::requestSubValues( const QString& oid ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new RequestSubValuesJob( this, work_id, oid ) ) ); return work_id; } qint32 Session::setValue( const QByteArray& community, const QString& oid, const int type, const QByteArray& value ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new SetValueJob( this, work_id, community, oid, type, value ) ) ); return work_id; } void Session::addWork( const JobPointer& work ) { #ifndef Q_CC_MSVC IN_QOBJECT_THREAD( work ); #endif const int queue_limit = 10; if( m_work_queue.count() < queue_limit ) { m_work_queue.push_back( work ); startNextWork(); } else { qWarning() << "Warning: snmp request( " << work->description() << ") " << "to " << m_agent_address.toString() << " dropped, queue if full"; } } void Session::startNextWork() { if( m_current_work.isNull() && !m_work_queue.isEmpty() ){ m_current_work = m_work_queue.takeFirst(); m_current_work->start(); } } void Session::completeWork( const QtSnmpDataList& values ) { Q_ASSERT( ! m_current_work.isNull() ); emit responseReceived( m_current_work->id(), values ); m_current_work.clear(); startNextWork(); } void Session::cancelWork() { if( !m_current_work.isNull() ) { emit requestFailed( m_current_work->id() ); m_current_work.clear(); } m_response_wait_timer->stop(); m_request_id = -1; startNextWork(); } void Session::sendRequestGetValues( const QStringList& names ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); QtSnmpData full_packet = QtSnmpData::sequence(); full_packet.addChild( QtSnmpData::integer( 0 ) ); full_packet.addChild( QtSnmpData::string( m_community ) ); QtSnmpData request( QtSnmpData::GET_REQUEST_TYPE ); request.addChild( QtSnmpData::integer( m_request_id ) ); request.addChild( QtSnmpData::integer( 0 ) ); request.addChild( QtSnmpData::integer( 0 ) ); QtSnmpData seq_all_obj = QtSnmpData::sequence(); for( const auto& oid_key : names ) { QtSnmpData seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( oid_key.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData::null() ); seq_all_obj.addChild( seq_obj_info ); } request.addChild( seq_all_obj ); full_packet.addChild( request ); sendDatagram( full_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "we already wait response"; } } void Session::sendRequestGetNextValue( const QString& name ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); QtSnmpData full_packet = QtSnmpData::sequence(); full_packet.addChild( QtSnmpData::integer( 0 ) ); full_packet.addChild( QtSnmpData::string( m_community ) ); QtSnmpData request( QtSnmpData::GET_NEXT_REQUEST_TYPE ); request.addChild( QtSnmpData::integer( m_request_id ) ); request.addChild( QtSnmpData::integer( 0 ) ); request.addChild( QtSnmpData::integer( 0 ) ); QtSnmpData seq_all_obj = QtSnmpData::sequence(); QtSnmpData seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData::null() ); seq_all_obj.addChild( seq_obj_info ); request.addChild( seq_all_obj ); full_packet.addChild( request ); sendDatagram( full_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "we already wait response"; } } void Session::sendRequestSetValue( const QByteArray& community, const QString& name, const int type, const QByteArray& value ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); auto pdu_packet = QtSnmpData::sequence(); pdu_packet.addChild( QtSnmpData::integer( 0 ) ); pdu_packet.addChild( QtSnmpData::string( community ) ); auto request_type = QtSnmpData( QtSnmpData::SET_REQUEST_TYPE ); request_type.addChild( QtSnmpData::integer( m_request_id ) ); request_type.addChild( QtSnmpData::integer( 0 ) ); request_type.addChild( QtSnmpData::integer( 0 ) ); auto seq_all_obj = QtSnmpData::sequence(); auto seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData( type, value ) ); seq_all_obj.addChild( seq_obj_info ); request_type.addChild( seq_all_obj ); pdu_packet.addChild( request_type ); sendDatagram( pdu_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "we already wait response"; } } void Session::onReadyRead() { const int size = static_cast< int >( m_socket->pendingDatagramSize() ); if( size ) { QByteArray datagram; datagram.resize( size ); m_socket->readDatagram( datagram.data(), size ); const auto& list = getResponseData( datagram ); if( !list.isEmpty() ) { Q_ASSERT( !m_current_work.isNull() ); m_current_work->processData( list ); } } } QtSnmpDataList Session::getResponseData( const QByteArray& datagram ) { QtSnmpDataList result; const auto list = QtSnmpData::parseData( datagram ); Q_ASSERT( !list.isEmpty() ); for( const auto& packet : list ) { const QtSnmpDataList resp_list = packet.children(); if( 3 == resp_list.count() ) { const auto& resp = resp_list.at( 2 ); Q_ASSERT( QtSnmpData::GET_RESPONSE_TYPE == resp.type() ); if( QtSnmpData::GET_RESPONSE_TYPE != resp.type() ) { qWarning() << Q_FUNC_INFO << "Err: unexpected response type"; return result; } const auto& children = resp.children(); Q_ASSERT( 4 == children.count() ); if( 4 != children.count() ) { qWarning() << Q_FUNC_INFO << "Err: unexpected child count"; return result; } const auto& request_id_data = children.at( 0 ); Q_ASSERT( QtSnmpData::INTEGER_TYPE == request_id_data.type() ); if( QtSnmpData::INTEGER_TYPE != request_id_data.type() ) { qWarning() << Q_FUNC_INFO << "Err: request id type"; return result; } const int response_req_id = request_id_data.intValue(); Q_ASSERT( response_req_id == m_request_id ); if( response_req_id == m_request_id ) { m_response_wait_timer->stop(); m_request_id = -1; } else { qWarning() << Q_FUNC_INFO << "Err: unexpected request_id: " << response_req_id << " (expected: " << m_request_id << ")"; return result; } const auto& error_state_data = children.at( 1 ); Q_ASSERT( QtSnmpData::INTEGER_TYPE == error_state_data.type() ); if( QtSnmpData::INTEGER_TYPE != error_state_data.type() ) { qWarning() << Q_FUNC_INFO << "Err: unexpected error state type"; return result; } const auto& error_index_data = children.at( 2 ); Q_ASSERT( QtSnmpData::INTEGER_TYPE == error_index_data.type() ); if( QtSnmpData::INTEGER_TYPE != error_index_data.type() ) { qWarning() << Q_FUNC_INFO << "Err: unexpected error index type"; return result; } const int err_st = error_state_data.intValue(); const int err_in = error_index_data.intValue(); if( err_st || err_in ) { qWarning() << Q_FUNC_INFO << QString( "error [ status: %1; index: %2 ] in answer from %3 for %4" ) .arg( errorStatusText( err_st ) ) .arg( QString::number( err_in ) ) .arg( m_agent_address.toString() ) .arg( m_current_work->description() ); cancelWork(); return result; } const auto& variable_list_data = children.at( 3 ); Q_ASSERT( QtSnmpData::SEQUENCE_TYPE == variable_list_data.type() ); if( QtSnmpData::SEQUENCE_TYPE != variable_list_data.type() ) { qWarning() << Q_FUNC_INFO << "Err: unexpected variable list type"; return result; } const auto& variable_list = variable_list_data.children(); for( int i = variable_list.count() - 1; i >= 0; --i ) { const auto& variable = variable_list.at( i ); if( QtSnmpData::SEQUENCE_TYPE == variable.type() ) { const QtSnmpDataList& items = variable.children(); if( 2 == items.count() ) { const auto& object = items.at( 0 ); if( QtSnmpData::OBJECT_TYPE == object.type() ) { auto result_item = items.at( 1 ); result_item.setAddress( object.data() ); result << result_item; } else { qWarning() << Q_FUNC_INFO << "invalid packet content"; Q_ASSERT( false ); } } else { qWarning() << Q_FUNC_INFO << "invalid packet type"; Q_ASSERT( false ); } } else { qWarning() << Q_FUNC_INFO << "invalid packet type"; Q_ASSERT( false ); } } } else { qWarning() << Q_FUNC_INFO << "parse_get_response error 2"; } } return result; } void Session::sendDatagram( const QByteArray& datagram ) { if( m_socket->writeDatagram( datagram, m_agent_address, SnmpPort ) ) { Q_ASSERT( ! m_response_wait_timer->isActive() ); m_response_wait_timer->start(); } else { Q_ASSERT( false ); cancelWork(); } } qint32 Session::createWorkId() { ++m_work_id; if( m_work_id < 1 ) { m_work_id = 1; } else if( m_work_id > 0x7FFF ) { m_work_id = 1; } return m_work_id; } void Session::updateRequestId() { m_request_id = 1 + abs( rand() ) % 0x7FFF; } } // namespace qtsnmpclient
36.193717
114
0.553595
Aseman-Land
a05224a0765c154870c5f2f17a1fe3122e5c54c9
585
cpp
C++
Cplus/CanMakePalindromefromSubstring.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/CanMakePalindromefromSubstring.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/CanMakePalindromefromSubstring.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <string> #include <vector> using namespace std; class Solution { public: vector<bool> canMakePaliQueries(string s, vector<vector<int>> &queries) { vector<bool> res; int N = s.length(); vector<int> prefixsum(N + 1); for (int i = 0; i < N; ++i) prefixsum[i + 1] = (prefixsum[i] ^ (1 << (s[i] - 'a'))); for (auto &query : queries) { int r = bitCount(prefixsum[query[1] + 1] ^ prefixsum[query[0]]); res.push_back(query[2] >= (r >> 1)); } return res; } int bitCount(int n) { int res = 0; for (; n != 0; n &= n - 1) ++res; return res; } };
18.870968
72
0.567521
JumHorn
a054a212010b793ac03b4ef74271f1b57987dc30
2,663
cpp
C++
Source Code V2/TssTest/RickerSource.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
11
2020-09-27T07:35:22.000Z
2022-03-09T11:01:31.000Z
Source Code V2/TssTest/RickerSource.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
1
2020-10-28T13:14:58.000Z
2020-10-28T21:04:44.000Z
Source Code V2/TssTest/RickerSource.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
7
2020-09-27T07:35:24.000Z
2022-01-02T13:53:21.000Z
/******************************************************************* Author: David Ge (dge893@gmail.com, aka Wei Ge) Last modified: 11/21/2020 Allrights reserved by David Ge field source of Ricker function ********************************************************************/ #include "RickerSource.h" RickerSource::RickerSource() { courant = 1.0 / sqrt(3.0); } RickerSource::~RickerSource() { } #define TP_FS_PPW "FS.PPW" int RickerSource::initialize(TaskFile *configs) { int ret = ERR_OK; ppw = configs->getDouble(TP_FS_PPW, false); ret = configs->getErrorCode(); if (ret == ERR_OK) { if (ppw <= 0.0) { ret = ERR_TASK_INVALID_VALUE; configs->setNameOfInvalidValue(TP_FS_PPW); } } return ret; } int RickerSource::initialize(SimStruct *params) { int ret = FieldSourceTss::initialize(params); i0 = pams->nx / 2; j0 = pams->ny / 2; k0 = pams->nz / 2; w0 = k0 + (pams->nz + 1)*(j0 + (pams->ny + 1)*i0); iN = i0 - pams->smax; iP = i0 + pams->smax; jN = j0 - pams->smax; jP = j0 + pams->smax; kN = k0 - pams->smax; kP = k0 + pams->smax; return ret; } bool RickerSource::isInSource(unsigned int i, unsigned int j, unsigned int k) { return (i >= iN && i <= iP && j >= jN && j <= jP && k >= kN && k <= kP); } int RickerSource::applySources(double t, size_t tIndex, Point3Dstruct *efile, Point3Dstruct *hfile) { int ret = ERR_OK; //H = C.F.dJm + C.G.dJe + ... //E = C.U.dJe + C.W.dJm + ... if (pams->kmax == 0) { //g[0] = 0 //u[0]*Je //apply at center //int i = pams->nx / 2; //int j = pams->ny / 2; //int k = pams->nz / 2; double arg; arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0); arg = arg * arg; arg = (1.0 - 2.0 * arg) * exp(-arg); efile[w0].z += arg; } else //if (pams->kmax == 1) { //int i = pams->nx / 2; //int j = pams->ny / 2; //int k = pams->nz / 2; double arg; arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0); arg = arg * arg; arg = (1.0 - 2.0 * arg) * exp(-arg); efile[w0].z += arg; } return ret; } int RickerSource::applyToZrotateSymmetry(double t, size_t tIndex, RotateSymmetryField *efile, RotateSymmetryField *hfile) { int ret = ERR_OK; //H = C.F.dJm + C.G.dJe + ... //E = C.U.dJe + C.W.dJm + ... // //g[0] = 0 //u[0]*Je //apply at center //int i = pams->nx / 2; //int j = pams->ny / 2; //int k = pams->nz / 2; double arg; arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0); arg = arg * arg; arg = (1.0 - 2.0 * arg) * exp(-arg); //efile[w0].z += arg; (efile->getFieldOnPlane(i0, k0))->z += arg; return ret; }
24.657407
122
0.524972
DavidGeUSA
a0552676f57568454f99572c6c398e69c234c3cb
3,411
cpp
C++
resolvedShotestPathGridDFSBFS.cpp
jkerkela/best-algorithm-collection
6b22536a9f8ebdf3ae134031d41becf30066a5ef
[ "MIT" ]
null
null
null
resolvedShotestPathGridDFSBFS.cpp
jkerkela/best-algorithm-collection
6b22536a9f8ebdf3ae134031d41becf30066a5ef
[ "MIT" ]
null
null
null
resolvedShotestPathGridDFSBFS.cpp
jkerkela/best-algorithm-collection
6b22536a9f8ebdf3ae134031d41becf30066a5ef
[ "MIT" ]
null
null
null
class Solution { public: int nextStepDims[4][2] = { {0,1},{0,-1},{1,0},{-1,0} }; int gridWidth; int gridHeight; int shortestBridge(vector<vector<int>>& A) { return resolveShortestPathJoiningIslandsDFSBFS(A); } int resolveShortestPathJoiningIslandsDFSBFS(vector<vector<int>>& grid) { gridWidth = grid[0].size(); gridHeight = grid.size(); int stepsFromIslandValAdjust = 3; int stepsFromIslandNonClashingWithIslandVals = 0 + stepsFromIslandValAdjust; queue<pair<int,int>> gridPositionToInvstigate; markStartingIslandBFS(grid, gridPositionToInvstigate); vector<vector<bool>> visitedLocations = vector<vector<bool>>(gridHeight, vector<bool>(gridWidth, false)); pair<int,int> inslandStartLoc = gridPositionToInvstigate.front(); floodfillIsland(grid, gridPositionToInvstigate, inslandStartLoc.second, inslandStartLoc.first, visitedLocations, false); while(!gridPositionToInvstigate.empty()) { int currentLevelSize = gridPositionToInvstigate.size(); for(int i = 0; i < currentLevelSize; i++) { pair<int,int> currentLoc = gridPositionToInvstigate.front(); gridPositionToInvstigate.pop(); int yCoord = currentLoc.first; int xCoord = currentLoc.second; for(auto stepToAdjacentLoc : nextStepDims) { int adjacentXCoord = xCoord + stepToAdjacentLoc[0]; int adjacentYCoord = yCoord + stepToAdjacentLoc[1]; if(adjacentXCoord >= 0 && adjacentXCoord < gridWidth && adjacentYCoord >= 0 && adjacentYCoord < gridHeight) { if(grid[adjacentYCoord][adjacentXCoord] == 0) { grid[adjacentYCoord][adjacentXCoord] = stepsFromIslandNonClashingWithIslandVals + 1; gridPositionToInvstigate.push({adjacentYCoord, adjacentXCoord}); } if(grid[adjacentYCoord][adjacentXCoord] == 1) { return stepsFromIslandNonClashingWithIslandVals - stepsFromIslandValAdjust; } } } } stepsFromIslandNonClashingWithIslandVals++; } return 0; } void markStartingIslandBFS(vector<vector<int>>& grid, queue<pair<int,int>>& gridPositionToInvstigate) { for (int i = 0; i < gridHeight; i++) { for (int j = 0; j < gridWidth; j++) { if (grid[i][j] == 1) { gridPositionToInvstigate.push({i, j}); return; } } } } void floodfillIsland(vector<vector<int>>& grid, queue<pair<int,int>>& gridPositionToInvstigate, int x, int y, vector<vector<bool>>& visited, bool newLoc) { if(x < 0 || y < 0 || x >= gridWidth || y >= gridHeight || visited[y][x] || grid[y][x] != 1) { return; } visited[y][x] = true; grid[y][x] = 2; if (newLoc) { gridPositionToInvstigate.push({y, x}); } for(int i = 0; i < 4; i++) { int nextY = y + nextStepDims[i][0]; int nextX = x + nextStepDims[i][1]; floodfillIsland(grid, gridPositionToInvstigate, nextX, nextY, visited, true); } } };
44.881579
159
0.56523
jkerkela
a05608ff85f4cba18a3d7f4b7eb83ecb96cb4308
96,243
cpp
C++
quantlibnode.cpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
27
2016-11-19T16:51:21.000Z
2021-09-08T16:44:15.000Z
quantlibnode.cpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
1
2016-12-28T16:38:38.000Z
2017-02-17T05:32:13.000Z
quantlibnode.cpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
10
2016-12-28T02:31:38.000Z
2021-06-15T09:02:07.000Z
/* Copyright (C) 2016 -2017 Jerry Jin */ #include <v8.h> #include <node.h> #include <nan.h> #include "quantlibnode.hpp" #include <oh/repository.hpp> #include <oh/enumerations/typefactory.hpp> #include <oh/enumerations/enumregistry.hpp> #include <qlo/enumerations/register/register_all.hpp> using namespace node; using namespace v8; NAN_MODULE_INIT(init){ static ObjectHandler::Repository repository; static ObjectHandler::ProcessorFactory processorFactory; static ObjectHandler::EnumTypeRegistry enumTypeRegistry; static ObjectHandler::EnumClassRegistry enumClassRegistry; static ObjectHandler::EnumPairRegistry enumPairRegistry; QuantLibAddin::registerEnumerations(); Nan::SetMethod(target, "AbcdFunction", QuantLibNode::AbcdFunction); Nan::SetMethod(target, "AbcdCalibration", QuantLibNode::AbcdCalibration); Nan::SetMethod(target, "AbcdFunctionInstantaneousValue", QuantLibNode::AbcdFunctionInstantaneousValue); Nan::SetMethod(target, "AbcdFunctionInstantaneousCovariance", QuantLibNode::AbcdFunctionInstantaneousCovariance); Nan::SetMethod(target, "AbcdFunctionInstantaneousVariance", QuantLibNode::AbcdFunctionInstantaneousVariance); Nan::SetMethod(target, "AbcdFunctionInstantaneousVolatility", QuantLibNode::AbcdFunctionInstantaneousVolatility); Nan::SetMethod(target, "AbcdFunctionCovariance", QuantLibNode::AbcdFunctionCovariance); Nan::SetMethod(target, "AbcdFunctionVariance", QuantLibNode::AbcdFunctionVariance); Nan::SetMethod(target, "AbcdFunctionVolatility", QuantLibNode::AbcdFunctionVolatility); Nan::SetMethod(target, "AbcdFunctionShortTermVolatility", QuantLibNode::AbcdFunctionShortTermVolatility); Nan::SetMethod(target, "AbcdFunctionLongTermVolatility", QuantLibNode::AbcdFunctionLongTermVolatility); Nan::SetMethod(target, "AbcdFunctionMaximumLocation", QuantLibNode::AbcdFunctionMaximumLocation); Nan::SetMethod(target, "AbcdFunctionMaximumVolatility", QuantLibNode::AbcdFunctionMaximumVolatility); Nan::SetMethod(target, "AbcdFunctionA", QuantLibNode::AbcdFunctionA); Nan::SetMethod(target, "AbcdFunctionB", QuantLibNode::AbcdFunctionB); Nan::SetMethod(target, "AbcdFunctionC", QuantLibNode::AbcdFunctionC); Nan::SetMethod(target, "AbcdFunctionD", QuantLibNode::AbcdFunctionD); Nan::SetMethod(target, "AbcdDFunction", QuantLibNode::AbcdDFunction); Nan::SetMethod(target, "AbcdCalibrationCompute", QuantLibNode::AbcdCalibrationCompute); Nan::SetMethod(target, "AbcdCalibrationK", QuantLibNode::AbcdCalibrationK); Nan::SetMethod(target, "AbcdCalibrationError", QuantLibNode::AbcdCalibrationError); Nan::SetMethod(target, "AbcdCalibrationMaxError", QuantLibNode::AbcdCalibrationMaxError); Nan::SetMethod(target, "AbcdCalibrationEndCriteria", QuantLibNode::AbcdCalibrationEndCriteria); Nan::SetMethod(target, "AbcdCalibrationA", QuantLibNode::AbcdCalibrationA); Nan::SetMethod(target, "AbcdCalibrationB", QuantLibNode::AbcdCalibrationB); Nan::SetMethod(target, "AbcdCalibrationC", QuantLibNode::AbcdCalibrationC); Nan::SetMethod(target, "AbcdCalibrationD", QuantLibNode::AbcdCalibrationD); Nan::SetMethod(target, "AccountingEngine", QuantLibNode::AccountingEngine); Nan::SetMethod(target, "AccountingEngineMultiplePathValues", QuantLibNode::AccountingEngineMultiplePathValues); Nan::SetMethod(target, "AlphaFormInverseLinear", QuantLibNode::AlphaFormInverseLinear); Nan::SetMethod(target, "AlphaFormLinearHyperbolic", QuantLibNode::AlphaFormLinearHyperbolic); Nan::SetMethod(target, "AlphaFormOperator", QuantLibNode::AlphaFormOperator); Nan::SetMethod(target, "AlphaFormSetAlpha", QuantLibNode::AlphaFormSetAlpha); Nan::SetMethod(target, "AssetSwap", QuantLibNode::AssetSwap); Nan::SetMethod(target, "AssetSwap2", QuantLibNode::AssetSwap2); Nan::SetMethod(target, "AssetSwapBondLegAnalysis", QuantLibNode::AssetSwapBondLegAnalysis); Nan::SetMethod(target, "AssetSwapFloatingLegAnalysis", QuantLibNode::AssetSwapFloatingLegAnalysis); Nan::SetMethod(target, "AssetSwapFairSpread", QuantLibNode::AssetSwapFairSpread); Nan::SetMethod(target, "AssetSwapFloatingLegBPS", QuantLibNode::AssetSwapFloatingLegBPS); Nan::SetMethod(target, "AssetSwapFairCleanPrice", QuantLibNode::AssetSwapFairCleanPrice); Nan::SetMethod(target, "AssetSwapFairNonParRepayment", QuantLibNode::AssetSwapFairNonParRepayment); Nan::SetMethod(target, "AssetSwapParSwap", QuantLibNode::AssetSwapParSwap); Nan::SetMethod(target, "AssetSwapPayBondCoupon", QuantLibNode::AssetSwapPayBondCoupon); Nan::SetMethod(target, "GaussianLHPLossmodel", QuantLibNode::GaussianLHPLossmodel); Nan::SetMethod(target, "IHGaussPoolLossModel", QuantLibNode::IHGaussPoolLossModel); Nan::SetMethod(target, "IHStudentPoolLossModel", QuantLibNode::IHStudentPoolLossModel); Nan::SetMethod(target, "GBinomialLossmodel", QuantLibNode::GBinomialLossmodel); Nan::SetMethod(target, "TBinomialLossmodel", QuantLibNode::TBinomialLossmodel); Nan::SetMethod(target, "BaseCorrelationLossModel", QuantLibNode::BaseCorrelationLossModel); Nan::SetMethod(target, "GMCLossModel", QuantLibNode::GMCLossModel); Nan::SetMethod(target, "GRandomRRMCLossModel", QuantLibNode::GRandomRRMCLossModel); Nan::SetMethod(target, "TMCLossModel", QuantLibNode::TMCLossModel); Nan::SetMethod(target, "TRandomRRMCLossModel", QuantLibNode::TRandomRRMCLossModel); Nan::SetMethod(target, "GSaddlePointLossmodel", QuantLibNode::GSaddlePointLossmodel); Nan::SetMethod(target, "TSaddlePointLossmodel", QuantLibNode::TSaddlePointLossmodel); Nan::SetMethod(target, "GRecursiveLossmodel", QuantLibNode::GRecursiveLossmodel); Nan::SetMethod(target, "FixedRateBond", QuantLibNode::FixedRateBond); Nan::SetMethod(target, "FixedRateBond2", QuantLibNode::FixedRateBond2); Nan::SetMethod(target, "FloatingRateBond", QuantLibNode::FloatingRateBond); Nan::SetMethod(target, "CmsRateBond", QuantLibNode::CmsRateBond); Nan::SetMethod(target, "ZeroCouponBond", QuantLibNode::ZeroCouponBond); Nan::SetMethod(target, "Bond", QuantLibNode::Bond); Nan::SetMethod(target, "BondSettlementDays", QuantLibNode::BondSettlementDays); Nan::SetMethod(target, "BondCalendar", QuantLibNode::BondCalendar); Nan::SetMethod(target, "BondNotionals", QuantLibNode::BondNotionals); Nan::SetMethod(target, "BondNotional", QuantLibNode::BondNotional); Nan::SetMethod(target, "BondMaturityDate", QuantLibNode::BondMaturityDate); Nan::SetMethod(target, "BondIssueDate", QuantLibNode::BondIssueDate); Nan::SetMethod(target, "BondIsTradable", QuantLibNode::BondIsTradable); Nan::SetMethod(target, "BondSettlementDate", QuantLibNode::BondSettlementDate); Nan::SetMethod(target, "BondCleanPrice", QuantLibNode::BondCleanPrice); Nan::SetMethod(target, "BondDescription", QuantLibNode::BondDescription); Nan::SetMethod(target, "BondCurrency", QuantLibNode::BondCurrency); Nan::SetMethod(target, "BondRedemptionAmount", QuantLibNode::BondRedemptionAmount); Nan::SetMethod(target, "BondRedemptionDate", QuantLibNode::BondRedemptionDate); Nan::SetMethod(target, "BondFlowAnalysis", QuantLibNode::BondFlowAnalysis); Nan::SetMethod(target, "BondSetCouponPricer", QuantLibNode::BondSetCouponPricer); Nan::SetMethod(target, "BondSetCouponPricers", QuantLibNode::BondSetCouponPricers); Nan::SetMethod(target, "BondStartDate", QuantLibNode::BondStartDate); Nan::SetMethod(target, "BondPreviousCashFlowDate", QuantLibNode::BondPreviousCashFlowDate); Nan::SetMethod(target, "BondNextCashFlowDate", QuantLibNode::BondNextCashFlowDate); Nan::SetMethod(target, "BondPreviousCashFlowAmount", QuantLibNode::BondPreviousCashFlowAmount); Nan::SetMethod(target, "BondNextCashFlowAmount", QuantLibNode::BondNextCashFlowAmount); Nan::SetMethod(target, "BondPreviousCouponRate", QuantLibNode::BondPreviousCouponRate); Nan::SetMethod(target, "BondNextCouponRate", QuantLibNode::BondNextCouponRate); Nan::SetMethod(target, "BondAccrualStartDate", QuantLibNode::BondAccrualStartDate); Nan::SetMethod(target, "BondAccrualEndDate", QuantLibNode::BondAccrualEndDate); Nan::SetMethod(target, "BondReferencePeriodStart", QuantLibNode::BondReferencePeriodStart); Nan::SetMethod(target, "BondReferencePeriodEnd", QuantLibNode::BondReferencePeriodEnd); Nan::SetMethod(target, "BondAccrualPeriod", QuantLibNode::BondAccrualPeriod); Nan::SetMethod(target, "BondAccrualDays", QuantLibNode::BondAccrualDays); Nan::SetMethod(target, "BondAccruedPeriod", QuantLibNode::BondAccruedPeriod); Nan::SetMethod(target, "BondAccruedDays", QuantLibNode::BondAccruedDays); Nan::SetMethod(target, "BondAccruedAmount", QuantLibNode::BondAccruedAmount); Nan::SetMethod(target, "BondCleanPriceFromYieldTermStructure", QuantLibNode::BondCleanPriceFromYieldTermStructure); Nan::SetMethod(target, "BondBpsFromYieldTermStructure", QuantLibNode::BondBpsFromYieldTermStructure); Nan::SetMethod(target, "BondAtmRateFromYieldTermStructure", QuantLibNode::BondAtmRateFromYieldTermStructure); Nan::SetMethod(target, "BondCleanPriceFromYield", QuantLibNode::BondCleanPriceFromYield); Nan::SetMethod(target, "BondDirtyPriceFromYield", QuantLibNode::BondDirtyPriceFromYield); Nan::SetMethod(target, "BondBpsFromYield", QuantLibNode::BondBpsFromYield); Nan::SetMethod(target, "BondYieldFromCleanPrice", QuantLibNode::BondYieldFromCleanPrice); Nan::SetMethod(target, "BondDurationFromYield", QuantLibNode::BondDurationFromYield); Nan::SetMethod(target, "BondConvexityFromYield", QuantLibNode::BondConvexityFromYield); Nan::SetMethod(target, "BondCleanPriceFromZSpread", QuantLibNode::BondCleanPriceFromZSpread); Nan::SetMethod(target, "BondZSpreadFromCleanPrice", QuantLibNode::BondZSpreadFromCleanPrice); Nan::SetMethod(target, "BondAlive", QuantLibNode::BondAlive); Nan::SetMethod(target, "BondMaturityLookup", QuantLibNode::BondMaturityLookup); Nan::SetMethod(target, "BondMaturitySort", QuantLibNode::BondMaturitySort); Nan::SetMethod(target, "MTBrownianGeneratorFactory", QuantLibNode::MTBrownianGeneratorFactory); Nan::SetMethod(target, "CCTEU", QuantLibNode::CCTEU); Nan::SetMethod(target, "BTP", QuantLibNode::BTP); Nan::SetMethod(target, "BTP2", QuantLibNode::BTP2); Nan::SetMethod(target, "RendistatoBasket", QuantLibNode::RendistatoBasket); Nan::SetMethod(target, "RendistatoCalculator", QuantLibNode::RendistatoCalculator); Nan::SetMethod(target, "RendistatoEquivalentSwapLengthQuote", QuantLibNode::RendistatoEquivalentSwapLengthQuote); Nan::SetMethod(target, "RendistatoEquivalentSwapSpreadQuote", QuantLibNode::RendistatoEquivalentSwapSpreadQuote); Nan::SetMethod(target, "RendistatoBasketSize", QuantLibNode::RendistatoBasketSize); Nan::SetMethod(target, "RendistatoBasketOutstanding", QuantLibNode::RendistatoBasketOutstanding); Nan::SetMethod(target, "RendistatoBasketOutstandings", QuantLibNode::RendistatoBasketOutstandings); Nan::SetMethod(target, "RendistatoBasketWeights", QuantLibNode::RendistatoBasketWeights); Nan::SetMethod(target, "RendistatoCalculatorYield", QuantLibNode::RendistatoCalculatorYield); Nan::SetMethod(target, "RendistatoCalculatorDuration", QuantLibNode::RendistatoCalculatorDuration); Nan::SetMethod(target, "RendistatoCalculatorYields", QuantLibNode::RendistatoCalculatorYields); Nan::SetMethod(target, "RendistatoCalculatorDurations", QuantLibNode::RendistatoCalculatorDurations); Nan::SetMethod(target, "RendistatoCalculatorSwapLengths", QuantLibNode::RendistatoCalculatorSwapLengths); Nan::SetMethod(target, "RendistatoCalculatorSwapRates", QuantLibNode::RendistatoCalculatorSwapRates); Nan::SetMethod(target, "RendistatoCalculatorSwapYields", QuantLibNode::RendistatoCalculatorSwapYields); Nan::SetMethod(target, "RendistatoCalculatorSwapDurations", QuantLibNode::RendistatoCalculatorSwapDurations); Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapRate", QuantLibNode::RendistatoCalculatorEquivalentSwapRate); Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapYield", QuantLibNode::RendistatoCalculatorEquivalentSwapYield); Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapDuration", QuantLibNode::RendistatoCalculatorEquivalentSwapDuration); Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapSpread", QuantLibNode::RendistatoCalculatorEquivalentSwapSpread); Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapLength", QuantLibNode::RendistatoCalculatorEquivalentSwapLength); Nan::SetMethod(target, "CalendarHolidayList", QuantLibNode::CalendarHolidayList); Nan::SetMethod(target, "CalendarName", QuantLibNode::CalendarName); Nan::SetMethod(target, "CalendarIsBusinessDay", QuantLibNode::CalendarIsBusinessDay); Nan::SetMethod(target, "CalendarIsHoliday", QuantLibNode::CalendarIsHoliday); Nan::SetMethod(target, "CalendarIsEndOfMonth", QuantLibNode::CalendarIsEndOfMonth); Nan::SetMethod(target, "CalendarEndOfMonth", QuantLibNode::CalendarEndOfMonth); Nan::SetMethod(target, "CalendarAddHoliday", QuantLibNode::CalendarAddHoliday); Nan::SetMethod(target, "CalendarRemoveHoliday", QuantLibNode::CalendarRemoveHoliday); Nan::SetMethod(target, "CalendarAdjust", QuantLibNode::CalendarAdjust); Nan::SetMethod(target, "CalendarAdvance", QuantLibNode::CalendarAdvance); Nan::SetMethod(target, "CalendarBusinessDaysBetween", QuantLibNode::CalendarBusinessDaysBetween); Nan::SetMethod(target, "SwaptionHelper", QuantLibNode::SwaptionHelper); Nan::SetMethod(target, "CalibrationHelperSetPricingEngine", QuantLibNode::CalibrationHelperSetPricingEngine); Nan::SetMethod(target, "CalibrationHelperImpliedVolatility", QuantLibNode::CalibrationHelperImpliedVolatility); Nan::SetMethod(target, "SwaptionHelperModelValue", QuantLibNode::SwaptionHelperModelValue); Nan::SetMethod(target, "OneFactorAffineModelCalibrate", QuantLibNode::OneFactorAffineModelCalibrate); Nan::SetMethod(target, "ModelG2Calibrate", QuantLibNode::ModelG2Calibrate); Nan::SetMethod(target, "CapFloor", QuantLibNode::CapFloor); Nan::SetMethod(target, "MakeCapFloor", QuantLibNode::MakeCapFloor); Nan::SetMethod(target, "CapFloorType", QuantLibNode::CapFloorType); Nan::SetMethod(target, "CapFloorCapRates", QuantLibNode::CapFloorCapRates); Nan::SetMethod(target, "CapFloorFloorRates", QuantLibNode::CapFloorFloorRates); Nan::SetMethod(target, "CapFloorAtmRate", QuantLibNode::CapFloorAtmRate); Nan::SetMethod(target, "CapFloorStartDate", QuantLibNode::CapFloorStartDate); Nan::SetMethod(target, "CapFloorMaturityDate", QuantLibNode::CapFloorMaturityDate); Nan::SetMethod(target, "CapFloorImpliedVolatility", QuantLibNode::CapFloorImpliedVolatility); Nan::SetMethod(target, "CapFloorLegAnalysis", QuantLibNode::CapFloorLegAnalysis); Nan::SetMethod(target, "RelinkableHandleOptionletVolatilityStructure", QuantLibNode::RelinkableHandleOptionletVolatilityStructure); Nan::SetMethod(target, "ConstantOptionletVolatility", QuantLibNode::ConstantOptionletVolatility); Nan::SetMethod(target, "SpreadedOptionletVolatility", QuantLibNode::SpreadedOptionletVolatility); Nan::SetMethod(target, "StrippedOptionletAdapter", QuantLibNode::StrippedOptionletAdapter); Nan::SetMethod(target, "StrippedOptionlet", QuantLibNode::StrippedOptionlet); Nan::SetMethod(target, "OptionletStripper1", QuantLibNode::OptionletStripper1); Nan::SetMethod(target, "OptionletStripper2", QuantLibNode::OptionletStripper2); Nan::SetMethod(target, "CapFloorTermVolCurve", QuantLibNode::CapFloorTermVolCurve); Nan::SetMethod(target, "CapFloorTermVolSurface", QuantLibNode::CapFloorTermVolSurface); Nan::SetMethod(target, "OptionletVTSVolatility", QuantLibNode::OptionletVTSVolatility); Nan::SetMethod(target, "OptionletVTSVolatility2", QuantLibNode::OptionletVTSVolatility2); Nan::SetMethod(target, "OptionletVTSBlackVariance", QuantLibNode::OptionletVTSBlackVariance); Nan::SetMethod(target, "OptionletVTSBlackVariance2", QuantLibNode::OptionletVTSBlackVariance2); Nan::SetMethod(target, "StrippedOptionletBaseStrikes", QuantLibNode::StrippedOptionletBaseStrikes); Nan::SetMethod(target, "StrippedOptionletBaseOptionletVolatilities", QuantLibNode::StrippedOptionletBaseOptionletVolatilities); Nan::SetMethod(target, "StrippedOptionletBaseOptionletFixingDates", QuantLibNode::StrippedOptionletBaseOptionletFixingDates); Nan::SetMethod(target, "StrippedOptionletBaseOptionletFixingTimes", QuantLibNode::StrippedOptionletBaseOptionletFixingTimes); Nan::SetMethod(target, "StrippedOptionletBaseAtmOptionletRates", QuantLibNode::StrippedOptionletBaseAtmOptionletRates); Nan::SetMethod(target, "StrippedOptionletBaseDayCounter", QuantLibNode::StrippedOptionletBaseDayCounter); Nan::SetMethod(target, "StrippedOptionletBaseCalendar", QuantLibNode::StrippedOptionletBaseCalendar); Nan::SetMethod(target, "StrippedOptionletBaseSettlementDays", QuantLibNode::StrippedOptionletBaseSettlementDays); Nan::SetMethod(target, "StrippedOptionletBaseBusinessDayConvention", QuantLibNode::StrippedOptionletBaseBusinessDayConvention); Nan::SetMethod(target, "OptionletStripperOptionletFixingTenors", QuantLibNode::OptionletStripperOptionletFixingTenors); Nan::SetMethod(target, "OptionletStripperOptionletPaymentDates", QuantLibNode::OptionletStripperOptionletPaymentDates); Nan::SetMethod(target, "OptionletStripperOptionletAccrualPeriods", QuantLibNode::OptionletStripperOptionletAccrualPeriods); Nan::SetMethod(target, "OptionletStripper1CapFloorPrices", QuantLibNode::OptionletStripper1CapFloorPrices); Nan::SetMethod(target, "OptionletStripper1CapFloorVolatilities", QuantLibNode::OptionletStripper1CapFloorVolatilities); Nan::SetMethod(target, "OptionletStripper1OptionletPrices", QuantLibNode::OptionletStripper1OptionletPrices); Nan::SetMethod(target, "OptionletStripper1SwitchStrike", QuantLibNode::OptionletStripper1SwitchStrike); Nan::SetMethod(target, "OptionletStripper2SpreadsVol", QuantLibNode::OptionletStripper2SpreadsVol); Nan::SetMethod(target, "OptionletStripper2AtmCapFloorPrices", QuantLibNode::OptionletStripper2AtmCapFloorPrices); Nan::SetMethod(target, "OptionletStripper2AtmCapFloorStrikes", QuantLibNode::OptionletStripper2AtmCapFloorStrikes); Nan::SetMethod(target, "CapFloorTermVTSVolatility", QuantLibNode::CapFloorTermVTSVolatility); Nan::SetMethod(target, "CapFloorTermVTSVolatility2", QuantLibNode::CapFloorTermVTSVolatility2); Nan::SetMethod(target, "CapFloorTermVolCurveOptionTenors", QuantLibNode::CapFloorTermVolCurveOptionTenors); Nan::SetMethod(target, "CapFloorTermVolCurveOptionDates", QuantLibNode::CapFloorTermVolCurveOptionDates); Nan::SetMethod(target, "CapFloorTermVolSurfaceOptionTenors", QuantLibNode::CapFloorTermVolSurfaceOptionTenors); Nan::SetMethod(target, "CapFloorTermVolSurfaceOptionDates", QuantLibNode::CapFloorTermVolSurfaceOptionDates); Nan::SetMethod(target, "CapFloorTermVolSurfaceStrikes", QuantLibNode::CapFloorTermVolSurfaceStrikes); Nan::SetMethod(target, "CmsMarket", QuantLibNode::CmsMarket); Nan::SetMethod(target, "BrowseCmsMarket", QuantLibNode::BrowseCmsMarket); Nan::SetMethod(target, "CmsMarketCalibration", QuantLibNode::CmsMarketCalibration); Nan::SetMethod(target, "CmsMarketCalibrationCompute", QuantLibNode::CmsMarketCalibrationCompute); Nan::SetMethod(target, "CmsMarketCalibrationError", QuantLibNode::CmsMarketCalibrationError); Nan::SetMethod(target, "CmsMarketCalibrationEndCriteria", QuantLibNode::CmsMarketCalibrationEndCriteria); Nan::SetMethod(target, "CmsMarketCalibrationElapsed", QuantLibNode::CmsMarketCalibrationElapsed); Nan::SetMethod(target, "CmsMarketCalibrationSparseSabrParameters", QuantLibNode::CmsMarketCalibrationSparseSabrParameters); Nan::SetMethod(target, "CmsMarketCalibrationDenseSabrParameters", QuantLibNode::CmsMarketCalibrationDenseSabrParameters); Nan::SetMethod(target, "SimultaneousCalibrationBrowseCmsMarket", QuantLibNode::SimultaneousCalibrationBrowseCmsMarket); Nan::SetMethod(target, "MarketModelLmLinearExponentialCorrelationModel", QuantLibNode::MarketModelLmLinearExponentialCorrelationModel); Nan::SetMethod(target, "HistoricalForwardRatesAnalysis", QuantLibNode::HistoricalForwardRatesAnalysis); Nan::SetMethod(target, "HistoricalRatesAnalysis", QuantLibNode::HistoricalRatesAnalysis); Nan::SetMethod(target, "TimeHomogeneousForwardCorrelation", QuantLibNode::TimeHomogeneousForwardCorrelation); Nan::SetMethod(target, "ExponentialForwardCorrelation", QuantLibNode::ExponentialForwardCorrelation); Nan::SetMethod(target, "CotSwapFromFwdCorrelation", QuantLibNode::CotSwapFromFwdCorrelation); Nan::SetMethod(target, "HistoricalForwardRatesAnalysisSkippedDates", QuantLibNode::HistoricalForwardRatesAnalysisSkippedDates); Nan::SetMethod(target, "HistoricalForwardRatesAnalysisSkippedDatesErrorMessage", QuantLibNode::HistoricalForwardRatesAnalysisSkippedDatesErrorMessage); Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFailedDates", QuantLibNode::HistoricalForwardRatesAnalysisFailedDates); Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFailedDatesErrorMessage", QuantLibNode::HistoricalForwardRatesAnalysisFailedDatesErrorMessage); Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFixingPeriods", QuantLibNode::HistoricalForwardRatesAnalysisFixingPeriods); Nan::SetMethod(target, "HistoricalRatesAnalysisSkippedDates", QuantLibNode::HistoricalRatesAnalysisSkippedDates); Nan::SetMethod(target, "HistoricalRatesAnalysisSkippedDatesErrorMessage", QuantLibNode::HistoricalRatesAnalysisSkippedDatesErrorMessage); Nan::SetMethod(target, "PiecewiseConstantCorrelationCorrelation", QuantLibNode::PiecewiseConstantCorrelationCorrelation); Nan::SetMethod(target, "PiecewiseConstantCorrelationTimes", QuantLibNode::PiecewiseConstantCorrelationTimes); Nan::SetMethod(target, "PiecewiseConstantCorrelationNumberOfRates", QuantLibNode::PiecewiseConstantCorrelationNumberOfRates); Nan::SetMethod(target, "ExponentialCorrelations", QuantLibNode::ExponentialCorrelations); Nan::SetMethod(target, "FixedRateLeg", QuantLibNode::FixedRateLeg); Nan::SetMethod(target, "FixedRateLeg2", QuantLibNode::FixedRateLeg2); Nan::SetMethod(target, "IborLeg", QuantLibNode::IborLeg); Nan::SetMethod(target, "DigitalIborLeg", QuantLibNode::DigitalIborLeg); Nan::SetMethod(target, "CmsLeg", QuantLibNode::CmsLeg); Nan::SetMethod(target, "DigitalCmsLeg", QuantLibNode::DigitalCmsLeg); Nan::SetMethod(target, "RangeAccrualLeg", QuantLibNode::RangeAccrualLeg); Nan::SetMethod(target, "CmsZeroLeg", QuantLibNode::CmsZeroLeg); Nan::SetMethod(target, "IborCouponPricer", QuantLibNode::IborCouponPricer); Nan::SetMethod(target, "CmsCouponPricer", QuantLibNode::CmsCouponPricer); Nan::SetMethod(target, "ConundrumPricerByNumericalIntegration", QuantLibNode::ConundrumPricerByNumericalIntegration); Nan::SetMethod(target, "DigitalReplication", QuantLibNode::DigitalReplication); Nan::SetMethod(target, "ConundrumPricerByNumericalIntegrationUpperLimit", QuantLibNode::ConundrumPricerByNumericalIntegrationUpperLimit); Nan::SetMethod(target, "CreditDefaultSwap", QuantLibNode::CreditDefaultSwap); Nan::SetMethod(target, "MidPointCdsEngine", QuantLibNode::MidPointCdsEngine); Nan::SetMethod(target, "HazardRateCurve", QuantLibNode::HazardRateCurve); Nan::SetMethod(target, "SpreadCdsHelper", QuantLibNode::SpreadCdsHelper); Nan::SetMethod(target, "UpfrontCdsHelper", QuantLibNode::UpfrontCdsHelper); Nan::SetMethod(target, "PiecewiseHazardRateCurve", QuantLibNode::PiecewiseHazardRateCurve); Nan::SetMethod(target, "PiecewiseFlatForwardCurve", QuantLibNode::PiecewiseFlatForwardCurve); Nan::SetMethod(target, "RiskyFixedBond", QuantLibNode::RiskyFixedBond); Nan::SetMethod(target, "Issuer", QuantLibNode::Issuer); Nan::SetMethod(target, "DefaultEvent", QuantLibNode::DefaultEvent); Nan::SetMethod(target, "SyntheticCDO", QuantLibNode::SyntheticCDO); Nan::SetMethod(target, "MidPointCDOEngine", QuantLibNode::MidPointCDOEngine); Nan::SetMethod(target, "NthToDefault", QuantLibNode::NthToDefault); Nan::SetMethod(target, "IntegralNtdEngine", QuantLibNode::IntegralNtdEngine); Nan::SetMethod(target, "BlackCdsOptionEngine", QuantLibNode::BlackCdsOptionEngine); Nan::SetMethod(target, "CDSOption", QuantLibNode::CDSOption); Nan::SetMethod(target, "BaseCorrelationTermStructure", QuantLibNode::BaseCorrelationTermStructure); Nan::SetMethod(target, "CdsCouponLegNPV", QuantLibNode::CdsCouponLegNPV); Nan::SetMethod(target, "CdsDefaultLegNPV", QuantLibNode::CdsDefaultLegNPV); Nan::SetMethod(target, "CdsFairSpread", QuantLibNode::CdsFairSpread); Nan::SetMethod(target, "CdsFairUpfront", QuantLibNode::CdsFairUpfront); Nan::SetMethod(target, "HRDates", QuantLibNode::HRDates); Nan::SetMethod(target, "HRates", QuantLibNode::HRates); Nan::SetMethod(target, "CdsOptionImpliedVol", QuantLibNode::CdsOptionImpliedVol); Nan::SetMethod(target, "BaseCorrelationValue", QuantLibNode::BaseCorrelationValue); Nan::SetMethod(target, "CTSMMCapletOriginalCalibration", QuantLibNode::CTSMMCapletOriginalCalibration); Nan::SetMethod(target, "CTSMMCapletAlphaFormCalibration", QuantLibNode::CTSMMCapletAlphaFormCalibration); Nan::SetMethod(target, "CTSMMCapletMaxHomogeneityCalibration", QuantLibNode::CTSMMCapletMaxHomogeneityCalibration); Nan::SetMethod(target, "CTSMMCapletCalibrationCalibrate", QuantLibNode::CTSMMCapletCalibrationCalibrate); Nan::SetMethod(target, "CTSMMCapletCalibrationFailures", QuantLibNode::CTSMMCapletCalibrationFailures); Nan::SetMethod(target, "CTSMMCapletCalibrationDeformationSize", QuantLibNode::CTSMMCapletCalibrationDeformationSize); Nan::SetMethod(target, "CTSMMCapletCalibrationMarketCapletVols", QuantLibNode::CTSMMCapletCalibrationMarketCapletVols); Nan::SetMethod(target, "CTSMMCapletCalibrationModelCapletVols", QuantLibNode::CTSMMCapletCalibrationModelCapletVols); Nan::SetMethod(target, "CTSMMCapletCalibrationCapletRmsError", QuantLibNode::CTSMMCapletCalibrationCapletRmsError); Nan::SetMethod(target, "CTSMMCapletCalibrationCapletMaxError", QuantLibNode::CTSMMCapletCalibrationCapletMaxError); Nan::SetMethod(target, "CTSMMCapletCalibrationMarketSwaptionVols", QuantLibNode::CTSMMCapletCalibrationMarketSwaptionVols); Nan::SetMethod(target, "CTSMMCapletCalibrationModelSwaptionVols", QuantLibNode::CTSMMCapletCalibrationModelSwaptionVols); Nan::SetMethod(target, "CTSMMCapletCalibrationSwaptionRmsError", QuantLibNode::CTSMMCapletCalibrationSwaptionRmsError); Nan::SetMethod(target, "CTSMMCapletCalibrationSwaptionMaxError", QuantLibNode::CTSMMCapletCalibrationSwaptionMaxError); Nan::SetMethod(target, "CTSMMCapletCalibrationSwapPseudoRoot", QuantLibNode::CTSMMCapletCalibrationSwapPseudoRoot); Nan::SetMethod(target, "CTSMMCapletCalibrationTimeDependentCalibratedSwaptionVols", QuantLibNode::CTSMMCapletCalibrationTimeDependentCalibratedSwaptionVols); Nan::SetMethod(target, "CTSMMCapletCalibrationTimeDependentUnCalibratedSwaptionVols", QuantLibNode::CTSMMCapletCalibrationTimeDependentUnCalibratedSwaptionVols); Nan::SetMethod(target, "CTSMMCapletAlphaFormCalibrationAlpha", QuantLibNode::CTSMMCapletAlphaFormCalibrationAlpha); Nan::SetMethod(target, "CMSwapCurveState", QuantLibNode::CMSwapCurveState); Nan::SetMethod(target, "CoterminalSwapCurveState", QuantLibNode::CoterminalSwapCurveState); Nan::SetMethod(target, "LMMCurveState", QuantLibNode::LMMCurveState); Nan::SetMethod(target, "CurveStateRateTimes", QuantLibNode::CurveStateRateTimes); Nan::SetMethod(target, "CurveStateRateTaus", QuantLibNode::CurveStateRateTaus); Nan::SetMethod(target, "CurveStateForwardRates", QuantLibNode::CurveStateForwardRates); Nan::SetMethod(target, "CurveStateCoterminalSwapRates", QuantLibNode::CurveStateCoterminalSwapRates); Nan::SetMethod(target, "CurveStateCMSwapRates", QuantLibNode::CurveStateCMSwapRates); Nan::SetMethod(target, "CMSwapCurveStateSetOnCMSwapRates", QuantLibNode::CMSwapCurveStateSetOnCMSwapRates); Nan::SetMethod(target, "CoterminalSwapCurveStateSetOnCoterminalSwapRates", QuantLibNode::CoterminalSwapCurveStateSetOnCoterminalSwapRates); Nan::SetMethod(target, "LMMCurveStateSetOnForwardRates", QuantLibNode::LMMCurveStateSetOnForwardRates); Nan::SetMethod(target, "LMMCurveStateSetOnDiscountRatios", QuantLibNode::LMMCurveStateSetOnDiscountRatios); Nan::SetMethod(target, "ForwardsFromDiscountRatios", QuantLibNode::ForwardsFromDiscountRatios); Nan::SetMethod(target, "CoterminalSwapRatesFromDiscountRatios", QuantLibNode::CoterminalSwapRatesFromDiscountRatios); Nan::SetMethod(target, "CoterminalSwapAnnuitiesFromDiscountRatios", QuantLibNode::CoterminalSwapAnnuitiesFromDiscountRatios); Nan::SetMethod(target, "ConstantMaturitySwapRatesFromDiscountRatios", QuantLibNode::ConstantMaturitySwapRatesFromDiscountRatios); Nan::SetMethod(target, "ConstantMaturitySwapAnnuitiesFromDiscountRatios", QuantLibNode::ConstantMaturitySwapAnnuitiesFromDiscountRatios); Nan::SetMethod(target, "PeriodFromFrequency", QuantLibNode::PeriodFromFrequency); Nan::SetMethod(target, "FrequencyFromPeriod", QuantLibNode::FrequencyFromPeriod); Nan::SetMethod(target, "PeriodLessThan", QuantLibNode::PeriodLessThan); Nan::SetMethod(target, "PeriodEquivalent", QuantLibNode::PeriodEquivalent); Nan::SetMethod(target, "DateMinDate", QuantLibNode::DateMinDate); Nan::SetMethod(target, "DateMaxDate", QuantLibNode::DateMaxDate); Nan::SetMethod(target, "DateIsLeap", QuantLibNode::DateIsLeap); Nan::SetMethod(target, "DateEndOfMonth", QuantLibNode::DateEndOfMonth); Nan::SetMethod(target, "DateIsEndOfMonth", QuantLibNode::DateIsEndOfMonth); Nan::SetMethod(target, "DateNextWeekday", QuantLibNode::DateNextWeekday); Nan::SetMethod(target, "DateNthWeekday", QuantLibNode::DateNthWeekday); Nan::SetMethod(target, "IMMIsIMMdate", QuantLibNode::IMMIsIMMdate); Nan::SetMethod(target, "IMMIsIMMcode", QuantLibNode::IMMIsIMMcode); Nan::SetMethod(target, "IMMcode", QuantLibNode::IMMcode); Nan::SetMethod(target, "IMMNextCode", QuantLibNode::IMMNextCode); Nan::SetMethod(target, "IMMNextCodes", QuantLibNode::IMMNextCodes); Nan::SetMethod(target, "IMMdate", QuantLibNode::IMMdate); Nan::SetMethod(target, "IMMNextDate", QuantLibNode::IMMNextDate); Nan::SetMethod(target, "IMMNextDates", QuantLibNode::IMMNextDates); Nan::SetMethod(target, "ASXIsASXdate", QuantLibNode::ASXIsASXdate); Nan::SetMethod(target, "ASXIsASXcode", QuantLibNode::ASXIsASXcode); Nan::SetMethod(target, "ASXcode", QuantLibNode::ASXcode); Nan::SetMethod(target, "ASXNextCode", QuantLibNode::ASXNextCode); Nan::SetMethod(target, "ASXNextCodes", QuantLibNode::ASXNextCodes); Nan::SetMethod(target, "ASXdate", QuantLibNode::ASXdate); Nan::SetMethod(target, "ASXNextDate", QuantLibNode::ASXNextDate); Nan::SetMethod(target, "ASXNextDates", QuantLibNode::ASXNextDates); Nan::SetMethod(target, "ECBKnownDates", QuantLibNode::ECBKnownDates); Nan::SetMethod(target, "ECBAddDate", QuantLibNode::ECBAddDate); Nan::SetMethod(target, "ECBRemoveDate", QuantLibNode::ECBRemoveDate); Nan::SetMethod(target, "ECBdate2", QuantLibNode::ECBdate2); Nan::SetMethod(target, "ECBdate", QuantLibNode::ECBdate); Nan::SetMethod(target, "ECBcode", QuantLibNode::ECBcode); Nan::SetMethod(target, "ECBNextDate", QuantLibNode::ECBNextDate); Nan::SetMethod(target, "ECBNextDate2", QuantLibNode::ECBNextDate2); Nan::SetMethod(target, "ECBNextDates", QuantLibNode::ECBNextDates); Nan::SetMethod(target, "ECBIsECBdate", QuantLibNode::ECBIsECBdate); Nan::SetMethod(target, "ECBIsECBcode", QuantLibNode::ECBIsECBcode); Nan::SetMethod(target, "ECBNextCode", QuantLibNode::ECBNextCode); Nan::SetMethod(target, "ECBNextCode2", QuantLibNode::ECBNextCode2); Nan::SetMethod(target, "DayCounterName", QuantLibNode::DayCounterName); Nan::SetMethod(target, "DayCounterDayCount", QuantLibNode::DayCounterDayCount); Nan::SetMethod(target, "DayCounterYearFraction", QuantLibNode::DayCounterYearFraction); Nan::SetMethod(target, "CreditBasket", QuantLibNode::CreditBasket); Nan::SetMethod(target, "CreditBasketSetLossModel", QuantLibNode::CreditBasketSetLossModel); Nan::SetMethod(target, "CreditBasketSize", QuantLibNode::CreditBasketSize); Nan::SetMethod(target, "CreditBasketLiveNotional", QuantLibNode::CreditBasketLiveNotional); Nan::SetMethod(target, "CreditBasketLoss", QuantLibNode::CreditBasketLoss); Nan::SetMethod(target, "CreditBasketAttachLive", QuantLibNode::CreditBasketAttachLive); Nan::SetMethod(target, "CreditBasketDetachLive", QuantLibNode::CreditBasketDetachLive); Nan::SetMethod(target, "ExpectedTrancheLoss", QuantLibNode::ExpectedTrancheLoss); Nan::SetMethod(target, "CreditBasketPercentile", QuantLibNode::CreditBasketPercentile); Nan::SetMethod(target, "CreditBasketESF", QuantLibNode::CreditBasketESF); Nan::SetMethod(target, "CreditBasketNthEventP", QuantLibNode::CreditBasketNthEventP); Nan::SetMethod(target, "CreditBasketProbLoss", QuantLibNode::CreditBasketProbLoss); Nan::SetMethod(target, "CreditBasketSplitLoss", QuantLibNode::CreditBasketSplitLoss); Nan::SetMethod(target, "CreditBasketDefaulCorrel", QuantLibNode::CreditBasketDefaulCorrel); Nan::SetMethod(target, "RelinkableHandleDefaultProbabilityTermStructure", QuantLibNode::RelinkableHandleDefaultProbabilityTermStructure); Nan::SetMethod(target, "FlatHazardRate", QuantLibNode::FlatHazardRate); Nan::SetMethod(target, "DefaultTSDefaultProbability", QuantLibNode::DefaultTSDefaultProbability); Nan::SetMethod(target, "ProbabilityToHR", QuantLibNode::ProbabilityToHR); Nan::SetMethod(target, "LMMDriftCalculator", QuantLibNode::LMMDriftCalculator); Nan::SetMethod(target, "LMMNormalDriftCalculator", QuantLibNode::LMMNormalDriftCalculator); Nan::SetMethod(target, "CMSMMDriftCalculator", QuantLibNode::CMSMMDriftCalculator); Nan::SetMethod(target, "SMMDriftCalculator", QuantLibNode::SMMDriftCalculator); Nan::SetMethod(target, "LMMDriftCalculatorComputePlain", QuantLibNode::LMMDriftCalculatorComputePlain); Nan::SetMethod(target, "LMMDriftCalculatorComputeReduced", QuantLibNode::LMMDriftCalculatorComputeReduced); Nan::SetMethod(target, "LMMDriftCalculatorCompute", QuantLibNode::LMMDriftCalculatorCompute); Nan::SetMethod(target, "LMMNormalDriftCalculatorComputePlain", QuantLibNode::LMMNormalDriftCalculatorComputePlain); Nan::SetMethod(target, "LMMNormalDriftCalculatorComputeReduced", QuantLibNode::LMMNormalDriftCalculatorComputeReduced); Nan::SetMethod(target, "LMMNormalDriftCalculatorCompute", QuantLibNode::LMMNormalDriftCalculatorCompute); Nan::SetMethod(target, "CMSMMDriftCalculatorCompute", QuantLibNode::CMSMMDriftCalculatorCompute); Nan::SetMethod(target, "SMMDriftCalculatorCompute", QuantLibNode::SMMDriftCalculatorCompute); Nan::SetMethod(target, "EvolutionDescription", QuantLibNode::EvolutionDescription); Nan::SetMethod(target, "EvolutionDescriptionFromProduct", QuantLibNode::EvolutionDescriptionFromProduct); Nan::SetMethod(target, "EvolutionDescriptionRateTimes", QuantLibNode::EvolutionDescriptionRateTimes); Nan::SetMethod(target, "EvolutionDescriptionRateTaus", QuantLibNode::EvolutionDescriptionRateTaus); Nan::SetMethod(target, "EvolutionDescriptionEvolutionTimes", QuantLibNode::EvolutionDescriptionEvolutionTimes); Nan::SetMethod(target, "EvolutionDescriptionFirstAliveRate", QuantLibNode::EvolutionDescriptionFirstAliveRate); Nan::SetMethod(target, "EvolutionDescriptionNumberOfRates", QuantLibNode::EvolutionDescriptionNumberOfRates); Nan::SetMethod(target, "EvolutionDescriptionNumberOfSteps", QuantLibNode::EvolutionDescriptionNumberOfSteps); Nan::SetMethod(target, "TerminalMeasure", QuantLibNode::TerminalMeasure); Nan::SetMethod(target, "MoneyMarketMeasure", QuantLibNode::MoneyMarketMeasure); Nan::SetMethod(target, "MoneyMarketPlusMeasure", QuantLibNode::MoneyMarketPlusMeasure); Nan::SetMethod(target, "IsInTerminalMeasure", QuantLibNode::IsInTerminalMeasure); Nan::SetMethod(target, "IsInMoneyMarketMeasure", QuantLibNode::IsInMoneyMarketMeasure); Nan::SetMethod(target, "IsInMoneyMarketPlusMeasure", QuantLibNode::IsInMoneyMarketPlusMeasure); Nan::SetMethod(target, "AmericanExercise", QuantLibNode::AmericanExercise); Nan::SetMethod(target, "EuropeanExercise", QuantLibNode::EuropeanExercise); Nan::SetMethod(target, "BermudanExercise", QuantLibNode::BermudanExercise); Nan::SetMethod(target, "ExerciseDates", QuantLibNode::ExerciseDates); Nan::SetMethod(target, "ExerciseLastDate", QuantLibNode::ExerciseLastDate); Nan::SetMethod(target, "FRA", QuantLibNode::FRA); Nan::SetMethod(target, "FRAforwardRate", QuantLibNode::FRAforwardRate); Nan::SetMethod(target, "FRAforwardValue", QuantLibNode::FRAforwardValue); Nan::SetMethod(target, "FRAspotValue", QuantLibNode::FRAspotValue); Nan::SetMethod(target, "HandleCurrentLink", QuantLibNode::HandleCurrentLink); Nan::SetMethod(target, "HandleEmpty", QuantLibNode::HandleEmpty); Nan::SetMethod(target, "RelinkableHandleLinkTo", QuantLibNode::RelinkableHandleLinkTo); Nan::SetMethod(target, "IborIndex", QuantLibNode::IborIndex); Nan::SetMethod(target, "OvernightIndex", QuantLibNode::OvernightIndex); Nan::SetMethod(target, "Euribor", QuantLibNode::Euribor); Nan::SetMethod(target, "Euribor365", QuantLibNode::Euribor365); Nan::SetMethod(target, "Eonia", QuantLibNode::Eonia); Nan::SetMethod(target, "Libor", QuantLibNode::Libor); Nan::SetMethod(target, "Sonia", QuantLibNode::Sonia); Nan::SetMethod(target, "SwapIndex", QuantLibNode::SwapIndex); Nan::SetMethod(target, "EuriborSwap", QuantLibNode::EuriborSwap); Nan::SetMethod(target, "LiborSwap", QuantLibNode::LiborSwap); Nan::SetMethod(target, "EuriborSwapIsdaFixA", QuantLibNode::EuriborSwapIsdaFixA); Nan::SetMethod(target, "BMAIndex", QuantLibNode::BMAIndex); Nan::SetMethod(target, "ProxyIbor", QuantLibNode::ProxyIbor); Nan::SetMethod(target, "IndexName", QuantLibNode::IndexName); Nan::SetMethod(target, "IndexFixingCalendar", QuantLibNode::IndexFixingCalendar); Nan::SetMethod(target, "IndexIsValidFixingDate", QuantLibNode::IndexIsValidFixingDate); Nan::SetMethod(target, "IndexFixing", QuantLibNode::IndexFixing); Nan::SetMethod(target, "IndexAddFixings", QuantLibNode::IndexAddFixings); Nan::SetMethod(target, "IndexAddFixings2", QuantLibNode::IndexAddFixings2); Nan::SetMethod(target, "IndexClearFixings", QuantLibNode::IndexClearFixings); Nan::SetMethod(target, "InterestRateIndexFamilyName", QuantLibNode::InterestRateIndexFamilyName); Nan::SetMethod(target, "InterestRateIndexTenor", QuantLibNode::InterestRateIndexTenor); Nan::SetMethod(target, "InterestRateIndexFixingDays", QuantLibNode::InterestRateIndexFixingDays); Nan::SetMethod(target, "InterestRateIndexCurrency", QuantLibNode::InterestRateIndexCurrency); Nan::SetMethod(target, "InterestRateIndexDayCounter", QuantLibNode::InterestRateIndexDayCounter); Nan::SetMethod(target, "InterestRateIndexValueDate", QuantLibNode::InterestRateIndexValueDate); Nan::SetMethod(target, "InterestRateIndexFixingDate", QuantLibNode::InterestRateIndexFixingDate); Nan::SetMethod(target, "InterestRateIndexMaturity", QuantLibNode::InterestRateIndexMaturity); Nan::SetMethod(target, "IborIndexBusinessDayConv", QuantLibNode::IborIndexBusinessDayConv); Nan::SetMethod(target, "IborIndexEndOfMonth", QuantLibNode::IborIndexEndOfMonth); Nan::SetMethod(target, "SwapIndexFixedLegTenor", QuantLibNode::SwapIndexFixedLegTenor); Nan::SetMethod(target, "SwapIndexFixedLegBDC", QuantLibNode::SwapIndexFixedLegBDC); Nan::SetMethod(target, "InstrumentNPV", QuantLibNode::InstrumentNPV); Nan::SetMethod(target, "InstrumentErrorEstimate", QuantLibNode::InstrumentErrorEstimate); Nan::SetMethod(target, "InstrumentValuationDate", QuantLibNode::InstrumentValuationDate); Nan::SetMethod(target, "InstrumentResults", QuantLibNode::InstrumentResults); Nan::SetMethod(target, "InstrumentIsExpired", QuantLibNode::InstrumentIsExpired); Nan::SetMethod(target, "InstrumentSetPricingEngine", QuantLibNode::InstrumentSetPricingEngine); Nan::SetMethod(target, "Interpolation", QuantLibNode::Interpolation); Nan::SetMethod(target, "MixedLinearCubicInterpolation", QuantLibNode::MixedLinearCubicInterpolation); Nan::SetMethod(target, "CubicInterpolation", QuantLibNode::CubicInterpolation); Nan::SetMethod(target, "AbcdInterpolation", QuantLibNode::AbcdInterpolation); Nan::SetMethod(target, "SABRInterpolation", QuantLibNode::SABRInterpolation); Nan::SetMethod(target, "Interpolation2D", QuantLibNode::Interpolation2D); Nan::SetMethod(target, "ExtrapolatorEnableExtrapolation", QuantLibNode::ExtrapolatorEnableExtrapolation); Nan::SetMethod(target, "InterpolationInterpolate", QuantLibNode::InterpolationInterpolate); Nan::SetMethod(target, "InterpolationDerivative", QuantLibNode::InterpolationDerivative); Nan::SetMethod(target, "InterpolationSecondDerivative", QuantLibNode::InterpolationSecondDerivative); Nan::SetMethod(target, "InterpolationPrimitive", QuantLibNode::InterpolationPrimitive); Nan::SetMethod(target, "InterpolationIsInRange", QuantLibNode::InterpolationIsInRange); Nan::SetMethod(target, "InterpolationXmin", QuantLibNode::InterpolationXmin); Nan::SetMethod(target, "InterpolationXmax", QuantLibNode::InterpolationXmax); Nan::SetMethod(target, "CubicInterpolationPrimitiveConstants", QuantLibNode::CubicInterpolationPrimitiveConstants); Nan::SetMethod(target, "CubicInterpolationACoefficients", QuantLibNode::CubicInterpolationACoefficients); Nan::SetMethod(target, "CubicInterpolationBCoefficients", QuantLibNode::CubicInterpolationBCoefficients); Nan::SetMethod(target, "CubicInterpolationCCoefficients", QuantLibNode::CubicInterpolationCCoefficients); Nan::SetMethod(target, "CubicInterpolationMonotonicityAdjustments", QuantLibNode::CubicInterpolationMonotonicityAdjustments); Nan::SetMethod(target, "AbcdInterpolationA", QuantLibNode::AbcdInterpolationA); Nan::SetMethod(target, "AbcdInterpolationB", QuantLibNode::AbcdInterpolationB); Nan::SetMethod(target, "AbcdInterpolationC", QuantLibNode::AbcdInterpolationC); Nan::SetMethod(target, "AbcdInterpolationD", QuantLibNode::AbcdInterpolationD); Nan::SetMethod(target, "AbcdInterpolationRmsError", QuantLibNode::AbcdInterpolationRmsError); Nan::SetMethod(target, "AbcdInterpolationMaxError", QuantLibNode::AbcdInterpolationMaxError); Nan::SetMethod(target, "AbcdInterpolationEndCriteria", QuantLibNode::AbcdInterpolationEndCriteria); Nan::SetMethod(target, "SABRInterpolationExpiry", QuantLibNode::SABRInterpolationExpiry); Nan::SetMethod(target, "SABRInterpolationForward", QuantLibNode::SABRInterpolationForward); Nan::SetMethod(target, "SABRInterpolationAlpha", QuantLibNode::SABRInterpolationAlpha); Nan::SetMethod(target, "SABRInterpolationBeta", QuantLibNode::SABRInterpolationBeta); Nan::SetMethod(target, "SABRInterpolationNu", QuantLibNode::SABRInterpolationNu); Nan::SetMethod(target, "SABRInterpolationRho", QuantLibNode::SABRInterpolationRho); Nan::SetMethod(target, "SABRInterpolationRmsError", QuantLibNode::SABRInterpolationRmsError); Nan::SetMethod(target, "SABRInterpolationMaxError", QuantLibNode::SABRInterpolationMaxError); Nan::SetMethod(target, "SABRInterpolationEndCriteria", QuantLibNode::SABRInterpolationEndCriteria); Nan::SetMethod(target, "SABRInterpolationWeights", QuantLibNode::SABRInterpolationWeights); Nan::SetMethod(target, "Interpolation2DXmin", QuantLibNode::Interpolation2DXmin); Nan::SetMethod(target, "Interpolation2DXmax", QuantLibNode::Interpolation2DXmax); Nan::SetMethod(target, "Interpolation2DXvalues", QuantLibNode::Interpolation2DXvalues); Nan::SetMethod(target, "Interpolation2DYmin", QuantLibNode::Interpolation2DYmin); Nan::SetMethod(target, "Interpolation2DYmax", QuantLibNode::Interpolation2DYmax); Nan::SetMethod(target, "Interpolation2DYvalues", QuantLibNode::Interpolation2DYvalues); Nan::SetMethod(target, "Interpolation2DzData", QuantLibNode::Interpolation2DzData); Nan::SetMethod(target, "Interpolation2DIsInRange", QuantLibNode::Interpolation2DIsInRange); Nan::SetMethod(target, "Interpolation2DInterpolate", QuantLibNode::Interpolation2DInterpolate); Nan::SetMethod(target, "GaussianDefaultProbLM", QuantLibNode::GaussianDefaultProbLM); Nan::SetMethod(target, "TDefaultProbLM", QuantLibNode::TDefaultProbLM); Nan::SetMethod(target, "GaussianLMDefaultCorrel", QuantLibNode::GaussianLMDefaultCorrel); Nan::SetMethod(target, "GaussianLMAssetCorrel", QuantLibNode::GaussianLMAssetCorrel); Nan::SetMethod(target, "GaussianLMProbNHits", QuantLibNode::GaussianLMProbNHits); Nan::SetMethod(target, "TLMDefaultCorrel", QuantLibNode::TLMDefaultCorrel); Nan::SetMethod(target, "TLMAssetCorrel", QuantLibNode::TLMAssetCorrel); Nan::SetMethod(target, "TLMProbNHits", QuantLibNode::TLMProbNHits); Nan::SetMethod(target, "Leg", QuantLibNode::Leg); Nan::SetMethod(target, "LegFromCapFloor", QuantLibNode::LegFromCapFloor); Nan::SetMethod(target, "LegFromSwap", QuantLibNode::LegFromSwap); Nan::SetMethod(target, "MultiPhaseLeg", QuantLibNode::MultiPhaseLeg); Nan::SetMethod(target, "InterestRate", QuantLibNode::InterestRate); Nan::SetMethod(target, "LegFlowAnalysis", QuantLibNode::LegFlowAnalysis); Nan::SetMethod(target, "LegSetCouponPricers", QuantLibNode::LegSetCouponPricers); Nan::SetMethod(target, "InterestRateRate", QuantLibNode::InterestRateRate); Nan::SetMethod(target, "InterestRateDayCounter", QuantLibNode::InterestRateDayCounter); Nan::SetMethod(target, "InterestRateCompounding", QuantLibNode::InterestRateCompounding); Nan::SetMethod(target, "InterestRateFrequency", QuantLibNode::InterestRateFrequency); Nan::SetMethod(target, "InterestRateDiscountFactor", QuantLibNode::InterestRateDiscountFactor); Nan::SetMethod(target, "InterestRateCompoundFactor", QuantLibNode::InterestRateCompoundFactor); Nan::SetMethod(target, "InterestRateEquivalentRate", QuantLibNode::InterestRateEquivalentRate); Nan::SetMethod(target, "LegStartDate", QuantLibNode::LegStartDate); Nan::SetMethod(target, "LegMaturityDate", QuantLibNode::LegMaturityDate); Nan::SetMethod(target, "LegIsExpired", QuantLibNode::LegIsExpired); Nan::SetMethod(target, "LegPreviousCashFlowDate", QuantLibNode::LegPreviousCashFlowDate); Nan::SetMethod(target, "LegNextCashFlowDate", QuantLibNode::LegNextCashFlowDate); Nan::SetMethod(target, "LegPreviousCashFlowAmount", QuantLibNode::LegPreviousCashFlowAmount); Nan::SetMethod(target, "LegNextCashFlowAmount", QuantLibNode::LegNextCashFlowAmount); Nan::SetMethod(target, "LegPreviousCouponRate", QuantLibNode::LegPreviousCouponRate); Nan::SetMethod(target, "LegNextCouponRate", QuantLibNode::LegNextCouponRate); Nan::SetMethod(target, "LegNominal", QuantLibNode::LegNominal); Nan::SetMethod(target, "LegAccrualStartDate", QuantLibNode::LegAccrualStartDate); Nan::SetMethod(target, "LegAccrualEndDate", QuantLibNode::LegAccrualEndDate); Nan::SetMethod(target, "LegReferencePeriodStart", QuantLibNode::LegReferencePeriodStart); Nan::SetMethod(target, "LegReferencePeriodEnd", QuantLibNode::LegReferencePeriodEnd); Nan::SetMethod(target, "LegAccrualPeriod", QuantLibNode::LegAccrualPeriod); Nan::SetMethod(target, "LegAccrualDays", QuantLibNode::LegAccrualDays); Nan::SetMethod(target, "LegAccruedPeriod", QuantLibNode::LegAccruedPeriod); Nan::SetMethod(target, "LegAccruedDays", QuantLibNode::LegAccruedDays); Nan::SetMethod(target, "LegAccruedAmount", QuantLibNode::LegAccruedAmount); Nan::SetMethod(target, "LegNPV", QuantLibNode::LegNPV); Nan::SetMethod(target, "LegBPS", QuantLibNode::LegBPS); Nan::SetMethod(target, "LegAtmRate", QuantLibNode::LegAtmRate); Nan::SetMethod(target, "LegNPVFromYield", QuantLibNode::LegNPVFromYield); Nan::SetMethod(target, "LegBPSFromYield", QuantLibNode::LegBPSFromYield); Nan::SetMethod(target, "LegYield", QuantLibNode::LegYield); Nan::SetMethod(target, "LegDuration", QuantLibNode::LegDuration); Nan::SetMethod(target, "LegConvexity", QuantLibNode::LegConvexity); Nan::SetMethod(target, "LegBasisPointValue", QuantLibNode::LegBasisPointValue); Nan::SetMethod(target, "LegYieldValueBasisPoint", QuantLibNode::LegYieldValueBasisPoint); Nan::SetMethod(target, "LegNPVFromZSpread", QuantLibNode::LegNPVFromZSpread); Nan::SetMethod(target, "LegZSpread", QuantLibNode::LegZSpread); Nan::SetMethod(target, "InterestRateImpliedRate", QuantLibNode::InterestRateImpliedRate); Nan::SetMethod(target, "ForwardRatePc", QuantLibNode::ForwardRatePc); Nan::SetMethod(target, "ForwardRateIpc", QuantLibNode::ForwardRateIpc); Nan::SetMethod(target, "ForwardRateNormalPc", QuantLibNode::ForwardRateNormalPc); Nan::SetMethod(target, "MarketModelEvolverStartNewPath", QuantLibNode::MarketModelEvolverStartNewPath); Nan::SetMethod(target, "MarketModelEvolverAdvanceStep", QuantLibNode::MarketModelEvolverAdvanceStep); Nan::SetMethod(target, "MarketModelEvolverCurrentStep", QuantLibNode::MarketModelEvolverCurrentStep); Nan::SetMethod(target, "MarketModelEvolverNumeraires", QuantLibNode::MarketModelEvolverNumeraires); Nan::SetMethod(target, "FlatVol", QuantLibNode::FlatVol); Nan::SetMethod(target, "AbcdVol", QuantLibNode::AbcdVol); Nan::SetMethod(target, "PseudoRootFacade", QuantLibNode::PseudoRootFacade); Nan::SetMethod(target, "CotSwapToFwdAdapter", QuantLibNode::CotSwapToFwdAdapter); Nan::SetMethod(target, "FwdPeriodAdapter", QuantLibNode::FwdPeriodAdapter); Nan::SetMethod(target, "FwdToCotSwapAdapter", QuantLibNode::FwdToCotSwapAdapter); Nan::SetMethod(target, "FlatVolFactory", QuantLibNode::FlatVolFactory); Nan::SetMethod(target, "MarketModelInitialRates", QuantLibNode::MarketModelInitialRates); Nan::SetMethod(target, "MarketModelDisplacements", QuantLibNode::MarketModelDisplacements); Nan::SetMethod(target, "MarketModelNumberOfRates", QuantLibNode::MarketModelNumberOfRates); Nan::SetMethod(target, "MarketModelNumberOfFactors", QuantLibNode::MarketModelNumberOfFactors); Nan::SetMethod(target, "MarketModelNumberOfSteps", QuantLibNode::MarketModelNumberOfSteps); Nan::SetMethod(target, "MarketModelPseudoRoot", QuantLibNode::MarketModelPseudoRoot); Nan::SetMethod(target, "MarketModelCovariance", QuantLibNode::MarketModelCovariance); Nan::SetMethod(target, "MarketModelTotalCovariance", QuantLibNode::MarketModelTotalCovariance); Nan::SetMethod(target, "MarketModelTimeDependentVolatility", QuantLibNode::MarketModelTimeDependentVolatility); Nan::SetMethod(target, "CoterminalSwapForwardJacobian", QuantLibNode::CoterminalSwapForwardJacobian); Nan::SetMethod(target, "CoterminalSwapZedMatrix", QuantLibNode::CoterminalSwapZedMatrix); Nan::SetMethod(target, "CoinitialSwapForwardJacobian", QuantLibNode::CoinitialSwapForwardJacobian); Nan::SetMethod(target, "CoinitialSwapZedMatrix", QuantLibNode::CoinitialSwapZedMatrix); Nan::SetMethod(target, "CmSwapForwardJacobian", QuantLibNode::CmSwapForwardJacobian); Nan::SetMethod(target, "CmSwapZedMatrix", QuantLibNode::CmSwapZedMatrix); Nan::SetMethod(target, "Annuity", QuantLibNode::Annuity); Nan::SetMethod(target, "SwapDerivative", QuantLibNode::SwapDerivative); Nan::SetMethod(target, "RateVolDifferences", QuantLibNode::RateVolDifferences); Nan::SetMethod(target, "RateInstVolDifferences", QuantLibNode::RateInstVolDifferences); Nan::SetMethod(target, "SymmetricSchurDecomposition", QuantLibNode::SymmetricSchurDecomposition); Nan::SetMethod(target, "CovarianceDecomposition", QuantLibNode::CovarianceDecomposition); Nan::SetMethod(target, "SymmetricSchurDecompositionEigenvalues", QuantLibNode::SymmetricSchurDecompositionEigenvalues); Nan::SetMethod(target, "SymmetricSchurDecompositionEigenvectors", QuantLibNode::SymmetricSchurDecompositionEigenvectors); Nan::SetMethod(target, "CovarianceDecompositionVariances", QuantLibNode::CovarianceDecompositionVariances); Nan::SetMethod(target, "CovarianceDecompositionStandardDeviations", QuantLibNode::CovarianceDecompositionStandardDeviations); Nan::SetMethod(target, "CovarianceDecompositionCorrelationMatrix", QuantLibNode::CovarianceDecompositionCorrelationMatrix); Nan::SetMethod(target, "PrimeNumber", QuantLibNode::PrimeNumber); Nan::SetMethod(target, "NormDist", QuantLibNode::NormDist); Nan::SetMethod(target, "NormSDist", QuantLibNode::NormSDist); Nan::SetMethod(target, "NormInv", QuantLibNode::NormInv); Nan::SetMethod(target, "NormSInv", QuantLibNode::NormSInv); Nan::SetMethod(target, "CholeskyDecomposition", QuantLibNode::CholeskyDecomposition); Nan::SetMethod(target, "PseudoSqrt", QuantLibNode::PseudoSqrt); Nan::SetMethod(target, "RankReducedSqrt", QuantLibNode::RankReducedSqrt); Nan::SetMethod(target, "GetCovariance", QuantLibNode::GetCovariance); Nan::SetMethod(target, "EndCriteria", QuantLibNode::EndCriteria); Nan::SetMethod(target, "NoConstraint", QuantLibNode::NoConstraint); Nan::SetMethod(target, "Simplex", QuantLibNode::Simplex); Nan::SetMethod(target, "LevenbergMarquardt", QuantLibNode::LevenbergMarquardt); Nan::SetMethod(target, "ConjugateGradient", QuantLibNode::ConjugateGradient); Nan::SetMethod(target, "SteepestDescent", QuantLibNode::SteepestDescent); Nan::SetMethod(target, "ArmijoLineSearch", QuantLibNode::ArmijoLineSearch); Nan::SetMethod(target, "EndCriteriaMaxIterations", QuantLibNode::EndCriteriaMaxIterations); Nan::SetMethod(target, "EndCriteriaMaxStationaryStateIterations", QuantLibNode::EndCriteriaMaxStationaryStateIterations); Nan::SetMethod(target, "EndCriteriaFunctionEpsilon", QuantLibNode::EndCriteriaFunctionEpsilon); Nan::SetMethod(target, "EndCriteriaGradientNormEpsilon", QuantLibNode::EndCriteriaGradientNormEpsilon); Nan::SetMethod(target, "SphereCylinderOptimizerClosest", QuantLibNode::SphereCylinderOptimizerClosest); Nan::SetMethod(target, "SecondsToString", QuantLibNode::SecondsToString); Nan::SetMethod(target, "BarrierOption", QuantLibNode::BarrierOption); Nan::SetMethod(target, "CaAsianOption", QuantLibNode::CaAsianOption); Nan::SetMethod(target, "DaAsianOption", QuantLibNode::DaAsianOption); Nan::SetMethod(target, "DividendVanillaOption", QuantLibNode::DividendVanillaOption); Nan::SetMethod(target, "ForwardVanillaOption", QuantLibNode::ForwardVanillaOption); Nan::SetMethod(target, "VanillaOption", QuantLibNode::VanillaOption); Nan::SetMethod(target, "EuropeanOption", QuantLibNode::EuropeanOption); Nan::SetMethod(target, "QuantoVanillaOption", QuantLibNode::QuantoVanillaOption); Nan::SetMethod(target, "QuantoForwardVanillaOption", QuantLibNode::QuantoForwardVanillaOption); Nan::SetMethod(target, "Delta", QuantLibNode::Delta); Nan::SetMethod(target, "DeltaForward", QuantLibNode::DeltaForward); Nan::SetMethod(target, "Elasticity", QuantLibNode::Elasticity); Nan::SetMethod(target, "Gamma", QuantLibNode::Gamma); Nan::SetMethod(target, "Theta", QuantLibNode::Theta); Nan::SetMethod(target, "ThetaPerDay", QuantLibNode::ThetaPerDay); Nan::SetMethod(target, "Vega", QuantLibNode::Vega); Nan::SetMethod(target, "Rho", QuantLibNode::Rho); Nan::SetMethod(target, "DividendRho", QuantLibNode::DividendRho); Nan::SetMethod(target, "ItmCashProbability", QuantLibNode::ItmCashProbability); Nan::SetMethod(target, "OvernightIndexedSwap", QuantLibNode::OvernightIndexedSwap); Nan::SetMethod(target, "MakeOIS", QuantLibNode::MakeOIS); Nan::SetMethod(target, "MakeDatedOIS", QuantLibNode::MakeDatedOIS); Nan::SetMethod(target, "OvernightIndexedSwapFromOISRateHelper", QuantLibNode::OvernightIndexedSwapFromOISRateHelper); Nan::SetMethod(target, "OvernightIndexedSwapFixedLegBPS", QuantLibNode::OvernightIndexedSwapFixedLegBPS); Nan::SetMethod(target, "OvernightIndexedSwapFixedLegNPV", QuantLibNode::OvernightIndexedSwapFixedLegNPV); Nan::SetMethod(target, "OvernightIndexedSwapFairRate", QuantLibNode::OvernightIndexedSwapFairRate); Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegBPS", QuantLibNode::OvernightIndexedSwapOvernightLegBPS); Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegNPV", QuantLibNode::OvernightIndexedSwapOvernightLegNPV); Nan::SetMethod(target, "OvernightIndexedSwapFairSpread", QuantLibNode::OvernightIndexedSwapFairSpread); Nan::SetMethod(target, "OvernightIndexedSwapType", QuantLibNode::OvernightIndexedSwapType); Nan::SetMethod(target, "OvernightIndexedSwapNominal", QuantLibNode::OvernightIndexedSwapNominal); Nan::SetMethod(target, "OvernightIndexedSwapFixedRate", QuantLibNode::OvernightIndexedSwapFixedRate); Nan::SetMethod(target, "OvernightIndexedSwapFixedDayCount", QuantLibNode::OvernightIndexedSwapFixedDayCount); Nan::SetMethod(target, "OvernightIndexedSwapSpread", QuantLibNode::OvernightIndexedSwapSpread); Nan::SetMethod(target, "OvernightIndexedSwapFixedLegAnalysis", QuantLibNode::OvernightIndexedSwapFixedLegAnalysis); Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegAnalysis", QuantLibNode::OvernightIndexedSwapOvernightLegAnalysis); Nan::SetMethod(target, "StrikedTypePayoff", QuantLibNode::StrikedTypePayoff); Nan::SetMethod(target, "DoubleStickyRatchetPayoff", QuantLibNode::DoubleStickyRatchetPayoff); Nan::SetMethod(target, "RatchetPayoff", QuantLibNode::RatchetPayoff); Nan::SetMethod(target, "StickyPayoff", QuantLibNode::StickyPayoff); Nan::SetMethod(target, "RatchetMaxPayoff", QuantLibNode::RatchetMaxPayoff); Nan::SetMethod(target, "RatchetMinPayoff", QuantLibNode::RatchetMinPayoff); Nan::SetMethod(target, "StickyMaxPayoff", QuantLibNode::StickyMaxPayoff); Nan::SetMethod(target, "StickyMinPayoff", QuantLibNode::StickyMinPayoff); Nan::SetMethod(target, "PayoffName", QuantLibNode::PayoffName); Nan::SetMethod(target, "PayoffDescription", QuantLibNode::PayoffDescription); Nan::SetMethod(target, "PayoffValue", QuantLibNode::PayoffValue); Nan::SetMethod(target, "PayoffOptionType", QuantLibNode::PayoffOptionType); Nan::SetMethod(target, "PayoffStrike", QuantLibNode::PayoffStrike); Nan::SetMethod(target, "PayoffThirdParameter", QuantLibNode::PayoffThirdParameter); Nan::SetMethod(target, "PiecewiseYieldCurve", QuantLibNode::PiecewiseYieldCurve); Nan::SetMethod(target, "PiecewiseYieldCurveTimes", QuantLibNode::PiecewiseYieldCurveTimes); Nan::SetMethod(target, "PiecewiseYieldCurveDates", QuantLibNode::PiecewiseYieldCurveDates); Nan::SetMethod(target, "PiecewiseYieldCurveData", QuantLibNode::PiecewiseYieldCurveData); Nan::SetMethod(target, "PiecewiseYieldCurveJumpTimes", QuantLibNode::PiecewiseYieldCurveJumpTimes); Nan::SetMethod(target, "PiecewiseYieldCurveJumpDates", QuantLibNode::PiecewiseYieldCurveJumpDates); Nan::SetMethod(target, "MidEquivalent", QuantLibNode::MidEquivalent); Nan::SetMethod(target, "MidSafe", QuantLibNode::MidSafe); Nan::SetMethod(target, "BlackCalculator2", QuantLibNode::BlackCalculator2); Nan::SetMethod(target, "BlackCalculator", QuantLibNode::BlackCalculator); Nan::SetMethod(target, "BlackScholesCalculator2", QuantLibNode::BlackScholesCalculator2); Nan::SetMethod(target, "BlackScholesCalculator", QuantLibNode::BlackScholesCalculator); Nan::SetMethod(target, "PricingEngine", QuantLibNode::PricingEngine); Nan::SetMethod(target, "DiscountingSwapEngine", QuantLibNode::DiscountingSwapEngine); Nan::SetMethod(target, "BinomialPricingEngine", QuantLibNode::BinomialPricingEngine); Nan::SetMethod(target, "BlackSwaptionEngine", QuantLibNode::BlackSwaptionEngine); Nan::SetMethod(target, "BlackSwaptionEngine2", QuantLibNode::BlackSwaptionEngine2); Nan::SetMethod(target, "BlackCapFloorEngine", QuantLibNode::BlackCapFloorEngine); Nan::SetMethod(target, "BlackCapFloorEngine2", QuantLibNode::BlackCapFloorEngine2); Nan::SetMethod(target, "AnalyticCapFloorEngine", QuantLibNode::AnalyticCapFloorEngine); Nan::SetMethod(target, "BondEngine", QuantLibNode::BondEngine); Nan::SetMethod(target, "JamshidianSwaptionEngine", QuantLibNode::JamshidianSwaptionEngine); Nan::SetMethod(target, "TreeSwaptionEngine", QuantLibNode::TreeSwaptionEngine); Nan::SetMethod(target, "ModelG2SwaptionEngine", QuantLibNode::ModelG2SwaptionEngine); Nan::SetMethod(target, "BlackCalculatorValue", QuantLibNode::BlackCalculatorValue); Nan::SetMethod(target, "BlackCalculatorDeltaForward", QuantLibNode::BlackCalculatorDeltaForward); Nan::SetMethod(target, "BlackCalculatorDelta", QuantLibNode::BlackCalculatorDelta); Nan::SetMethod(target, "BlackCalculatorElasticityForward", QuantLibNode::BlackCalculatorElasticityForward); Nan::SetMethod(target, "BlackCalculatorElasticity", QuantLibNode::BlackCalculatorElasticity); Nan::SetMethod(target, "BlackCalculatorGammaForward", QuantLibNode::BlackCalculatorGammaForward); Nan::SetMethod(target, "BlackCalculatorGamma", QuantLibNode::BlackCalculatorGamma); Nan::SetMethod(target, "BlackCalculatorTheta", QuantLibNode::BlackCalculatorTheta); Nan::SetMethod(target, "BlackCalculatorThetaPerDay", QuantLibNode::BlackCalculatorThetaPerDay); Nan::SetMethod(target, "BlackCalculatorVega", QuantLibNode::BlackCalculatorVega); Nan::SetMethod(target, "BlackCalculatorRho", QuantLibNode::BlackCalculatorRho); Nan::SetMethod(target, "BlackCalculatorDividendRho", QuantLibNode::BlackCalculatorDividendRho); Nan::SetMethod(target, "BlackCalculatorItmCashProbability", QuantLibNode::BlackCalculatorItmCashProbability); Nan::SetMethod(target, "BlackCalculatorItmAssetProbability", QuantLibNode::BlackCalculatorItmAssetProbability); Nan::SetMethod(target, "BlackCalculatorStrikeSensitivity", QuantLibNode::BlackCalculatorStrikeSensitivity); Nan::SetMethod(target, "BlackCalculatorAlpha", QuantLibNode::BlackCalculatorAlpha); Nan::SetMethod(target, "BlackCalculatorBeta", QuantLibNode::BlackCalculatorBeta); Nan::SetMethod(target, "BlackScholesCalculatorDelta", QuantLibNode::BlackScholesCalculatorDelta); Nan::SetMethod(target, "BlackScholesCalculatorElasticity", QuantLibNode::BlackScholesCalculatorElasticity); Nan::SetMethod(target, "BlackScholesCalculatorGamma", QuantLibNode::BlackScholesCalculatorGamma); Nan::SetMethod(target, "BlackScholesCalculatorTheta", QuantLibNode::BlackScholesCalculatorTheta); Nan::SetMethod(target, "BlackScholesCalculatorThetaPerDay", QuantLibNode::BlackScholesCalculatorThetaPerDay); Nan::SetMethod(target, "BlackFormula", QuantLibNode::BlackFormula); Nan::SetMethod(target, "BlackFormulaCashItmProbability", QuantLibNode::BlackFormulaCashItmProbability); Nan::SetMethod(target, "BlackFormulaImpliedStdDevApproximation", QuantLibNode::BlackFormulaImpliedStdDevApproximation); Nan::SetMethod(target, "BlackFormulaImpliedStdDev", QuantLibNode::BlackFormulaImpliedStdDev); Nan::SetMethod(target, "BlackFormulaStdDevDerivative", QuantLibNode::BlackFormulaStdDevDerivative); Nan::SetMethod(target, "BachelierBlackFormula", QuantLibNode::BachelierBlackFormula); Nan::SetMethod(target, "BlackFormula2", QuantLibNode::BlackFormula2); Nan::SetMethod(target, "BlackFormulaCashItmProbability2", QuantLibNode::BlackFormulaCashItmProbability2); Nan::SetMethod(target, "BlackFormulaImpliedStdDevApproximation2", QuantLibNode::BlackFormulaImpliedStdDevApproximation2); Nan::SetMethod(target, "BlackFormulaImpliedStdDev2", QuantLibNode::BlackFormulaImpliedStdDev2); Nan::SetMethod(target, "BlackFormulaStdDevDerivative2", QuantLibNode::BlackFormulaStdDevDerivative2); Nan::SetMethod(target, "BachelierBlackFormula2", QuantLibNode::BachelierBlackFormula2); Nan::SetMethod(target, "GeneralizedBlackScholesProcess", QuantLibNode::GeneralizedBlackScholesProcess); Nan::SetMethod(target, "MarketModelMultiProductComposite", QuantLibNode::MarketModelMultiProductComposite); Nan::SetMethod(target, "MarketModelOneStepForwards", QuantLibNode::MarketModelOneStepForwards); Nan::SetMethod(target, "MarketModelMultiStepRatchet", QuantLibNode::MarketModelMultiStepRatchet); Nan::SetMethod(target, "MarketModelOneStepOptionlets", QuantLibNode::MarketModelOneStepOptionlets); Nan::SetMethod(target, "MarketModelMultiProductCompositeAdd", QuantLibNode::MarketModelMultiProductCompositeAdd); Nan::SetMethod(target, "MarketModelMultiProductCompositeFinalize", QuantLibNode::MarketModelMultiProductCompositeFinalize); Nan::SetMethod(target, "MarketModelMultiProductSuggestedNumeraires", QuantLibNode::MarketModelMultiProductSuggestedNumeraires); Nan::SetMethod(target, "MarketModelMultiProductPossibleCashFlowTimes", QuantLibNode::MarketModelMultiProductPossibleCashFlowTimes); Nan::SetMethod(target, "MarketModelMultiProductNumberOfProducts", QuantLibNode::MarketModelMultiProductNumberOfProducts); Nan::SetMethod(target, "MarketModelMultiProductMaxNumberOfCashFlowsPerProductPerStep", QuantLibNode::MarketModelMultiProductMaxNumberOfCashFlowsPerProductPerStep); Nan::SetMethod(target, "SimpleQuote", QuantLibNode::SimpleQuote); Nan::SetMethod(target, "ForwardValueQuote", QuantLibNode::ForwardValueQuote); Nan::SetMethod(target, "ForwardSwapQuote", QuantLibNode::ForwardSwapQuote); Nan::SetMethod(target, "ImpliedStdDevQuote", QuantLibNode::ImpliedStdDevQuote); Nan::SetMethod(target, "EurodollarFuturesImpliedStdDevQuote", QuantLibNode::EurodollarFuturesImpliedStdDevQuote); Nan::SetMethod(target, "CompositeQuote", QuantLibNode::CompositeQuote); Nan::SetMethod(target, "FuturesConvAdjustmentQuote", QuantLibNode::FuturesConvAdjustmentQuote); Nan::SetMethod(target, "LastFixingQuote", QuantLibNode::LastFixingQuote); Nan::SetMethod(target, "RelinkableHandleQuote", QuantLibNode::RelinkableHandleQuote); Nan::SetMethod(target, "QuoteValue", QuantLibNode::QuoteValue); Nan::SetMethod(target, "QuoteIsValid", QuantLibNode::QuoteIsValid); Nan::SetMethod(target, "SimpleQuoteReset", QuantLibNode::SimpleQuoteReset); Nan::SetMethod(target, "SimpleQuoteSetValue", QuantLibNode::SimpleQuoteSetValue); Nan::SetMethod(target, "SimpleQuoteSetTickValue", QuantLibNode::SimpleQuoteSetTickValue); Nan::SetMethod(target, "SimpleQuoteTickValue", QuantLibNode::SimpleQuoteTickValue); Nan::SetMethod(target, "FuturesConvAdjustmentQuoteVolatility", QuantLibNode::FuturesConvAdjustmentQuoteVolatility); Nan::SetMethod(target, "FuturesConvAdjustmentQuoteMeanReversion", QuantLibNode::FuturesConvAdjustmentQuoteMeanReversion); Nan::SetMethod(target, "FuturesConvAdjustmentQuoteImmDate", QuantLibNode::FuturesConvAdjustmentQuoteImmDate); Nan::SetMethod(target, "FuturesConvAdjustmentQuoteFuturesValue", QuantLibNode::FuturesConvAdjustmentQuoteFuturesValue); Nan::SetMethod(target, "LastFixingQuoteReferenceDate", QuantLibNode::LastFixingQuoteReferenceDate); Nan::SetMethod(target, "BucketAnalysis", QuantLibNode::BucketAnalysis); Nan::SetMethod(target, "BucketAnalysisDelta", QuantLibNode::BucketAnalysisDelta); Nan::SetMethod(target, "BucketAnalysisDelta2", QuantLibNode::BucketAnalysisDelta2); Nan::SetMethod(target, "MersenneTwisterRsg", QuantLibNode::MersenneTwisterRsg); Nan::SetMethod(target, "FaureRsg", QuantLibNode::FaureRsg); Nan::SetMethod(target, "HaltonRsg", QuantLibNode::HaltonRsg); Nan::SetMethod(target, "SobolRsg", QuantLibNode::SobolRsg); Nan::SetMethod(target, "Variates", QuantLibNode::Variates); Nan::SetMethod(target, "Rand", QuantLibNode::Rand); Nan::SetMethod(target, "Randomize", QuantLibNode::Randomize); Nan::SetMethod(target, "RangeAccrualFloatersCoupon", QuantLibNode::RangeAccrualFloatersCoupon); Nan::SetMethod(target, "RangeAccrualFloatersCouponFromLeg", QuantLibNode::RangeAccrualFloatersCouponFromLeg); Nan::SetMethod(target, "RangeAccrualPricerByBgm", QuantLibNode::RangeAccrualPricerByBgm); Nan::SetMethod(target, "RangeAccrualFloatersCouponSetPricer", QuantLibNode::RangeAccrualFloatersCouponSetPricer); Nan::SetMethod(target, "RangeAccrualFloatersCouponObservationDates", QuantLibNode::RangeAccrualFloatersCouponObservationDates); Nan::SetMethod(target, "RangeAccrualFloatersCouponStarDate", QuantLibNode::RangeAccrualFloatersCouponStarDate); Nan::SetMethod(target, "RangeAccrualFloatersCouponEndDate", QuantLibNode::RangeAccrualFloatersCouponEndDate); Nan::SetMethod(target, "RangeAccrualFloatersCouponObservationsNo", QuantLibNode::RangeAccrualFloatersCouponObservationsNo); Nan::SetMethod(target, "RangeAccrualFloatersPrice", QuantLibNode::RangeAccrualFloatersPrice); Nan::SetMethod(target, "SimpleFloaterPrice", QuantLibNode::SimpleFloaterPrice); Nan::SetMethod(target, "DepositRateHelper", QuantLibNode::DepositRateHelper); Nan::SetMethod(target, "DepositRateHelper2", QuantLibNode::DepositRateHelper2); Nan::SetMethod(target, "SwapRateHelper", QuantLibNode::SwapRateHelper); Nan::SetMethod(target, "SwapRateHelper2", QuantLibNode::SwapRateHelper2); Nan::SetMethod(target, "OISRateHelper", QuantLibNode::OISRateHelper); Nan::SetMethod(target, "DatedOISRateHelper", QuantLibNode::DatedOISRateHelper); Nan::SetMethod(target, "FraRateHelper", QuantLibNode::FraRateHelper); Nan::SetMethod(target, "FraRateHelper2", QuantLibNode::FraRateHelper2); Nan::SetMethod(target, "BondHelper", QuantLibNode::BondHelper); Nan::SetMethod(target, "FixedRateBondHelper", QuantLibNode::FixedRateBondHelper); Nan::SetMethod(target, "FuturesRateHelper", QuantLibNode::FuturesRateHelper); Nan::SetMethod(target, "FuturesRateHelper2", QuantLibNode::FuturesRateHelper2); Nan::SetMethod(target, "FuturesRateHelper3", QuantLibNode::FuturesRateHelper3); Nan::SetMethod(target, "FxSwapRateHelper", QuantLibNode::FxSwapRateHelper); Nan::SetMethod(target, "RateHelperEarliestDate", QuantLibNode::RateHelperEarliestDate); Nan::SetMethod(target, "RateHelperLatestRelevantDate", QuantLibNode::RateHelperLatestRelevantDate); Nan::SetMethod(target, "RateHelperPillarDate", QuantLibNode::RateHelperPillarDate); Nan::SetMethod(target, "RateHelperMaturityDate", QuantLibNode::RateHelperMaturityDate); Nan::SetMethod(target, "RateHelperQuoteName", QuantLibNode::RateHelperQuoteName); Nan::SetMethod(target, "RateHelperQuoteValue", QuantLibNode::RateHelperQuoteValue); Nan::SetMethod(target, "RateHelperQuoteIsValid", QuantLibNode::RateHelperQuoteIsValid); Nan::SetMethod(target, "RateHelperImpliedQuote", QuantLibNode::RateHelperImpliedQuote); Nan::SetMethod(target, "RateHelperQuoteError", QuantLibNode::RateHelperQuoteError); Nan::SetMethod(target, "SwapRateHelperSpread", QuantLibNode::SwapRateHelperSpread); Nan::SetMethod(target, "SwapRateHelperForwardStart", QuantLibNode::SwapRateHelperForwardStart); Nan::SetMethod(target, "FuturesRateHelperConvexityAdjustment", QuantLibNode::FuturesRateHelperConvexityAdjustment); Nan::SetMethod(target, "FxSwapRateHelperSpotValue", QuantLibNode::FxSwapRateHelperSpotValue); Nan::SetMethod(target, "FxSwapRateHelperTenor", QuantLibNode::FxSwapRateHelperTenor); Nan::SetMethod(target, "FxSwapRateHelperFixingDays", QuantLibNode::FxSwapRateHelperFixingDays); Nan::SetMethod(target, "FxSwapRateHelperCalendar", QuantLibNode::FxSwapRateHelperCalendar); Nan::SetMethod(target, "FxSwapRateHelperBDC", QuantLibNode::FxSwapRateHelperBDC); Nan::SetMethod(target, "FxSwapRateHelperEOM", QuantLibNode::FxSwapRateHelperEOM); Nan::SetMethod(target, "FxSwapRateHelperIsBaseCurrencyCollateralCurrency", QuantLibNode::FxSwapRateHelperIsBaseCurrencyCollateralCurrency); Nan::SetMethod(target, "RateHelperSelection", QuantLibNode::RateHelperSelection); Nan::SetMethod(target, "RateHelperRate", QuantLibNode::RateHelperRate); Nan::SetMethod(target, "Schedule", QuantLibNode::Schedule); Nan::SetMethod(target, "ScheduleFromDateVector", QuantLibNode::ScheduleFromDateVector); Nan::SetMethod(target, "ScheduleTruncated", QuantLibNode::ScheduleTruncated); Nan::SetMethod(target, "ScheduleSize", QuantLibNode::ScheduleSize); Nan::SetMethod(target, "SchedulePreviousDate", QuantLibNode::SchedulePreviousDate); Nan::SetMethod(target, "ScheduleNextDate", QuantLibNode::ScheduleNextDate); Nan::SetMethod(target, "ScheduleDates", QuantLibNode::ScheduleDates); Nan::SetMethod(target, "ScheduleIsRegular", QuantLibNode::ScheduleIsRegular); Nan::SetMethod(target, "ScheduleEmpty", QuantLibNode::ScheduleEmpty); Nan::SetMethod(target, "ScheduleCalendar", QuantLibNode::ScheduleCalendar); Nan::SetMethod(target, "ScheduleStartDate", QuantLibNode::ScheduleStartDate); Nan::SetMethod(target, "ScheduleEndDate", QuantLibNode::ScheduleEndDate); Nan::SetMethod(target, "ScheduleTenor", QuantLibNode::ScheduleTenor); Nan::SetMethod(target, "ScheduleBDC", QuantLibNode::ScheduleBDC); Nan::SetMethod(target, "ScheduleTerminationDateBDC", QuantLibNode::ScheduleTerminationDateBDC); Nan::SetMethod(target, "ScheduleRule", QuantLibNode::ScheduleRule); Nan::SetMethod(target, "ScheduleEndOfMonth", QuantLibNode::ScheduleEndOfMonth); Nan::SetMethod(target, "SequenceStatistics", QuantLibNode::SequenceStatistics); Nan::SetMethod(target, "SequenceStatistics2", QuantLibNode::SequenceStatistics2); Nan::SetMethod(target, "SequenceStatisticsInc", QuantLibNode::SequenceStatisticsInc); Nan::SetMethod(target, "SequenceStatisticsInc2", QuantLibNode::SequenceStatisticsInc2); Nan::SetMethod(target, "SequenceStatisticsSamples", QuantLibNode::SequenceStatisticsSamples); Nan::SetMethod(target, "SequenceStatisticsWeightSum", QuantLibNode::SequenceStatisticsWeightSum); Nan::SetMethod(target, "SequenceStatisticsMean", QuantLibNode::SequenceStatisticsMean); Nan::SetMethod(target, "SequenceStatisticsVariance", QuantLibNode::SequenceStatisticsVariance); Nan::SetMethod(target, "SequenceStatisticsStandardDeviation", QuantLibNode::SequenceStatisticsStandardDeviation); Nan::SetMethod(target, "SequenceStatisticsDownsideVariance", QuantLibNode::SequenceStatisticsDownsideVariance); Nan::SetMethod(target, "SequenceStatisticsDownsideDeviation", QuantLibNode::SequenceStatisticsDownsideDeviation); Nan::SetMethod(target, "SequenceStatisticsSemiVariance", QuantLibNode::SequenceStatisticsSemiVariance); Nan::SetMethod(target, "SequenceStatisticsSemiDeviation", QuantLibNode::SequenceStatisticsSemiDeviation); Nan::SetMethod(target, "SequenceStatisticsErrorEstimate", QuantLibNode::SequenceStatisticsErrorEstimate); Nan::SetMethod(target, "SequenceStatisticsSkewness", QuantLibNode::SequenceStatisticsSkewness); Nan::SetMethod(target, "SequenceStatisticsKurtosis", QuantLibNode::SequenceStatisticsKurtosis); Nan::SetMethod(target, "SequenceStatisticsMin", QuantLibNode::SequenceStatisticsMin); Nan::SetMethod(target, "SequenceStatisticsMax", QuantLibNode::SequenceStatisticsMax); Nan::SetMethod(target, "SequenceStatisticsGaussianPercentile", QuantLibNode::SequenceStatisticsGaussianPercentile); Nan::SetMethod(target, "SequenceStatisticsPercentile", QuantLibNode::SequenceStatisticsPercentile); Nan::SetMethod(target, "SequenceStatisticsGaussianPotentialUpside", QuantLibNode::SequenceStatisticsGaussianPotentialUpside); Nan::SetMethod(target, "SequenceStatisticsPotentialUpside", QuantLibNode::SequenceStatisticsPotentialUpside); Nan::SetMethod(target, "SequenceStatisticsGaussianValueAtRisk", QuantLibNode::SequenceStatisticsGaussianValueAtRisk); Nan::SetMethod(target, "SequenceStatisticsValueAtRisk", QuantLibNode::SequenceStatisticsValueAtRisk); Nan::SetMethod(target, "SequenceStatisticsRegret", QuantLibNode::SequenceStatisticsRegret); Nan::SetMethod(target, "SequenceStatisticsGaussianShortfall", QuantLibNode::SequenceStatisticsGaussianShortfall); Nan::SetMethod(target, "SequenceStatisticsShortfall", QuantLibNode::SequenceStatisticsShortfall); Nan::SetMethod(target, "SequenceStatisticsGaussianAverageShortfall", QuantLibNode::SequenceStatisticsGaussianAverageShortfall); Nan::SetMethod(target, "SequenceStatisticsAverageShortfall", QuantLibNode::SequenceStatisticsAverageShortfall); Nan::SetMethod(target, "SequenceStatisticsSize", QuantLibNode::SequenceStatisticsSize); Nan::SetMethod(target, "SequenceStatisticsCovariance", QuantLibNode::SequenceStatisticsCovariance); Nan::SetMethod(target, "SequenceStatisticsCorrelation", QuantLibNode::SequenceStatisticsCorrelation); Nan::SetMethod(target, "SettingsEvaluationDate", QuantLibNode::SettingsEvaluationDate); Nan::SetMethod(target, "SettingsSetEvaluationDate", QuantLibNode::SettingsSetEvaluationDate); Nan::SetMethod(target, "SettingsEnforceTodaysHistoricFixings", QuantLibNode::SettingsEnforceTodaysHistoricFixings); Nan::SetMethod(target, "SettingsSetEnforceTodaysHistoricFixings", QuantLibNode::SettingsSetEnforceTodaysHistoricFixings); Nan::SetMethod(target, "HullWhite", QuantLibNode::HullWhite); Nan::SetMethod(target, "Vasicek", QuantLibNode::Vasicek); Nan::SetMethod(target, "ModelG2", QuantLibNode::ModelG2); Nan::SetMethod(target, "VasicekA", QuantLibNode::VasicekA); Nan::SetMethod(target, "VasicekB", QuantLibNode::VasicekB); Nan::SetMethod(target, "VasicekLambda", QuantLibNode::VasicekLambda); Nan::SetMethod(target, "VasicekSigma", QuantLibNode::VasicekSigma); Nan::SetMethod(target, "ModelG2A", QuantLibNode::ModelG2A); Nan::SetMethod(target, "ModelG2sigma", QuantLibNode::ModelG2sigma); Nan::SetMethod(target, "ModelG2B", QuantLibNode::ModelG2B); Nan::SetMethod(target, "ModelG2eta", QuantLibNode::ModelG2eta); Nan::SetMethod(target, "ModelG2rho", QuantLibNode::ModelG2rho); Nan::SetMethod(target, "FuturesConvexityBias", QuantLibNode::FuturesConvexityBias); Nan::SetMethod(target, "FlatSmileSection", QuantLibNode::FlatSmileSection); Nan::SetMethod(target, "SabrInterpolatedSmileSection", QuantLibNode::SabrInterpolatedSmileSection); Nan::SetMethod(target, "SabrInterpolatedSmileSection1", QuantLibNode::SabrInterpolatedSmileSection1); Nan::SetMethod(target, "SabrSmileSection", QuantLibNode::SabrSmileSection); Nan::SetMethod(target, "InterpolatedSmileSection", QuantLibNode::InterpolatedSmileSection); Nan::SetMethod(target, "SmileSectionFromSabrVolSurface", QuantLibNode::SmileSectionFromSabrVolSurface); Nan::SetMethod(target, "SmileSectionVolatility", QuantLibNode::SmileSectionVolatility); Nan::SetMethod(target, "SmileSectionVariance", QuantLibNode::SmileSectionVariance); Nan::SetMethod(target, "SmileSectionAtmLevel", QuantLibNode::SmileSectionAtmLevel); Nan::SetMethod(target, "SmileSectionExerciseDate", QuantLibNode::SmileSectionExerciseDate); Nan::SetMethod(target, "SmileSectionDayCounter", QuantLibNode::SmileSectionDayCounter); Nan::SetMethod(target, "SabrInterpolatedSmileSectionAlpha", QuantLibNode::SabrInterpolatedSmileSectionAlpha); Nan::SetMethod(target, "SabrInterpolatedSmileSectionBeta", QuantLibNode::SabrInterpolatedSmileSectionBeta); Nan::SetMethod(target, "SabrInterpolatedSmileSectionNu", QuantLibNode::SabrInterpolatedSmileSectionNu); Nan::SetMethod(target, "SabrInterpolatedSmileSectionRho", QuantLibNode::SabrInterpolatedSmileSectionRho); Nan::SetMethod(target, "SabrInterpolatedSmileSectionError", QuantLibNode::SabrInterpolatedSmileSectionError); Nan::SetMethod(target, "SabrInterpolatedSmileSectionMaxError", QuantLibNode::SabrInterpolatedSmileSectionMaxError); Nan::SetMethod(target, "SabrInterpolatedSmileSectionEndCriteria", QuantLibNode::SabrInterpolatedSmileSectionEndCriteria); Nan::SetMethod(target, "Statistics", QuantLibNode::Statistics); Nan::SetMethod(target, "IncrementalStatistics", QuantLibNode::IncrementalStatistics); Nan::SetMethod(target, "StatisticsSamples", QuantLibNode::StatisticsSamples); Nan::SetMethod(target, "StatisticsWeightSum", QuantLibNode::StatisticsWeightSum); Nan::SetMethod(target, "StatisticsMean", QuantLibNode::StatisticsMean); Nan::SetMethod(target, "StatisticsVariance", QuantLibNode::StatisticsVariance); Nan::SetMethod(target, "StatisticsStandardDeviation", QuantLibNode::StatisticsStandardDeviation); Nan::SetMethod(target, "StatisticsErrorEstimate", QuantLibNode::StatisticsErrorEstimate); Nan::SetMethod(target, "StatisticsSkewness", QuantLibNode::StatisticsSkewness); Nan::SetMethod(target, "StatisticsKurtosis", QuantLibNode::StatisticsKurtosis); Nan::SetMethod(target, "StatisticsMin", QuantLibNode::StatisticsMin); Nan::SetMethod(target, "StatisticsMax", QuantLibNode::StatisticsMax); Nan::SetMethod(target, "StatisticsPercentile", QuantLibNode::StatisticsPercentile); Nan::SetMethod(target, "StatisticsTopPercentile", QuantLibNode::StatisticsTopPercentile); Nan::SetMethod(target, "StatisticsGaussianDownsideVariance", QuantLibNode::StatisticsGaussianDownsideVariance); Nan::SetMethod(target, "StatisticsGaussianDownsideDeviation", QuantLibNode::StatisticsGaussianDownsideDeviation); Nan::SetMethod(target, "StatisticsGaussianRegret", QuantLibNode::StatisticsGaussianRegret); Nan::SetMethod(target, "StatisticsGaussianPercentile", QuantLibNode::StatisticsGaussianPercentile); Nan::SetMethod(target, "StatisticsGaussianTopPercentile", QuantLibNode::StatisticsGaussianTopPercentile); Nan::SetMethod(target, "StatisticsGaussianPotentialUpside", QuantLibNode::StatisticsGaussianPotentialUpside); Nan::SetMethod(target, "StatisticsGaussianValueAtRisk", QuantLibNode::StatisticsGaussianValueAtRisk); Nan::SetMethod(target, "StatisticsGaussianExpectedShortfall", QuantLibNode::StatisticsGaussianExpectedShortfall); Nan::SetMethod(target, "StatisticsGaussianShortfall", QuantLibNode::StatisticsGaussianShortfall); Nan::SetMethod(target, "StatisticsGaussianAverageShortfall", QuantLibNode::StatisticsGaussianAverageShortfall); Nan::SetMethod(target, "StatisticsSemiVariance", QuantLibNode::StatisticsSemiVariance); Nan::SetMethod(target, "StatisticsSemiDeviation", QuantLibNode::StatisticsSemiDeviation); Nan::SetMethod(target, "StatisticsDownsideVariance", QuantLibNode::StatisticsDownsideVariance); Nan::SetMethod(target, "StatisticsDownsideDeviation", QuantLibNode::StatisticsDownsideDeviation); Nan::SetMethod(target, "StatisticsRegret", QuantLibNode::StatisticsRegret); Nan::SetMethod(target, "StatisticsPotentialUpside", QuantLibNode::StatisticsPotentialUpside); Nan::SetMethod(target, "StatisticsValueAtRisk", QuantLibNode::StatisticsValueAtRisk); Nan::SetMethod(target, "StatisticsExpectedShortfall", QuantLibNode::StatisticsExpectedShortfall); Nan::SetMethod(target, "StatisticsShortfall", QuantLibNode::StatisticsShortfall); Nan::SetMethod(target, "StatisticsAverageShortfall", QuantLibNode::StatisticsAverageShortfall); Nan::SetMethod(target, "GaussianDownsideVariance", QuantLibNode::GaussianDownsideVariance); Nan::SetMethod(target, "GaussianDownsideDeviation", QuantLibNode::GaussianDownsideDeviation); Nan::SetMethod(target, "GaussianRegret", QuantLibNode::GaussianRegret); Nan::SetMethod(target, "GaussianPercentile", QuantLibNode::GaussianPercentile); Nan::SetMethod(target, "GaussianTopPercentile", QuantLibNode::GaussianTopPercentile); Nan::SetMethod(target, "GaussianPotentialUpside", QuantLibNode::GaussianPotentialUpside); Nan::SetMethod(target, "GaussianValueAtRisk", QuantLibNode::GaussianValueAtRisk); Nan::SetMethod(target, "GaussianExpectedShortfall", QuantLibNode::GaussianExpectedShortfall); Nan::SetMethod(target, "GaussianShortfall", QuantLibNode::GaussianShortfall); Nan::SetMethod(target, "GaussianAverageShortfall", QuantLibNode::GaussianAverageShortfall); Nan::SetMethod(target, "Swap", QuantLibNode::Swap); Nan::SetMethod(target, "MakeCms", QuantLibNode::MakeCms); Nan::SetMethod(target, "SwapLegBPS", QuantLibNode::SwapLegBPS); Nan::SetMethod(target, "SwapLegNPV", QuantLibNode::SwapLegNPV); Nan::SetMethod(target, "SwapStartDate", QuantLibNode::SwapStartDate); Nan::SetMethod(target, "SwapMaturityDate", QuantLibNode::SwapMaturityDate); Nan::SetMethod(target, "SwapLegAnalysis", QuantLibNode::SwapLegAnalysis); Nan::SetMethod(target, "Swaption", QuantLibNode::Swaption); Nan::SetMethod(target, "MakeSwaption", QuantLibNode::MakeSwaption); Nan::SetMethod(target, "SwaptionType", QuantLibNode::SwaptionType); Nan::SetMethod(target, "SwaptionSettlementType", QuantLibNode::SwaptionSettlementType); Nan::SetMethod(target, "SwaptionImpliedVolatility", QuantLibNode::SwaptionImpliedVolatility); Nan::SetMethod(target, "RelinkableHandleSwaptionVolatilityStructure", QuantLibNode::RelinkableHandleSwaptionVolatilityStructure); Nan::SetMethod(target, "ConstantSwaptionVolatility", QuantLibNode::ConstantSwaptionVolatility); Nan::SetMethod(target, "SpreadedSwaptionVolatility", QuantLibNode::SpreadedSwaptionVolatility); Nan::SetMethod(target, "SwaptionVTSMatrix", QuantLibNode::SwaptionVTSMatrix); Nan::SetMethod(target, "SwaptionVolCube2", QuantLibNode::SwaptionVolCube2); Nan::SetMethod(target, "SwaptionVolCube1", QuantLibNode::SwaptionVolCube1); Nan::SetMethod(target, "SmileSectionByCube", QuantLibNode::SmileSectionByCube); Nan::SetMethod(target, "SmileSectionByCube2", QuantLibNode::SmileSectionByCube2); Nan::SetMethod(target, "SwaptionVTSVolatility", QuantLibNode::SwaptionVTSVolatility); Nan::SetMethod(target, "SwaptionVTSVolatility2", QuantLibNode::SwaptionVTSVolatility2); Nan::SetMethod(target, "SwaptionVTSBlackVariance", QuantLibNode::SwaptionVTSBlackVariance); Nan::SetMethod(target, "SwaptionVTSBlackVariance2", QuantLibNode::SwaptionVTSBlackVariance2); Nan::SetMethod(target, "SwaptionVTSMaxSwapTenor", QuantLibNode::SwaptionVTSMaxSwapTenor); Nan::SetMethod(target, "SwaptionVTSBusinessDayConvention", QuantLibNode::SwaptionVTSBusinessDayConvention); Nan::SetMethod(target, "SwaptionVTSOptionDateFromTenor", QuantLibNode::SwaptionVTSOptionDateFromTenor); Nan::SetMethod(target, "SwaptionVTSSwapLength", QuantLibNode::SwaptionVTSSwapLength); Nan::SetMethod(target, "SwaptionVTSSwapLength2", QuantLibNode::SwaptionVTSSwapLength2); Nan::SetMethod(target, "SwaptionVTSMatrixOptionDates", QuantLibNode::SwaptionVTSMatrixOptionDates); Nan::SetMethod(target, "SwaptionVTSMatrixOptionTenors", QuantLibNode::SwaptionVTSMatrixOptionTenors); Nan::SetMethod(target, "SwaptionVTSMatrixSwapTenors", QuantLibNode::SwaptionVTSMatrixSwapTenors); Nan::SetMethod(target, "SwaptionVTSMatrixLocate", QuantLibNode::SwaptionVTSMatrixLocate); Nan::SetMethod(target, "SwaptionVTSatmStrike", QuantLibNode::SwaptionVTSatmStrike); Nan::SetMethod(target, "SwaptionVTSatmStrike2", QuantLibNode::SwaptionVTSatmStrike2); Nan::SetMethod(target, "SparseSabrParameters", QuantLibNode::SparseSabrParameters); Nan::SetMethod(target, "DenseSabrParameters", QuantLibNode::DenseSabrParameters); Nan::SetMethod(target, "MarketVolCube", QuantLibNode::MarketVolCube); Nan::SetMethod(target, "VolCubeAtmCalibrated", QuantLibNode::VolCubeAtmCalibrated); Nan::SetMethod(target, "RelinkableHandleYieldTermStructure", QuantLibNode::RelinkableHandleYieldTermStructure); Nan::SetMethod(target, "DiscountCurve", QuantLibNode::DiscountCurve); Nan::SetMethod(target, "ZeroCurve", QuantLibNode::ZeroCurve); Nan::SetMethod(target, "ForwardCurve", QuantLibNode::ForwardCurve); Nan::SetMethod(target, "FlatForward", QuantLibNode::FlatForward); Nan::SetMethod(target, "ForwardSpreadedTermStructure", QuantLibNode::ForwardSpreadedTermStructure); Nan::SetMethod(target, "ImpliedTermStructure", QuantLibNode::ImpliedTermStructure); Nan::SetMethod(target, "InterpolatedYieldCurve", QuantLibNode::InterpolatedYieldCurve); Nan::SetMethod(target, "TermStructureDayCounter", QuantLibNode::TermStructureDayCounter); Nan::SetMethod(target, "TermStructureMaxDate", QuantLibNode::TermStructureMaxDate); Nan::SetMethod(target, "TermStructureReferenceDate", QuantLibNode::TermStructureReferenceDate); Nan::SetMethod(target, "TermStructureTimeFromReference", QuantLibNode::TermStructureTimeFromReference); Nan::SetMethod(target, "TermStructureCalendar", QuantLibNode::TermStructureCalendar); Nan::SetMethod(target, "TermStructureSettlementDays", QuantLibNode::TermStructureSettlementDays); Nan::SetMethod(target, "YieldTSDiscount", QuantLibNode::YieldTSDiscount); Nan::SetMethod(target, "YieldTSForwardRate", QuantLibNode::YieldTSForwardRate); Nan::SetMethod(target, "YieldTSForwardRate2", QuantLibNode::YieldTSForwardRate2); Nan::SetMethod(target, "YieldTSZeroRate", QuantLibNode::YieldTSZeroRate); Nan::SetMethod(target, "InterpolatedYieldCurveTimes", QuantLibNode::InterpolatedYieldCurveTimes); Nan::SetMethod(target, "InterpolatedYieldCurveDates", QuantLibNode::InterpolatedYieldCurveDates); Nan::SetMethod(target, "InterpolatedYieldCurveData", QuantLibNode::InterpolatedYieldCurveData); Nan::SetMethod(target, "InterpolatedYieldCurveJumpTimes", QuantLibNode::InterpolatedYieldCurveJumpTimes); Nan::SetMethod(target, "InterpolatedYieldCurveJumpDates", QuantLibNode::InterpolatedYieldCurveJumpDates); Nan::SetMethod(target, "TimeSeries", QuantLibNode::TimeSeries); Nan::SetMethod(target, "TimeSeriesFromIndex", QuantLibNode::TimeSeriesFromIndex); Nan::SetMethod(target, "TimeSeriesFirstDate", QuantLibNode::TimeSeriesFirstDate); Nan::SetMethod(target, "TimeSeriesLastDate", QuantLibNode::TimeSeriesLastDate); Nan::SetMethod(target, "TimeSeriesSize", QuantLibNode::TimeSeriesSize); Nan::SetMethod(target, "TimeSeriesEmpty", QuantLibNode::TimeSeriesEmpty); Nan::SetMethod(target, "TimeSeriesDates", QuantLibNode::TimeSeriesDates); Nan::SetMethod(target, "TimeSeriesValues", QuantLibNode::TimeSeriesValues); Nan::SetMethod(target, "TimeSeriesValue", QuantLibNode::TimeSeriesValue); Nan::SetMethod(target, "xlVersion", QuantLibNode::xlVersion); Nan::SetMethod(target, "AddinVersion", QuantLibNode::AddinVersion); Nan::SetMethod(target, "Version", QuantLibNode::Version); Nan::SetMethod(target, "FunctionCount", QuantLibNode::FunctionCount); Nan::SetMethod(target, "VanillaSwap", QuantLibNode::VanillaSwap); Nan::SetMethod(target, "MakeVanillaSwap", QuantLibNode::MakeVanillaSwap); Nan::SetMethod(target, "MakeIMMSwap", QuantLibNode::MakeIMMSwap); Nan::SetMethod(target, "VanillaSwapFromSwapIndex", QuantLibNode::VanillaSwapFromSwapIndex); Nan::SetMethod(target, "VanillaSwapFromSwapRateHelper", QuantLibNode::VanillaSwapFromSwapRateHelper); Nan::SetMethod(target, "VanillaSwapFixedLegBPS", QuantLibNode::VanillaSwapFixedLegBPS); Nan::SetMethod(target, "VanillaSwapFixedLegNPV", QuantLibNode::VanillaSwapFixedLegNPV); Nan::SetMethod(target, "VanillaSwapFairRate", QuantLibNode::VanillaSwapFairRate); Nan::SetMethod(target, "VanillaSwapFloatingLegBPS", QuantLibNode::VanillaSwapFloatingLegBPS); Nan::SetMethod(target, "VanillaSwapFloatingLegNPV", QuantLibNode::VanillaSwapFloatingLegNPV); Nan::SetMethod(target, "VanillaSwapFairSpread", QuantLibNode::VanillaSwapFairSpread); Nan::SetMethod(target, "VanillaSwapType", QuantLibNode::VanillaSwapType); Nan::SetMethod(target, "VanillaSwapNominal", QuantLibNode::VanillaSwapNominal); Nan::SetMethod(target, "VanillaSwapFixedRate", QuantLibNode::VanillaSwapFixedRate); Nan::SetMethod(target, "VanillaSwapFixedDayCount", QuantLibNode::VanillaSwapFixedDayCount); Nan::SetMethod(target, "VanillaSwapSpread", QuantLibNode::VanillaSwapSpread); Nan::SetMethod(target, "VanillaSwapFloatingDayCount", QuantLibNode::VanillaSwapFloatingDayCount); Nan::SetMethod(target, "VanillaSwapPaymentConvention", QuantLibNode::VanillaSwapPaymentConvention); Nan::SetMethod(target, "VanillaSwapFixedLegAnalysis", QuantLibNode::VanillaSwapFixedLegAnalysis); Nan::SetMethod(target, "VanillaSwapFloatingLegAnalysis", QuantLibNode::VanillaSwapFloatingLegAnalysis); Nan::SetMethod(target, "BlackConstantVol", QuantLibNode::BlackConstantVol); Nan::SetMethod(target, "BlackVarianceSurface", QuantLibNode::BlackVarianceSurface); Nan::SetMethod(target, "AbcdAtmVolCurve", QuantLibNode::AbcdAtmVolCurve); Nan::SetMethod(target, "SabrVolSurface", QuantLibNode::SabrVolSurface); Nan::SetMethod(target, "VolatilityTermStructureBusinessDayConvention", QuantLibNode::VolatilityTermStructureBusinessDayConvention); Nan::SetMethod(target, "VolatilityTermStructureOptionDateFromTenor", QuantLibNode::VolatilityTermStructureOptionDateFromTenor); Nan::SetMethod(target, "VolatilityTermStructureMinStrike", QuantLibNode::VolatilityTermStructureMinStrike); Nan::SetMethod(target, "VolatilityTermStructureMaxStrike", QuantLibNode::VolatilityTermStructureMaxStrike); Nan::SetMethod(target, "BlackAtmVolCurveAtmVol", QuantLibNode::BlackAtmVolCurveAtmVol); Nan::SetMethod(target, "BlackAtmVolCurveAtmVol2", QuantLibNode::BlackAtmVolCurveAtmVol2); Nan::SetMethod(target, "BlackAtmVolCurveAtmVol3", QuantLibNode::BlackAtmVolCurveAtmVol3); Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance", QuantLibNode::BlackAtmVolCurveAtmVariance); Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance2", QuantLibNode::BlackAtmVolCurveAtmVariance2); Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance3", QuantLibNode::BlackAtmVolCurveAtmVariance3); Nan::SetMethod(target, "BlackVolTermStructureBlackVol", QuantLibNode::BlackVolTermStructureBlackVol); Nan::SetMethod(target, "BlackVolTermStructureBlackVariance", QuantLibNode::BlackVolTermStructureBlackVariance); Nan::SetMethod(target, "BlackVolTermStructureBlackForwardVol", QuantLibNode::BlackVolTermStructureBlackForwardVol); Nan::SetMethod(target, "BlackVolTermStructureBlackForwardVariance", QuantLibNode::BlackVolTermStructureBlackForwardVariance); Nan::SetMethod(target, "AbcdAtmVolCurveOptionTenors", QuantLibNode::AbcdAtmVolCurveOptionTenors); Nan::SetMethod(target, "AbcdAtmVolCurveOptionTenorsInInterpolation", QuantLibNode::AbcdAtmVolCurveOptionTenorsInInterpolation); Nan::SetMethod(target, "AbcdAtmVolCurveOptionDates", QuantLibNode::AbcdAtmVolCurveOptionDates); Nan::SetMethod(target, "AbcdAtmVolCurveOptionTimes", QuantLibNode::AbcdAtmVolCurveOptionTimes); Nan::SetMethod(target, "AbcdAtmVolCurveRmsError", QuantLibNode::AbcdAtmVolCurveRmsError); Nan::SetMethod(target, "AbcdAtmVolCurveMaxError", QuantLibNode::AbcdAtmVolCurveMaxError); Nan::SetMethod(target, "AbcdAtmVolCurveA", QuantLibNode::AbcdAtmVolCurveA); Nan::SetMethod(target, "AbcdAtmVolCurveB", QuantLibNode::AbcdAtmVolCurveB); Nan::SetMethod(target, "AbcdAtmVolCurveC", QuantLibNode::AbcdAtmVolCurveC); Nan::SetMethod(target, "AbcdAtmVolCurveD", QuantLibNode::AbcdAtmVolCurveD); Nan::SetMethod(target, "AbcdAtmVolCurveKatOptionTenors", QuantLibNode::AbcdAtmVolCurveKatOptionTenors); Nan::SetMethod(target, "AbcdAtmVolCurveK", QuantLibNode::AbcdAtmVolCurveK); Nan::SetMethod(target, "VolatilitySpreads", QuantLibNode::VolatilitySpreads); Nan::SetMethod(target, "VolatilitySpreads2", QuantLibNode::VolatilitySpreads2); Nan::SetMethod(target, "AtmCurve", QuantLibNode::AtmCurve); Nan::SetMethod(target, "SabrVolatility", QuantLibNode::SabrVolatility); Nan::SetMethod(target, "PiecewiseConstantAbcdVariance", QuantLibNode::PiecewiseConstantAbcdVariance); Nan::SetMethod(target, "MarketModelLmExtLinearExponentialVolModel", QuantLibNode::MarketModelLmExtLinearExponentialVolModel); Nan::SetMethod(target, "PiecewiseConstantVarianceVariances", QuantLibNode::PiecewiseConstantVarianceVariances); Nan::SetMethod(target, "PiecewiseConstantVarianceVolatilities", QuantLibNode::PiecewiseConstantVarianceVolatilities); Nan::SetMethod(target, "PiecewiseConstantVarianceRateTimes", QuantLibNode::PiecewiseConstantVarianceRateTimes); Nan::SetMethod(target, "PiecewiseConstantVarianceVariance", QuantLibNode::PiecewiseConstantVarianceVariance); Nan::SetMethod(target, "PiecewiseConstantVarianceVolatility", QuantLibNode::PiecewiseConstantVarianceVolatility); Nan::SetMethod(target, "PiecewiseConstantVarianceTotalVariance", QuantLibNode::PiecewiseConstantVarianceTotalVariance); Nan::SetMethod(target, "PiecewiseConstantVarianceTotalVolatility", QuantLibNode::PiecewiseConstantVarianceTotalVolatility); Nan::SetMethod(target, "PiecewiseYieldCurveMixedInterpolation", QuantLibNode::PiecewiseYieldCurveMixedInterpolation); Nan::SetMethod(target, "BachelierCapFloorEngine", QuantLibNode::BachelierCapFloorEngine); Nan::SetMethod(target, "BachelierCapFloorEngine2", QuantLibNode::BachelierCapFloorEngine2); Nan::SetMethod(target, "BachelierBlackFormulaImpliedVol", QuantLibNode::BachelierBlackFormulaImpliedVol); Nan::SetMethod(target, "DeleteObject", QuantLibNode::DeleteObject); Nan::SetMethod(target, "DeleteObjects", QuantLibNode::DeleteObjects); Nan::SetMethod(target, "DeleteAllObjects", QuantLibNode::DeleteAllObjects); Nan::SetMethod(target, "ListObjectIDs", QuantLibNode::ListObjectIDs); Nan::SetMethod(target, "ObjectPropertyNames", QuantLibNode::ObjectPropertyNames); } NODE_MODULE(quantlib, init)
87.414169
165
0.821203
quantlibnode
a058976055137f5f03ab6c450097495f3357939f
1,894
cc
C++
ehpc/src/model/SetJobUserRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
ehpc/src/model/SetJobUserRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
ehpc/src/model/SetJobUserRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ehpc/model/SetJobUserRequest.h> using AlibabaCloud::EHPC::Model::SetJobUserRequest; SetJobUserRequest::SetJobUserRequest() : RpcServiceRequest("ehpc", "2018-04-12", "SetJobUser") { setMethod(HttpRequest::Method::Get); } SetJobUserRequest::~SetJobUserRequest() {} std::string SetJobUserRequest::getRunasUserPassword()const { return runasUserPassword_; } void SetJobUserRequest::setRunasUserPassword(const std::string& runasUserPassword) { runasUserPassword_ = runasUserPassword; setParameter("RunasUserPassword", runasUserPassword); } std::string SetJobUserRequest::getRunasUser()const { return runasUser_; } void SetJobUserRequest::setRunasUser(const std::string& runasUser) { runasUser_ = runasUser; setParameter("RunasUser", runasUser); } std::string SetJobUserRequest::getClusterId()const { return clusterId_; } void SetJobUserRequest::setClusterId(const std::string& clusterId) { clusterId_ = clusterId; setParameter("ClusterId", clusterId); } std::string SetJobUserRequest::getAccessKeyId()const { return accessKeyId_; } void SetJobUserRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); }
25.594595
83
0.75132
iamzken
a06049ac17c49765ab36004d06fec4e0014a9098
943
cpp
C++
Contests/_Archived/Old-Lab/lg1434-lower-score-after-redo.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/_Archived/Old-Lab/lg1434-lower-score-after-redo.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/_Archived/Old-Lab/lg1434-lower-score-after-redo.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e2 + 5; int height[MAXN][MAXN], len[MAXN][MAXN]; int directs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; int r, c; int ans = 0; void dfs(int x, int y) { if (x < 0 || x >= r || y < 0 || y >= c) return; for (int i = 0; i < 4; i++) { int newx = x + directs[i][0], newy = y + directs[i][1]; if (len[newx][newy] == 0 || height[newx][newy] < height[x][y] + 1) { len[newx][newy] = height[x][y] + 1; ans = max(ans, len[newx][newy]); dfs(newx, newy); } } } int main(int argc, char const *argv[]) { int maxh = 0, maxx = 0, maxy = 0; scanf("%d%d", &r, &c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", &height[i][j]); if (height[i][j] > maxh) { maxh = height[i][j]; maxx = i; maxy = j; } } } memset(len, 0, sizeof(len)); len[maxx][maxy] = 1; dfs(maxx, maxy); printf("%d\n", ans - 1); return 0; }
18.490196
68
0.484624
DCTewi
a060f63262b77064c704df214dca93a80cb7c929
410
cpp
C++
remove-element/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
3
2018-05-08T14:08:50.000Z
2019-02-28T00:10:14.000Z
remove-element/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
remove-element/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
#include <vector> class Solution { public: int removeElement(std::vector<int>& nums, int val) { int newSz = 0; // as we know newSz is always less or equal to i (implicit here) // the write access should be fine for (int n : nums) { if (n != val) { nums[newSz] = n; ++newSz; } } return newSz; } };
22.777778
72
0.47561
Javran
a06106b3a8a98dd65658b2db5b7d77b19197e70e
1,100
cpp
C++
Scripts/497.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
Scripts/497.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
Scripts/497.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> rects; vector<int> acc_weights; int area_total = 0; Solution(vector<vector<int>>& rects) { this->rects = rects; for (auto rect : rects){ area_total += (rect[2]-rect[0] + 1) * (rect[3] - rect[1] + 1); this->acc_weights.push_back(area_total); } } vector<int> pick() { int w = rand() % area_total; int left = 0, right = acc_weights.size(), mid; while(left != right) { mid = (left+right)/2; if (w >= acc_weights[mid]) { left = mid+1; } else { right = mid; } } return pickRandomPoint(rects[left]); } vector<int> pickRandomPoint(vector<int> rect) { int x = rand() % (rect[2] - rect[0] + 1); int y = rand() % (rect[3] - rect[1] + 1); return {rect[0] + x, rect[1] + y}; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(rects); * vector<int> param_1 = obj->pick(); */
26.190476
74
0.497273
zzz0906
a0612f0b5015f839d8c53e2de9d78fc53418444f
563
hpp
C++
include/openpose/core/cvMatToOpInput.hpp
noussquid/openpose
e60b5d385f5b26c27be9c2a3bcfddb6648480fc4
[ "MIT-CMU" ]
7
2018-05-03T01:10:56.000Z
2021-01-12T10:39:47.000Z
include/openpose/core/cvMatToOpInput.hpp
clhne/openpose
29b6697d4c4afa919ac0b63c1ed80c5020cbe0df
[ "MIT-CMU" ]
null
null
null
include/openpose/core/cvMatToOpInput.hpp
clhne/openpose
29b6697d4c4afa919ac0b63c1ed80c5020cbe0df
[ "MIT-CMU" ]
6
2018-03-31T06:54:59.000Z
2021-08-18T12:10:42.000Z
#ifndef OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP #define OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP #include <opencv2/core/core.hpp> // cv::Mat #include <openpose/core/common.hpp> namespace op { class OP_API CvMatToOpInput { public: std::vector<Array<float>> createArray(const cv::Mat& cvInputData, const std::vector<double>& scaleInputToNetInputs, const std::vector<Point<int>>& netInputSizes) const; }; } #endif // OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP
29.631579
98
0.634103
noussquid
a0613bf5354c09cdd9ab153af28f2572f48b9b28
37,947
cpp
C++
unittests/rem_rotation_test.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
null
null
null
unittests/rem_rotation_test.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
null
null
null
unittests/rem_rotation_test.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/chain/abi_serializer.hpp> #include <eosio/testing/tester.hpp> #include <Runtime/Runtime.h> #include <fc/variant_object.hpp> #include <boost/test/unit_test.hpp> #include <contracts.hpp> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::chain; using namespace eosio::testing; using namespace fc; using mvo = fc::mutable_variant_object; struct genesis_account { account_name aname; uint64_t initial_balance; }; static std::vector<genesis_account> test_genesis( { {N(b1), 100'000'000'0000ll}, {N(whale1), 70'000'000'0000ll}, {N(whale2), 40'000'000'0000ll}, {N(whale3), 20'000'000'0000ll}, {N(proda), 2'000'000'0000ll}, {N(prodb), 2'000'000'0000ll}, {N(prodc), 2'000'000'0000ll}, {N(prodd), 2'000'000'0000ll}, {N(prode), 2'000'000'0000ll}, {N(prodf), 2'000'000'0000ll}, {N(prodg), 2'000'000'0000ll}, {N(prodh), 2'000'000'0000ll}, {N(prodi), 2'000'000'0000ll}, {N(prodj), 2'000'000'0000ll}, {N(prodk), 2'000'000'0000ll}, {N(prodl), 2'000'000'0000ll}, {N(prodm), 2'000'000'0000ll}, {N(prodn), 2'000'000'0000ll}, {N(prodo), 2'000'000'0000ll}, {N(prodp), 2'000'000'0000ll}, {N(prodq), 2'000'000'0000ll}, {N(prodr), 2'000'000'0000ll}, {N(prods), 2'000'000'0000ll}, {N(prodt), 2'000'000'0000ll}, {N(produ), 2'000'000'0000ll}, {N(runnerup1), 1'000'000'0000ll}, {N(runnerup2), 1'000'000'0000ll}, {N(runnerup3), 1'000'000'0000ll}, {N(runnerup4), 1'000'000'0000ll}, {N(runnerup5), 1'000'000'0000ll}, {N(catchingup), 500'000'0000ll} } ); class rotation_tester : public TESTER { public: rotation_tester(); void deploy_contract( bool call_init = true ) { set_code( config::system_account_name, contracts::rem_system_wasm() ); set_abi( config::system_account_name, contracts::rem_system_abi().data() ); if( call_init ) { base_tester::push_action(config::system_account_name, N(init), config::system_account_name, mutable_variant_object() ("version", 0) ("core", CORE_SYM_STR) ); } const auto& accnt = control->db().get<account_object,by_name>( config::system_account_name ); abi_def abi; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true); abi_ser.set_abi(abi, abi_serializer_max_time); } fc::variant get_global_state() { vector<char> data = get_row_by_account( config::system_account_name, config::system_account_name, N(global), N(global) ); if (data.empty()) std::cout << "\nData is empty\n" << std::endl; return data.empty() ? fc::variant() : abi_ser.binary_to_variant( "eosio_global_state", data, abi_serializer_max_time ); } auto delegate_bandwidth( name from, name receiver, asset stake_quantity, uint8_t transfer = 1) { auto r = base_tester::push_action(config::system_account_name, N(delegatebw), from, mvo() ("from", from ) ("receiver", receiver) ("stake_quantity", stake_quantity) ("transfer", transfer) ); produce_block(); return r; } void create_currency( name contract, name manager, asset maxsupply, const private_key_type* signer = nullptr ) { auto act = mutable_variant_object() ("issuer", manager ) ("maximum_supply", maxsupply ); base_tester::push_action(contract, N(create), contract, act ); } auto issue( name contract, name manager, name to, asset amount ) { auto r = base_tester::push_action( contract, N(issue), manager, mutable_variant_object() ("to", to ) ("quantity", amount ) ("memo", "") ); produce_block(); return r; } auto set_privileged( name account ) { auto r = base_tester::push_action(config::system_account_name, N(setpriv), config::system_account_name, mvo()("account", account)("is_priv", 1)); produce_block(); return r; } auto register_producer(name producer) { auto r = base_tester::push_action(config::system_account_name, N(regproducer), producer, mvo() ("producer", name(producer)) ("producer_key", get_public_key( producer, "active" ) ) ("url", "" ) ("location", 0 ) ); produce_block(); return r; } void votepro( account_name voter, vector<account_name> producers ) { std::sort( producers.begin(), producers.end() ); base_tester::push_action(config::system_account_name, N(voteproducer), voter, mvo() ("voter", name(voter)) ("proxy", name(0) ) ("producers", producers) ); produce_blocks(); }; void set_code_abi(const account_name& account, const vector<uint8_t>& wasm, const char* abi, const private_key_type* signer = nullptr) { wdump((account)); set_code(account, wasm, signer); set_abi(account, abi, signer); if (account == config::system_account_name) { const auto& accnt = control->db().get<account_object,by_name>( account ); abi_def abi_definition; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi_definition), true); abi_ser.set_abi(abi_definition, abi_serializer_max_time); } produce_blocks(); } uint32_t produce_blocks_until_schedule_is_changed(const uint32_t max_blocks) { const auto current_version = control->active_producers().version; uint32_t blocks_produced = 0; while (control->active_producers().version == current_version && blocks_produced < max_blocks) { produce_block(); blocks_produced++; } return blocks_produced; } abi_serializer abi_ser; }; rotation_tester::rotation_tester() { // Create rem.msig and rem.token create_accounts({N(rem.msig), N(rem.token), N(rem.rex), N(rem.ram), N(rem.ramfee), N(rem.stake), N(rem.bpay), N(rem.spay), N(rem.vpay), N(rem.saving)}); // Set code for the following accounts: // - rem (code: rem.bios) (already set by tester constructor) // - rem.msig (code: rem.msig) // - rem.token (code: rem.token) set_code_abi(N(rem.msig), contracts::rem_msig_wasm(), contracts::rem_msig_abi().data()); //, &rem_active_pk); set_code_abi(N(rem.token), contracts::rem_token_wasm(), contracts::rem_token_abi().data()); //, &rem_active_pk); // Set privileged for rem.msig and rem.token set_privileged(N(rem.msig)); set_privileged(N(rem.token)); // Verify rem.msig and rem.token is privileged const auto &rem_msig_acc = get<account_metadata_object, by_name>(N(rem.msig)); BOOST_TEST(rem_msig_acc.is_privileged() == true); const auto &rem_token_acc = get<account_metadata_object, by_name>(N(rem.token)); BOOST_TEST(rem_token_acc.is_privileged() == true); // Create SYS tokens in rem.token, set its manager as rem const auto max_supply = core_from_string("1000000000.0000"); const auto initial_supply = core_from_string("900000000.0000"); create_currency(N(rem.token), config::system_account_name, max_supply); // Issue the genesis supply of 1 billion SYS tokens to rem.system issue(N(rem.token), config::system_account_name, config::system_account_name, initial_supply); // Create genesis accounts for (const auto &account : test_genesis) { create_account(account.aname, config::system_account_name); } deploy_contract(); // Buy ram and stake cpu and net for each genesis accounts for( const auto& account : test_genesis ) { const auto stake_quantity = account.initial_balance - 1000; const auto r = delegate_bandwidth(N(rem.stake), account.aname, asset(stake_quantity)); BOOST_REQUIRE( !r->except_ptr ); } // register whales as producers const auto whales_as_producers = { N(b1), N(whale1), N(whale2), N(whale3) }; for( const auto& producer : whales_as_producers ) { register_producer(producer); } } BOOST_AUTO_TEST_SUITE(rem_rotation_tests) // Expected schedule versions: // V1: top21[proda - prodt, produ], top25[], rotation[] // V2: top21[proda - prodt, produ], top25[], rotation[] // V3: top21[proda - prodt, produ], top25[], rotation[] // ... BOOST_FIXTURE_TEST_CASE( no_rotation_test, rotation_tester ) { try { const auto producer_candidates = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates ); votepro( N(whale2), producer_candidates ); votepro( N(whale3), producer_candidates ); // Initial producers setup { produce_blocks(2); const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::end( producer_candidates ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } const auto rotation_period = fc::hours(4); // Next round { produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::end( producer_candidates ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round { produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::end( producer_candidates ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } } FC_LOG_AND_RETHROW() } // Expected schedule versions: // V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ] // V2: top21[proda - prodt, runnerup1], top25[runnerup1-runnerup4], rotation[runnerup2, runnerup3, runnerup4, produ, runnerup1] // V3: top21[proda - prodt, runnerup2], top25[runnerup1-runnerup4], rotation[runnerup3, runnerup4, produ, runnerup1, runnerup2] // V4: top21[proda - prodt, runnerup3], top25[runnerup1-runnerup4], rotation[runnerup4, produ, runnerup1, runnerup2, runnerup3] // V5: top21[proda - prodt, runnerup4], top25[runnerup1-runnerup4], rotation[produ, runnerup1, runnerup2, runnerup3, runnerup4] // V6: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ] // ... BOOST_FIXTURE_TEST_CASE( rotation_with_stable_top25, rotation_tester ) { try { auto producer_candidates = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } auto runnerups = std::vector< account_name >{ N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4) }; // Register producers for( auto pro : runnerups ) { register_producer(pro); } votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates ); votepro( N(whale2), producer_candidates ); votepro( N(whale3), runnerups ); // After this voting producers table looks like this: // Top21: // proda-produ: (100'000'000'0000 + 70'000'000'0000 + 40'000'000'0000) / 21 = 10'000'000'0000 // Standby (22-24): // runnerup1-runnerup3: 20'000'000'0000 / 3 = 6'600'000'0000 // // So the first schedule should be proda-produ { produce_blocks(2); const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::end( producer_candidates ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } const auto rotation_period = fc::hours(4); // Next round should be included runnerup1 instead of produ { auto rota = producer_candidates; rota.back() = N(runnerup1); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round should be included runnerup2 instead of runnerup1 { auto rota = producer_candidates; rota.back() = N(runnerup2); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round should be included runnerup3 instead of runnerup2 { auto rota = producer_candidates; rota.back() = N(runnerup3); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round should be included runnerup4 instead of runnerup3 { auto rota = producer_candidates; rota.back() = N(runnerup4); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round should be included produ instead of runnerup4 { auto rota = producer_candidates; rota.back() = N(produ); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round should be included runnerup1 instead of produ { auto rota = producer_candidates; rota.back() = N(runnerup1); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } } FC_LOG_AND_RETHROW() } // Expected schedule versions: // V1: top21[proda - produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ] // V2: top21[produ, proda - prods, runnerup1], top25[runnerup1-runnerup4], rotation[runnerup2, runnerup3, runnerup4, prodt, runnerup1] // V3: top21[produ, proda - prods, runnerup2], top25[runnerup1-runnerup4], rotation[runnerup3, runnerup4, prodt, runnerup1, runnerup2] // V4: top21[proda - prods, produ, runnerup3], top25[runnerup3, prodt, runnerup1, runnerup2], rotation[runnerup4, prodt, runnerup1, runnerup2, runnerup3] BOOST_FIXTURE_TEST_CASE( top_25_reordered_test, rotation_tester ) { try { auto producer_candidates = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ), N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4), N(runnerup5) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates); votepro( N(whale2), producer_candidates ); votepro( N(whale3), producer_candidates ); // Initial schedule should be proda-produ { produce_blocks(2); const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::begin( producer_candidates ) + 21, std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } const auto rotation_period = fc::hours(4); // produ votes for himself reaching top1 // top21: produ, proda-prods // top25: prodt, runnerup1-runnerup4 // prodt was in top25 of previous schedule so it will be rotated { // active schedule is sorted by name acutally auto rota = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup1) }; votepro( N(produ), { N(produ) } ); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // Next round { // active schedule is sorted by name acutally auto rota = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup2) }; produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // proda-prods, produ, runnerup4 votes for themselves // top21: proda-prods, produ, runnerup4 // top25: prodt, runnerup1-runnerup3 // runnerup4 was in top25 of previous schedule so it will be rotated { // active schedule is sorted by name acutally auto rota = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup4) }; for( auto pro: rota ) { votepro( pro, { pro } ); } rota.back() = N(runnerup3); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } } FC_LOG_AND_RETHROW() } // Expected schedule versions: // V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ] // V2: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup5, runnerup1, runnerup2, runnerup3, produ] // V3: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup1, runnerup2, runnerup3, produ, runnerup5] BOOST_FIXTURE_TEST_CASE( new_top_21_test, rotation_tester ) { try { auto producer_candidates = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ), N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4), N(runnerup5) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates); votepro( N(whale2), producer_candidates ); votepro( N(whale3), producer_candidates ); // Initial schedule should be proda-produ { produce_blocks(2); const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::begin( producer_candidates ) + 21, std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } const auto rotation_period = fc::hours(4); // produ-prodt voted for themselves getting additional 2'000'000'0000 votes // produ,runnerup1-runnerup4 did not voted for themselves // runnerup5 voted for himselve getting additional 1'000'000'0000 votes // top21: proda-prodt, runnerup5 // top25: produ, runnerup1-runnerup3 { auto rota = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(runnerup5) }; for (auto pro : rota) { votepro(pro, { pro }); } produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } { auto rota = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(runnerup1) }; produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; // std::cout << "expected: " << std::endl; // std::copy( std::begin( rota ), std::end( rota ), std::ostream_iterator< account_name >( std::cout, ", " ) ); // std::cout << "\nactual: " << std::endl; // std::transform( std::begin( active_schedule.producers ), std::end( active_schedule.producers ), std::ostream_iterator< account_name >( std::cout, ", "), []( const auto& prod_key ){ return prod_key.producer_name; } ); BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } } FC_LOG_AND_RETHROW() } // Expected schedule versions: // V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ] // V2: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup5, runnerup1, runnerup2, runnerup3, produ] // V3: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup1, runnerup2, runnerup3, produ, runnerup5] BOOST_FIXTURE_TEST_CASE( new_active_prod_test, rotation_tester ) { try { auto producer_candidates = std::vector< account_name >{ N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } auto runnerups = std::vector< account_name >{ N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4) }; // Register producers for( auto pro : runnerups ) { register_producer(pro); } register_producer(N(catchingup)); votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates ); votepro( N(whale2), producer_candidates ); votepro( N(whale3), runnerups ); votepro( N(catchingup), { N(catchingup) } ); // After this voting producers table looks like this: // Top21: // proda-produ: (100'000'000'0000 + 70'000'000'0000 + 40'000'000'0000) / 21 = 10'000'000'0000 // Standby (22-24): // runnerup1-runnerup3: 20'000'000'0000 / 3 = 6'600'000'0000 // // So the first schedule should be proda-produ { produce_blocks(2); const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( producer_candidates ), std::end( producer_candidates ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } const auto rotation_period = fc::hours(4); // Next round should be included runnerup1 instead of produ { auto rota = producer_candidates; rota.back() = N(runnerup1); produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time) produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule) produce_blocks(2); // wait until schedule is accepted const auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); } // catchingup reaching top1 { producer_candidates.push_back(N(catchingup)); votepro( N(b1), producer_candidates ); votepro( N(whale1), producer_candidates ); votepro( N(whale2), producer_candidates ); produce_blocks_until_schedule_is_changed(2000); produce_blocks(2); auto rota = std::vector< account_name >{ N(catchingup), N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(runnerup1) }; auto active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE( std::equal( std::begin( rota ), std::end( rota ), std::begin( active_schedule.producers ), std::end( active_schedule.producers ), []( const account_name& rhs, const producer_authority& lhs ) { return rhs == lhs.producer_name; } ) ); auto standby = std::vector< account_name >{ N(prodt), N(produ), N(runnerup2), N(runnerup3) }; auto actual_standby = get_global_state()["standby"].get_array(); BOOST_REQUIRE( std::equal( std::begin( standby ), std::end( standby ), std::begin( actual_standby ), std::end( actual_standby ), []( const account_name& rhs, const fc::variant& lhs ) { return rhs == name{ lhs["first"].as_string() }; } ) ); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
45.282816
231
0.584236
kushnirenko
a066e565e42e392490b7c5fe524de9689dc97351
3,866
cpp
C++
src/services/artifact.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
null
null
null
src/services/artifact.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
10
2018-03-02T13:58:32.000Z
2020-06-05T11:12:42.000Z
src/services/artifact.cpp
EmanuelHerrendorf/mapping-core
d28d85547e8ed08df37dad1da142594d3f07a366
[ "MIT" ]
3
2018-02-26T14:01:43.000Z
2019-12-09T10:03:17.000Z
#include "services/httpservice.h" #include "userdb/userdb.h" #include "util/configuration.h" #include "util/concat.h" #include "util/exceptions.h" #include "util/curl.h" #include "util/timeparser.h" #include <cstring> #include <sstream> #include <json/json.h> /* * This class provides access to the artifacts in the UserDB. * Parameter request defines the type of request * * Operations: * - request = create: Create a new artifact * - parameters: * - type * - name * - value * - request = update: Update the value of an existing artifact * - parameters: * - type * - name * - value * - request = get: get the value of a given artifact at a given time (latest version if not specified) * - parameters: * - username * - type * - name * - time (optional) * - request = list: list all artifacts of a given type * - parmeters: * - type * - request = share: share an artifact with a given user * - parameters: * - username * - type * - name */ class ArtifactService : public HTTPService { public: using HTTPService::HTTPService; virtual ~ArtifactService() = default; struct ArtifactServiceException : public std::runtime_error { using std::runtime_error::runtime_error; }; private: virtual void run(); }; REGISTER_HTTP_SERVICE(ArtifactService, "artifact"); void ArtifactService::run() { try { std::string request = params.get("request"); auto session = UserDB::loadSession(params.get("sessiontoken")); auto user = session->getUser(); if(request == "create") { std::string type = params.get("type"); std::string name = params.get("name"); std::string value = params.get("value"); user.createArtifact(type, name, value); response.sendSuccessJSON(); } else if(request == "update") { std::string type = params.get("type"); std::string name = params.get("name"); std::string value = params.get("value"); auto artifact = user.loadArtifact(user.getUsername(), type, name); artifact->updateValue(value); response.sendSuccessJSON(); } else if(request == "get") { std::string username = params.get("username"); std::string type = params.get("type"); std::string name = params.get("name"); std::string time = params.get("time", "9999-12-31T23:59:59"); auto timeParser = TimeParser::create(TimeParser::Format::ISO); double timestamp = timeParser->parse(time); auto artifact = user.loadArtifact(user.getUsername(), type, name); std::string value = artifact->getArtifactVersion(timestamp)->getValue(); Json::Value json(Json::objectValue); json["value"] = value; response.sendSuccessJSON(json); } else if(request == "list") { std::string type = params.get("type"); auto artifacts = user.loadArtifactsOfType(type); Json::Value jsonArtifacts(Json::arrayValue); for(auto artifact : artifacts) { Json::Value entry(Json::objectValue); entry["user"] = artifact.getUser().getUsername(); entry["type"] = artifact.getType(); entry["name"] = artifact.getName(); jsonArtifacts.append(entry); } Json::Value json(Json::objectValue); json["artifacts"] = jsonArtifacts; response.sendSuccessJSON(json); } else if(request == "share") { std::string username = params.get("username"); std::string type = params.get("type"); std::string name = params.get("name"); std::string permission = params.get("permission", ""); auto artifact = user.loadArtifact(user.getUsername(), type, name); if(permission == "user") artifact->shareWithUser(permission); else if(permission == "group") artifact->shareWithGroup(permission); else throw ArtifactServiceException("ArtifactService: invalid permission target"); response.sendSuccessJSON(); } } catch (const std::exception &e) { response.sendFailureJSON(e.what()); } }
27.614286
103
0.665546
EmanuelHerrendorf
a068978f377f85f1696facda1bc974c27b17f582
2,849
cpp
C++
src/pid.cpp
carmeloevoli/SimProp-beta
6d3fce16b0d288abcd36b439ef181b50e96b1ee6
[ "MIT" ]
null
null
null
src/pid.cpp
carmeloevoli/SimProp-beta
6d3fce16b0d288abcd36b439ef181b50e96b1ee6
[ "MIT" ]
null
null
null
src/pid.cpp
carmeloevoli/SimProp-beta
6d3fce16b0d288abcd36b439ef181b50e96b1ee6
[ "MIT" ]
null
null
null
#include "simprop/pid.h" #include <map> #include <string> #include "simprop/units.h" namespace simprop { PID getPidNucleus(const int& Z, const int& A) { if (A < 0 || Z > A) throw std::invalid_argument("invalid arguments for nucleus PID"); return PID(1000000000 + 10 * Z + 10000 * A); } bool pidIsNucleus(const PID& pid) { return (pid.get() >= 1000009990); } int getPidNucleusMassNumber(const PID& pid) { if (!pidIsNucleus(pid)) throw std::invalid_argument(getPidName(pid) + " is not a nucleus"); if (pid == neutron || pid == antiproton) return 1; else return (pid.get() / 10000) % 1000; } int getPidNucleusCharge(const PID& pid) { if (!pidIsNucleus(pid)) throw std::invalid_argument(getPidName(pid) + " is not a nucleus"); if (pid == neutron) return 0; else if (pid == antiproton) return -1; else return (pid.get() / 10) % 1000; } static const std::map<PID, std::string> pidNames = { {photon, "photon"}, {neutrino_e, "nu_e"}, {antineutrino_e, "antinu_e"}, {neutrino_mu, "nu_mu"}, {antineutrino_mu, "antinu_mu"}, {electron, "electron"}, {positron, "positron"}, {pionNeutral, "pion_0"}, {pionPlus, "pion_plus"}, {pionMinus, "pion_minus"}}; static const std::map<int, std::string> chargeToName = { {1, "H"}, {2, "He"}, {3, "Li"}, {4, "Be"}, {5, "B"}, {6, "C"}, {7, "N"}, {8, "O"}, {9, "F"}, {10, "Ne"}, {11, "Na"}, {12, "Mg"}, {13, "Al"}, {14, "Si"}, {15, "P"}, {16, "S"}, {17, "Cl"}, {18, "Ar"}, {19, "K"}, {20, "Ca"}, {21, "Sc"}, {22, "Ti"}, {23, "V"}, {24, "Cr"}, {25, "Mn"}, {26, "Fe"}, {27, "Co"}, {28, "Ni"}}; std::string getPidNucleusName(const PID& pid) { auto A = getPidNucleusMassNumber(pid); auto Z = getPidNucleusCharge(pid); auto it = chargeToName.find(Z); if (it != chargeToName.end()) return it->second + std::to_string(A); else throw std::invalid_argument("pid name not found"); } double getPidMass(const PID& pid) { if (pidIsNucleus(pid)) { auto A = (double)getPidNucleusMassNumber(pid); auto Z = (double)getPidNucleusCharge(pid); return (A - Z) * SI::neutronMassC2 + Z * SI::protonMassC2; } else if (pid == positron || pid == electron) return SI::electronMassC2; else if (pid == pionNeutral || pid == pionMinus || pid == pionPlus) return SI::pionMassC2; else throw std::invalid_argument("mass not available for this pid"); } std::string getPidName(const PID& pid) { if (pid == proton) return "proton"; if (pid == neutron) return "neutron"; if (pid == antiproton) return "antiproton"; if (pid == deuterium) return "deuterium"; if (pidIsNucleus(pid)) return getPidNucleusName(pid); auto it = pidNames.find(pid); if (it != pidNames.end()) return it->second; else throw std::invalid_argument("pid name not found"); } } // namespace simprop
33.916667
93
0.608284
carmeloevoli
a06e6421664e57b4ebfcbb72a51ff87828a4c934
1,419
hpp
C++
include/Error.hpp
scribe-lang/scribe
28ee67cc5081aa3bdd0d4fc284c04738e3272687
[ "MIT" ]
13
2021-12-28T17:54:05.000Z
2022-03-19T16:13:03.000Z
include/Error.hpp
scribelang/scribe
8b82ed839e290c1204928dcd196237c6cd6000ba
[ "MIT" ]
null
null
null
include/Error.hpp
scribelang/scribe
8b82ed839e290c1204928dcd196237c6cd6000ba
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2022 Scribe Language Repositories 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. */ #ifndef ERROR_HPP #define ERROR_HPP #include "Core.hpp" namespace sc { namespace lex { class Lexeme; } // namespace lex class Module; class Stmt; class ModuleLoc { Module *mod; size_t line; size_t col; public: ModuleLoc(Module *mod, const size_t &line, const size_t &col); String getLocStr() const; inline Module *getMod() const { return mod; } inline size_t getLine() const { return line; } inline size_t getCol() const { return col; } }; namespace err { void setMaxErrs(size_t max_err); void out(Stmt *stmt, InitList<StringRef> err); void out(const lex::Lexeme &tok, InitList<StringRef> err); void out(const ModuleLoc &loc, InitList<StringRef> err); // equivalent to out(), but for warnings void outw(Stmt *stmt, InitList<StringRef> err); void outw(const lex::Lexeme &tok, InitList<StringRef> err); void outw(const ModuleLoc &loc, InitList<StringRef> err); } // namespace err } // namespace sc #endif // ERROR_HPP
20.565217
78
0.735729
scribe-lang
a06fe4ad3468774bddbd55ae95b1f76a8c77276b
6,524
cpp
C++
demos/demo_helloworld/demo_helloworld.cpp
borisblizzard/april
924a4fd770508bc87ac67b49b022c9905f94db32
[ "BSD-3-Clause" ]
null
null
null
demos/demo_helloworld/demo_helloworld.cpp
borisblizzard/april
924a4fd770508bc87ac67b49b022c9905f94db32
[ "BSD-3-Clause" ]
null
null
null
demos/demo_helloworld/demo_helloworld.cpp
borisblizzard/april
924a4fd770508bc87ac67b49b022c9905f94db32
[ "BSD-3-Clause" ]
null
null
null
/// @file /// @version 4.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #ifndef __ANDROID__ #ifndef _UWP #define RESOURCE_PATH "../../demos/media/" #else #define RESOURCE_PATH "media/" #endif #elif defined(__APPLE__) #define RESOURCE_PATH "media/" #else #define RESOURCE_PATH "./" #endif #include <stdlib.h> #include <april/april.h> #include <april/Cursor.h> #include <april/KeyDelegate.h> #include <april/main.h> #include <april/MouseDelegate.h> #include <april/Platform.h> #include <april/RenderSystem.h> #include <april/SystemDelegate.h> #include <april/UpdateDelegate.h> #include <april/Window.h> #include <gtypes/Rectangle.h> #include <hltypes/hlog.h> #include <hltypes/hstring.h> #define LOG_TAG "demo_helloworld" april::Cursor* cursor = NULL; april::TexturedVertex v[4]; #if !defined(__ANDROID__) && !defined(_IOS) && !defined(_WINP8) grectf drawRect(0.0f, 0.0f, 800.0f, 600.0f); #else grectf drawRect(0.0f, 0.0f, 480.0f, 320.0f); #endif grectf backgroundRect(50.0f, 50.0f, drawRect.w - 100.0f, drawRect.h - 100.0f); gvec2f size = drawRect.getSize() * 5 / 16; class Ball { public: april::Texture* texture; Ball(april::Texture* texture) { this->texture = texture; this->position.set((float)hrand((int)drawRect.w - size), (float)hrand((int)drawRect.h - size)); this->velocity.set((float)speed, (float)speed); } void update(float timeDelta) { this->position += this->velocity * timeDelta; if (this->position.x < 0 || this->position.x > drawRect.w - size) { this->position -= this->velocity * timeDelta; this->velocity.x = -this->velocity.x; } if (this->position.y < 0 || this->position.y > drawRect.h - size) { this->position -= this->velocity * timeDelta; this->velocity.y = -this->velocity.y; } } void render() { float x1 = this->position.x; float x2 = this->position.x + size; float y1 = this->position.y; float y2 = this->position.y + size; april::rendersys->setTexture(this->texture); v[0].x = x1; v[0].y = y1; v[0].z = 0; v[0].u = 0; v[0].v = 0; v[1].x = x2; v[1].y = y1; v[1].z = 0; v[1].u = 1; v[1].v = 0; v[2].x = x1; v[2].y = y2; v[2].z = 0; v[2].u = 0; v[2].v = 1; v[3].x = x2; v[3].y = y2; v[3].z = 0; v[3].u = 1; v[3].v = 1; april::rendersys->render(april::RenderOperation::TriangleStrip, v, 4); } protected: gvec2f position; gvec2f velocity; static const int size = 96; static const int speed = 256; }; harray<Ball> balls; class UpdateDelegate : public april::UpdateDelegate { bool onUpdate(float timeDelta) override { april::rendersys->clear(); april::rendersys->setOrthoProjection(drawRect); april::rendersys->drawFilledRect(drawRect, april::Color::Grey); april::rendersys->drawFilledRect(backgroundRect, april::Color::DarkGreen); foreach (Ball, it, balls) { it->update(timeDelta); it->render(); } return true; } }; class SystemDelegate : public april::SystemDelegate { public: SystemDelegate() : april::SystemDelegate() { } void onWindowSizeChanged(int width, int height, bool fullScreen) override { hlog::writef(LOG_TAG, "window size changed: %dx%d", width, height); april::rendersys->setViewport(drawRect); } }; static UpdateDelegate* updateDelegate = NULL; static SystemDelegate* systemDelegate = NULL; void __aprilApplicationInit() { #ifdef __APPLE__ // On MacOSX, the current working directory is not set by // the Finder, since you are expected to use Core Foundation // or ObjC APIs to find files. // So, when porting you probably want to set the current working // directory to something sane (e.g. .../Resources/ in the app // bundle). // In this case, we set it to parent of the .app bundle. { // curly braces in order to localize variables CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle); // let's hope chdir() will be happy with utf8 encoding const char* cpath = CFStringGetCStringPtr(path, kCFStringEncodingUTF8); char* cpath_alloc = NULL; if (cpath == NULL) { // CFStringGetCStringPtr is allowed to return NULL. bummer. // we need to use CFStringGetCString instead. cpath_alloc = (char*)malloc(CFStringGetLength(path) + 1); CFStringGetCString(path, cpath_alloc, CFStringGetLength(path) + 1, kCFStringEncodingUTF8); } else { // even though it didn't return NULL, we still want to slice off bundle name. cpath_alloc = (char*)malloc(CFStringGetLength(path) + 1); strcpy(cpath_alloc, cpath); } // just in case / is appended to .app path for some reason if (cpath_alloc[CFStringGetLength(path) - 1] == '/') { cpath_alloc[CFStringGetLength(path) - 1] = 0; } // replace pre-.app / with a null character, thus // cutting off .app's name and getting parent of .app. strrchr(cpath_alloc, '/')[0] = 0; // change current dir using posix api chdir(cpath_alloc); free(cpath_alloc); // even if null, still ok CFRelease(path); CFRelease(url); } #endif srand((unsigned int)htime()); updateDelegate = new UpdateDelegate(); systemDelegate = new SystemDelegate(); #if defined(__ANDROID__) || defined(_IOS) drawRect.setSize(april::getSystemInfo().displayResolution); #endif april::init(april::RenderSystemType::Default, april::WindowType::Default); april::createRenderSystem(); april::Window::Options windowOptions; windowOptions.resizable = true; april::createWindow((int)drawRect.w, (int)drawRect.h, false, "APRIL: Hello World Demo", windowOptions); #ifdef _UWP april::window->setParam("cursor_mappings", "101 " RESOURCE_PATH "cursor\n102 " RESOURCE_PATH "simple"); #endif april::window->setUpdateDelegate(updateDelegate); april::window->setSystemDelegate(systemDelegate); cursor = april::window->createCursorFromResource(RESOURCE_PATH "cursor"); april::window->setCursor(cursor); april::Texture* texture = april::rendersys->createTextureFromResource(RESOURCE_PATH "logo"); balls.add(Ball(texture)); texture = april::rendersys->createTextureFromResource(RESOURCE_PATH "x"); balls.add(Ball(texture)); } void __aprilApplicationDestroy() { april::window->setCursor(NULL); april::window->destroyCursor(cursor); cursor = NULL; foreach (Ball, it, balls) { april::rendersys->destroyTexture((*it).texture); } balls.clear(); april::destroy(); delete systemDelegate; systemDelegate = NULL; delete updateDelegate; updateDelegate = NULL; }
29.125
104
0.700031
borisblizzard
a0715dae8ecd753e5811f33b3bfca3610f48b08e
5,840
cpp
C++
test/cppunit-tests/TestXml.cpp
johnhalloran321/crux-toolkit
329390c63a4ec8ab4add22d847732dfa2e7f74ca
[ "Apache-2.0" ]
27
2016-10-04T19:06:41.000Z
2022-02-24T12:59:59.000Z
test/cppunit-tests/TestXml.cpp
johnhalloran321/crux-toolkit
329390c63a4ec8ab4add22d847732dfa2e7f74ca
[ "Apache-2.0" ]
232
2016-10-25T05:54:38.000Z
2022-03-30T20:33:35.000Z
test/cppunit-tests/TestXml.cpp
johnhalloran321/crux-toolkit
329390c63a4ec8ab4add22d847732dfa2e7f74ca
[ "Apache-2.0" ]
29
2016-10-04T22:12:32.000Z
2022-03-26T17:12:27.000Z
#include <cppunit/config/SourcePrefix.h> #include <stdlib.h> #include <map> #include "TestXml.h" #include "Match.h" #include "Peptide.h" #include "modifications.h" #include "parameter.h" using namespace std; bool set_double_parameter( const char* name, ///< the name of the parameter looking for -in double set_value, ///< the value to be set -in double min_value, ///< the value to be set -in double max_value, ///< the value to be set -in const char* usage, ///< string to print in usage statement const char* filenotes, ///< additional info for param file const char* foruser ///< "true" if should be revealed to user ); CPPUNIT_TEST_SUITE_REGISTRATION( TestXml ); void TestXml::setUp(){ initialize_parameters(); set_double_parameter((const char*) "V", 30, 30, 30, "", "", ""); set_double_parameter((const char*) "P", 40, 40, 40, "", "", ""); isotopic_type = get_mass_type_parameter("isotopic-mass"); mass_v = get_mass_amino_acid('V', isotopic_type); mass_p = get_mass_amino_acid('P', isotopic_type); ord_pep_seq = "VGGAGK"; //ordinary peptide sequence } void TestXml::tearDown(){ var_mods.clear(); static_mods.clear(); } /* * Checks that the number of internal cleavage should be * zero for ordinary peptide sequence and Trypsin cut */ void TestXml::getNumInternalCleavageNone(){ int num_missed_cleavage = get_num_internal_cleavage((char *)ord_pep_seq.c_str(), TRYPSIN); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of internal cleavages is wrong.", 0, num_missed_cleavage); } /* * Checks that number of internal cleavage or RVGGAGKA * should be two since RV and KA are internal sites */ void TestXml::getNumInternalCleavageTwo(){ string peptide_sequence = "RVGGAGKA"; //RV and KA int num_missed_cleavage = get_num_internal_cleavage((char *)peptide_sequence.c_str(), TRYPSIN); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of internal cleavages is wrong.", 2, num_missed_cleavage); } /* * Checks that Dash '-' is counted as terminal cleavage */ void TestXml::getNumTerminalCleavageTwoDash(){ int num = get_num_terminal_cleavage((char*)ord_pep_seq.c_str(), '-', '-', TRYPSIN); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of terminal cleavage is wrong.", 2, num); } /* * Checks that it recognizes non-terminal cleavage sites * at the beginning of the sequence */ void TestXml::getNumTerminalCleavageOnePrev(){ int num = get_num_terminal_cleavage((char*)ord_pep_seq.c_str(), 'R', 'P', TRYPSIN); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of terminal cleavage is wrong.", 1, num); } /* * Checks that it recognizes non-terminal cleavage sites * at the end of the sequence */ void TestXml::getNumTerminalCleavageOneNext(){ string peptide_sequence = "PGGAGK"; int num = get_num_terminal_cleavage((char*)peptide_sequence.c_str(), 'R', 'A', TRYPSIN); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of terminal cleavage is wrong.", 1, num); } /* * Makes sure that the number variable modifications found in * sequence is 0 */ void TestXml::findVariableModificationsNone(){ find_variable_modifications(var_mods, (char*)ord_pep_seq.c_str()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of variable modifcations is wrong.", 0, (int)var_mods.size()); } /* * Makes sure that the correct variable modifications are * identified */ void TestXml::findVariableModificationsThree(){ string mod_seq = "V[100.00]GGA[20.3]K[100.1]"; find_variable_modifications(var_mods, (char*)mod_seq.c_str()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of variable modifications is wrong.", 3, (int)var_mods.size()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect variable modification information", 100.00, var_mods[1]); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect variable modification information", 20.3, var_mods[4]); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect variable modification information", 100.1, var_mods[5]); } /* * Makes sure that none of the static modifications are * identified because the modifications were already * identified as variable */ void TestXml::findStaticModificationsNoneFromVariable(){ string mod_seq = "V[100.00]GGA[20.3]K[100.1]"; find_variable_modifications(var_mods, (char*) mod_seq.c_str()); find_static_modifications(static_mods, var_mods, (char*) ord_pep_seq.c_str()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of static modifcations is wrong.", 0, (int)static_mods.size()); } /* * Makes sure that there are no static modifications * found in the the sequence RRRRR */ void TestXml::findStaticModificationsNone(){ string mod_seq = "R[100.00]RRR[20.3]R[100.1]"; string peptide_sequence = "RRRRR"; find_variable_modifications(var_mods, (char*) mod_seq.c_str()); find_static_modifications(static_mods, var_mods, (char*) peptide_sequence.c_str()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of static modifcations is wrong.", 0, (int)static_mods.size()); } /* * Makes sure all static modifications are found * and identified correctly */ void TestXml::findStaticModificationsThree(){ string mod_seq = "VGGPA[20.3]GKP"; string peptide_sequence = "VGGPAGKP"; find_variable_modifications(var_mods, (char*) mod_seq.c_str()); find_static_modifications(static_mods, var_mods, (char*) peptide_sequence.c_str()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of static modifcations is wrong.", 3, (int)static_mods.size()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect static modification information", mass_v , static_mods[1]); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect static modification information", mass_p , static_mods[4]); CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect static modification information", mass_p , static_mods[8]); }
33.563218
77
0.718664
johnhalloran321
a074fd13a34c341a5fdf673edc6fb541e13384e8
10,981
cc
C++
selfdrive/ui/qt/widgets/moc_setup.cc
hikee9123/openpilot_083
0734b670396417e568186bf146865e1032116dad
[ "MIT" ]
null
null
null
selfdrive/ui/qt/widgets/moc_setup.cc
hikee9123/openpilot_083
0734b670396417e568186bf146865e1032116dad
[ "MIT" ]
null
null
null
selfdrive/ui/qt/widgets/moc_setup.cc
hikee9123/openpilot_083
0734b670396417e568186bf146865e1032116dad
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'setup.hpp' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "setup.hpp" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'setup.hpp' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.8. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_PairingQRWidget_t { QByteArrayData data[3]; char stringdata0[25]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PairingQRWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PairingQRWidget_t qt_meta_stringdata_PairingQRWidget = { { QT_MOC_LITERAL(0, 0, 15), // "PairingQRWidget" QT_MOC_LITERAL(1, 16, 7), // "refresh" QT_MOC_LITERAL(2, 24, 0) // "" }, "PairingQRWidget\0refresh\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PairingQRWidget[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0 // eod }; void PairingQRWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<PairingQRWidget *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->refresh(); break; default: ; } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject PairingQRWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_PairingQRWidget.data, qt_meta_data_PairingQRWidget, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *PairingQRWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PairingQRWidget::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_PairingQRWidget.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int PairingQRWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } struct qt_meta_stringdata_PrimeUserWidget_t { QByteArrayData data[4]; char stringdata0[40]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PrimeUserWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PrimeUserWidget_t qt_meta_stringdata_PrimeUserWidget = { { QT_MOC_LITERAL(0, 0, 15), // "PrimeUserWidget" QT_MOC_LITERAL(1, 16, 13), // "replyFinished" QT_MOC_LITERAL(2, 30, 0), // "" QT_MOC_LITERAL(3, 31, 8) // "response" }, "PrimeUserWidget\0replyFinished\0\0response" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PrimeUserWidget[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 19, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QString, 3, 0 // eod }; void PrimeUserWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<PrimeUserWidget *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->replyFinished((*reinterpret_cast< QString(*)>(_a[1]))); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject PrimeUserWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_PrimeUserWidget.data, qt_meta_data_PrimeUserWidget, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *PrimeUserWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PrimeUserWidget::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_PrimeUserWidget.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int PrimeUserWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } struct qt_meta_stringdata_PrimeAdWidget_t { QByteArrayData data[1]; char stringdata0[14]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PrimeAdWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PrimeAdWidget_t qt_meta_stringdata_PrimeAdWidget = { { QT_MOC_LITERAL(0, 0, 13) // "PrimeAdWidget" }, "PrimeAdWidget" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PrimeAdWidget[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void PrimeAdWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject PrimeAdWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_PrimeAdWidget.data, qt_meta_data_PrimeAdWidget, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *PrimeAdWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PrimeAdWidget::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_PrimeAdWidget.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int PrimeAdWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); return _id; } struct qt_meta_stringdata_SetupWidget_t { QByteArrayData data[6]; char stringdata0[58]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_SetupWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_SetupWidget_t qt_meta_stringdata_SetupWidget = { { QT_MOC_LITERAL(0, 0, 11), // "SetupWidget" QT_MOC_LITERAL(1, 12, 10), // "parseError" QT_MOC_LITERAL(2, 23, 0), // "" QT_MOC_LITERAL(3, 24, 8), // "response" QT_MOC_LITERAL(4, 33, 13), // "replyFinished" QT_MOC_LITERAL(5, 47, 10) // "showQrCode" }, "SetupWidget\0parseError\0\0response\0" "replyFinished\0showQrCode" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_SetupWidget[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 29, 2, 0x08 /* Private */, 4, 1, 32, 2, 0x08 /* Private */, 5, 0, 35, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QString, 3, QMetaType::Void, QMetaType::QString, 3, QMetaType::Void, 0 // eod }; void SetupWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<SetupWidget *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->parseError((*reinterpret_cast< QString(*)>(_a[1]))); break; case 1: _t->replyFinished((*reinterpret_cast< QString(*)>(_a[1]))); break; case 2: _t->showQrCode(); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject SetupWidget::staticMetaObject = { { &QFrame::staticMetaObject, qt_meta_stringdata_SetupWidget.data, qt_meta_data_SetupWidget, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *SetupWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *SetupWidget::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_SetupWidget.stringdata0)) return static_cast<void*>(this); return QFrame::qt_metacast(_clname); } int SetupWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QFrame::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
28.448187
96
0.63282
hikee9123
a076344867e963a6feaee7c6e9381dd3f16e0f07
7,017
cpp
C++
Engine/Source/Runtime/RuntimeAssetCache/Private/RuntimeAssetCacheBuilders.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/RuntimeAssetCache/Private/RuntimeAssetCacheBuilders.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/RuntimeAssetCache/Private/RuntimeAssetCacheBuilders.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "RuntimeAssetCachePrivatePCH.h" #include "RuntimeAssetCacheBuilders.h" #include "EngineMinimal.h" void URuntimeAssetCacheBuilder_ObjectBase::SaveNewAssetToCache(UObject* NewAsset) { SetAsset(NewAsset); GetFromCacheAsync(OnAssetCacheComplete); } void URuntimeAssetCacheBuilder_ObjectBase::SetAsset(UObject* NewAsset) { Asset = NewAsset; OnSetAsset(Asset); } FVoidPtrParam URuntimeAssetCacheBuilder_ObjectBase::Build() { // There was no cached asset, so this is expecting us to return the data that needs to be saved to disk // If we have no asset created yet, just return null. That will trigger the async creation of the asset. // If we do have an asset, serialize it here into a good format and return a pointer to that memory buffer. if (Asset) { int64 DataSize = GetSerializedDataSizeEstimate(); void* Result = new uint8[DataSize]; FBufferWriter Ar(Result, DataSize, false); Ar.ArIsPersistent = true; SerializeAsset(Ar); return FVoidPtrParam(Result, Ar.Tell()); } // null return FVoidPtrParam::NullPtr(); } void URuntimeAssetCacheBuilder_ObjectBase::GetFromCacheAsync(const FOnAssetCacheComplete& OnComplete) { OnAssetCacheComplete = OnComplete; GetFromCacheAsyncCompleteDelegate.BindDynamic(this, &URuntimeAssetCacheBuilder_ObjectBase::GetFromCacheAsyncComplete); GetRuntimeAssetCache().GetAsynchronous(this, GetFromCacheAsyncCompleteDelegate); } void URuntimeAssetCacheBuilder_ObjectBase::GetFromCacheAsyncComplete(int32 Handle, FVoidPtrParam DataPtr) { if (DataPtr.Data != nullptr) { // Success! Finished loading or saving data from cache // If saving, then we already have the right data and we can just report success if (Asset == nullptr) { // If loading, we now need to serialize the data into a usable format // Make sure Asset is set up to be loaded into OnAssetPreLoad(); FBufferReader Ar(DataPtr.Data, DataPtr.DataSize, false); SerializeAsset(Ar); // Perform any specific init functions after load OnAssetPostLoad(); } // Free the buffer memory on both save and load // On save the buffer gets created in Build() // On load the buffer gets created in FRuntimeAssetCacheBackend::GetCachedData() FMemory::Free(DataPtr.Data); // Success! OnAssetCacheComplete.ExecuteIfBound(this, true); CacheHandle = 0; } else { // Data not on disk. Kick off the creation process. // Once complete, call GetFromCacheAsync() again and it will loop back to this function, but should succeed. // But, prevent recursion the second time by checking if the CacheHandle is already set. if (CacheHandle == 0) { CacheHandle = Handle; OnAssetCacheMiss(); } else { // Failed OnAssetCacheComplete.ExecuteIfBound(this, false); } } } void UExampleTextureCacheBuilder::OnSetAsset(UObject* NewAsset) { Texture = Cast<UTexture2D>(NewAsset); } void UExampleTextureCacheBuilder::OnAssetCacheMiss_Implementation() { // Override and create the new asset here (this is where we would render to a render target, then get the result) // For this example we will simply load an existing texture UTexture2D* NewTexture = LoadObject<UTexture2D>(nullptr, *AssetName); // Make sure the new asset gets properly cached for next time. SaveNewAssetToCache(NewTexture); } void UExampleTextureCacheBuilder::SerializeAsset(FArchive& Ar) { if (Texture && Texture->PlatformData) { FTexturePlatformData* PlatformData = Texture->PlatformData; UEnum* PixelFormatEnum = UTexture::GetPixelFormatEnum(); Ar << PlatformData->SizeX; Ar << PlatformData->SizeY; Ar << PlatformData->NumSlices; if (Ar.IsLoading()) { FString PixelFormatString; Ar << PixelFormatString; PlatformData->PixelFormat = (EPixelFormat)PixelFormatEnum->FindEnumIndex(*PixelFormatString); } else if (Ar.IsSaving()) { FString PixelFormatString = PixelFormatEnum->GetEnum(PlatformData->PixelFormat).GetPlainNameString(); Ar << PixelFormatString; } int32 NumMips = PlatformData->Mips.Num(); int32 FirstMip = 0; int32 LastMip = NumMips; TArray<uint32> SavedFlags; if (Ar.IsSaving()) { // Force resident mips inline SavedFlags.Empty(NumMips); for (int32 MipIndex = 0; MipIndex < NumMips; ++MipIndex) { SavedFlags.Add(PlatformData->Mips[MipIndex].BulkData.GetBulkDataFlags()); PlatformData->Mips[MipIndex].BulkData.SetBulkDataFlags(BULKDATA_ForceInlinePayload | BULKDATA_SingleUse); } // Don't save empty Mips while (FirstMip < NumMips && PlatformData->Mips[FirstMip].BulkData.GetBulkDataSize() <= 0) { FirstMip++; } for (int32 MipIndex = FirstMip + 1; MipIndex < NumMips; ++MipIndex) { if (PlatformData->Mips[FirstMip].BulkData.GetBulkDataSize() <= 0) { // This means there are empty tail mips, which should never happen // If it does, simply don't save any mips after this point. LastMip = MipIndex; break; } } int32 NumMipsSaved = LastMip - FirstMip; Ar << NumMipsSaved; } if (Ar.IsLoading()) { Ar << NumMips; LastMip = NumMips; PlatformData->Mips.Empty(NumMips); for (int32 MipIndex = 0; MipIndex < NumMips; ++MipIndex) { new(PlatformData->Mips) FTexture2DMipMap(); } } uint32 LockFlags = Ar.IsSaving() ? LOCK_READ_ONLY : LOCK_READ_WRITE; for (int32 MipIndex = FirstMip; MipIndex < LastMip; ++MipIndex) { FTexture2DMipMap& Mip = PlatformData->Mips[MipIndex]; Ar << Mip.SizeX; Ar << Mip.SizeY; int32 BulkDataSizeInBytes = Mip.BulkData.GetBulkDataSize(); Ar << BulkDataSizeInBytes; if (BulkDataSizeInBytes > 0) { void* BulkMipData = Mip.BulkData.Lock(LockFlags); if (Ar.IsLoading()) { int32 ElementCount = BulkDataSizeInBytes / Mip.BulkData.GetElementSize(); BulkMipData = Mip.BulkData.Realloc(ElementCount); } Ar.Serialize(BulkMipData, BulkDataSizeInBytes); Mip.BulkData.Unlock(); } } // Restore flags if (Ar.IsSaving()) { for (int32 MipIndex = 0; MipIndex < NumMips; ++MipIndex) { PlatformData->Mips[MipIndex].BulkData.SetBulkDataFlags(SavedFlags[MipIndex]); } } } } void UExampleTextureCacheBuilder::OnAssetPreLoad() { // Create an object to load the data into UTexture2D* NewTexture = NewObject<UTexture2D>(); NewTexture->PlatformData = new FTexturePlatformData(); NewTexture->NeverStream = true; SetAsset(NewTexture); } void UExampleTextureCacheBuilder::OnAssetPostLoad() { Texture->UpdateResource(); } int64 UExampleTextureCacheBuilder::GetSerializedDataSizeEstimate() { int64 DataSize = sizeof(FTexturePlatformData); DataSize += sizeof(FString) + (sizeof(TCHAR) * 12); // Guess the size of the pixel format string (most are less than 12 characters, but we don't need to be exact) DataSize += Texture->GetResourceSize(EResourceSizeMode::Exclusive); // Size of all the mips DataSize += (sizeof(int32) * 3) * Texture->GetNumMips(); // Each mip stores its X and Y size, and its BulkDataSize return DataSize; }
30.376623
168
0.729514
PopCap
a0766ce898b416d7957d626dafbc34758d47915a
12,415
cc
C++
src/library/blas/functor/hawaii_sgemmSplit64_32.cc
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
615
2015-01-05T13:24:44.000Z
2022-03-31T14:58:04.000Z
src/library/blas/functor/hawaii_sgemmSplit64_32.cc
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
223
2015-01-12T21:07:18.000Z
2021-11-24T17:00:44.000Z
src/library/blas/functor/hawaii_sgemmSplit64_32.cc
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
250
2015-01-05T06:39:43.000Z
2022-03-23T09:13:00.000Z
#if !defined CLBLAS_HAWAII_DYNAMIC_KERNEL || !defined CLBLAS_BONAIRE_DYNAMIC_KERNEL //this split kernel algorithm solves the main matrix with 64x64 micro tile size //solves the row boundry with 32x64 micro tile size //solves the column boundry with 64x32 micro tile size //solves the rest boundry with 32x32 micro tile size //assumption : after the main matrix being computed by kernels with 64x64 micro tile size, the boundary are of size 32. //in other words, M and N are mod32 and not mod64 #include <stdio.h> #include <string.h> #include <clBLAS.h> #include <devinfo.h> #include "clblas-internal.h" #include "solution_seq.h" #include <functor.h> #include <binary_lookup.h> #include <iostream> #include <functor_xgemm.h> #include <tahiti.h> #include <hawaii.h> #include "BinaryBuild.h" #include "hawaii_sgemmSplit64_32.h" #if BUILD_KERNEL_FROM_STRING //#include "sgemm_hawaiiSplitKernel.clT" #else #ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL #include "sgemm_hawaiiSplit64_32.clHawaii_64.bin.clT" #include "sgemm_gcn.clHawaii_64.bin.clT" #endif//CLBLAS_HAWAII_DYNAMIC_KERNEL #ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL //#include "sgemm_hawaiiSplitKernel.clBonaire_64.bin.clT" #endif //CLBLAS_BONAIRE_DYNAMIC_KERNEL #endif //BUILD_KERNEL_FROM_STRING // Just because the full name is too long typedef clBlashawaiiSgemmSplit64_32Functor::Variant Variant; //define the string name of the soure/binary code #define SGEMM_SRC_NAME(TA,TB, DIVK, MULT) sgemm_##TA##TB##_##DIVK##_SPLIT##MULT #define SGEMM_SRC_NAME_HAWAII(TA,TB, DIVK, MULT, BITS) sgemm_##TA##TB##_##DIVK##_SPLIT##MULT##_##BITS##_bin_Hawaii #define SGEMM_SRC_NAME_BONAIRE(TA,TB, DIVK, MULT, BITS) sgemm_##TA##TB##_##DIVK##_SPLIT##MULT##_##BITS##_bin_Bonaire #define SGEMM_SRC_NAME_BIN(TA,TB, DIVK, MULT, BITS, DEVICE) SGEMM_SRC_NAME##_##DEVICE(TA,TB, DIVK, MULT, BITS) //variant name used to differentiate the different ones #define SGEMM_VARIANT_NAME(TA,TB, DIVK, MULT) "sgemm_" #TA #TB "_" #DIVK "_SPLIT64_32" #MULT //SGEMM_VARIANT_NAME(TA, TB, DIVM , DIVN, DIVK, GREATER48M, GREATER48N, NBKERNEL), #define SGEMM_KERNEL_NAME(TA,TB,DIVM,DIVN,DIVK,BS0,BS1,NV0,NV1,MULT, BLOC) "sgemm_" #TA #TB "_" #DIVM "_" #DIVN "_" #DIVK "_" #BS0 "x" #BS1 "_" #NV0 "x" #NV1 #MULT "_SPLIT_" #BLOC #define trans_N clblasNoTrans #define trans_T clblasTrans // Fill a variant descriptor using OpenCL source #define SGEMM_VARIANT_OBJ(TA,TB,DIVK,BS0,BS1,NV0,NV1, BITS, MULT, \ KERNEL_NAME_MAIN, KERNEL_NAME_ROW, KERNEL_NAME_COLUMN, KERNEL_NAME_SINGLE, \ KERNELS_SRC, \ KERNEL_BUILD_OPTIONS, \ KERNELS_BIN, \ KERNEL_BIN_SIZE) { \ SGEMM_VARIANT_NAME(TA,TB, DIVK, MULT), \ { KERNEL_NAME_MAIN, KERNEL_NAME_ROW, KERNEL_NAME_COLUMN, KERNEL_NAME_SINGLE } , \ KERNELS_SRC, \ KERNEL_BUILD_OPTIONS, \ KERNELS_BIN, \ KERNEL_BIN_SIZE, \ trans_##TA, trans_##TB, \ DIVK , \ { BS0, BS1 } , \ { NV0, NV1 } , \ #MULT \ } typedef clblasFunctorCache<clBlashawaiiSgemmSplit64_32Functor, const Variant *> CacheSplit; static CacheSplit cachesplit ; // Make it 1 to enable additional debug 'print' #define VERB 0 //static bool applicable( const Variant & var, clblasSgemmFunctor::Args & args, int RefMultiple ) //{ //#if 0 // // Transpose values are tested in select_variant // if ( args.transA != var.transA ) return false ; // if ( args.transB != var.transB ) return false ; //#endif // // //if (args.N>=var.divN && args.N % var.divN != 0 ) // if ( args.N % var.divN != 0 ) // return false ; // if ( args.M % var.divM != 0 ) // return false ; // if(var.Greater[0]?args.M<RefMultiple:args.M>=RefMultiple) // return false; // if(var.Greater[1]?args.N<RefMultiple:args.N>=RefMultiple) // return false; // if ( args.beta==0 && var.mult.compare("__ALPHA")!=0) // return false ; // return true ; //} static void to_upper(char* input) { while(*input) { *input=toupper(*input); input++; } } static const Variant * select_variant_SplitKernel( clblasSgemmFunctor::Args & args, const char* DevName, cl_uint _64BitsUse ) { if(_64BitsUse!=64) { std::cout<<"we don't support clblas on 32 bits"<< std::endl; assert(1); return NULL; } if ( args.transA == clblasNoTrans ) { if ( args.transB == clblasNoTrans ) { // ===== sgemm NN ====== // NN not implemented yet return NULL; } if (args.transB == clblasTrans) { const char* KName_NTMain = "sgemm_NT_64_64_16_16x16_4x4__ALPHABETA_SPLIT_MAIN" ; const char* KName_NTRow = "sgemm_NT_32_64_16_16x16_2x4__ALPHABETA_SPLIT_ROW" ; const char* KName_NTColumn = "sgemm_NT_64_32_16_16x16_4x2__ALPHABETA_SPLIT_COLUMN" ; const char* KName_NTSingleWave = "sgemm_NT_32_32_16_16x16_2x2__ALPHABETA_SPLIT_SINGLE" ; const char* KBin_NTMain64 ; size_t KBin_NTMainSize64 = 0; if (!strcmp(DevName, "Hawaii")) { #ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL //KBin_NTMain64 = SGEMM_SRC_NAME_BIN(N, T, 16, __ALPHABETA, 64, HAWAII) ; //KBin_NTMainSize64 = sizeof(SGEMM_SRC_NAME_BIN(N, T, 16, __ALPHABETA, 64, HAWAII)) ; KBin_NTMain64 = sgemm_NT_64_32_SPLIT__ALPHABETA_64_bin_Hawaii; KBin_NTMainSize64 = sizeof(sgemm_NT_64_32_SPLIT__ALPHABETA_64_bin_Hawaii); #endif //CLBLAS_HAWAII_DYNAMIC_KERNEL } else if (!strcmp(DevName, "Bonaire")) { #ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL //not implemented for Bonaire yet #endif //#ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL } // ===== SGEMM NT ====== static const Variant variant = SGEMM_VARIANT_OBJ(N,T,16,16,16,4,4,64,__ALPHABETA, KName_NTMain,KName_NTRow, KName_NTColumn, KName_NTSingleWave , NULL, NULL, KBin_NTMain64, KBin_NTMainSize64) ; return &variant ; } } else { // TN and TT are not implemented yet return NULL; } return NULL; } clBlashawaiiSgemmSplit64_32Functor::clBlashawaiiSgemmSplit64_32Functor(Args & args, const Variant * variant, cl_int & err) { cl_device_id device; cl_context context; m_program=NULL; m_variantSplit = variant; cl_command_queue queue = args.queue; err = getDeviceAndContext(queue, device, context); if( err != CL_SUCCESS ) { return; } if (VERB) printf(" ===> GET KERNEL %s\n", this->m_variantSplit->variantName) ; //Ben do I use the correct "kernel_name"? BinaryLookup bl(context, device, "clBlashawaiiSgemmSplitKernelFunctor"); bl.variantRaw( this->m_variantSplit->variantName, strlen(this->m_variantSplit->variantName)+1 ) ; if ( !bl.found() ) // may create empty file or may wait until file is ready { if ( this->m_variantSplit->bin != NULL ) { // build from a pre-compiled version of the kernel (SPIR or cl binaries) //only 1 binary containing all the kernel err = bl.buildFromBinary(this->m_variantSplit->bin, this->m_variantSplit->bin_size, /*this->m_variantSplit->build_options[i]*/ "-cl-std=2.0"); } else { //// directly build from a char* //for (int i=0; i<4; i++) // if(this->m_variantSplit->source[i] != 0) // err = bl.buildFromSource(this->m_variantSplit->source[i]); if (VERB) printf(" ===> BUILD PROBLEM WE DON'T SUPPORT SOURCE BUILD FOR SPLIT SGEMM\n") ; return; } if ( err != CL_SUCCESS ) { if (VERB) printf(" ===> BUILD PROBLEM\n") ; return; } } this->m_program = bl.getProgram(); } clBlashawaiiSgemmSplit64_32Functor * clBlashawaiiSgemmSplit64_32Functor::provide(clblasSgemmFunctor::Args & args, char* DevName) { if ( args.order == clblasRowMajor ) return NULL ; // The RowMajor case shall never occur. cl_device_id dev; cl_context ctxt; cl_int err = getDeviceAndContext(args.queue, dev, ctxt); if (err != CL_SUCCESS) { return NULL; } cl_uint bitness = getAddressBits(dev); int major; int minor; getCLVersion(dev, major, minor); //if (major<2) // return NULL; // to_upper( DevName); const Variant * variant = select_variant_SplitKernel( args, DevName, bitness ) ; if ( variant == NULL ) return NULL ; CacheSplit::Lookup lookup(cachesplit, ctxt, dev, variant) ; if ( lookup.ok() ) { clBlashawaiiSgemmSplit64_32Functor * functor = lookup.get(); functor->retain(); // increment the reference counter to avoid deletion while it is still beeing used return functor; } clBlashawaiiSgemmSplit64_32Functor * functor = new clBlashawaiiSgemmSplit64_32Functor(args, variant, err); if (err != CL_SUCCESS) { return NULL; } lookup.set(functor) ; return functor; } cl_int clBlashawaiiSgemmSplit64_32Functor::KernelsLaunch(cl_command_queue queue, cl_kernel Kernel[4], Args &args) { //GlobalX = ((Mvalue - 1) / 64) * 16 //GlobalY = ((Nvalue - 1) / 64) * 16 size_t GlobalX = ((args.M - 1) / (m_variantSplit->bwi[0] * m_variantSplit->ls[0])) * 16; size_t GlobalY = ((args.N - 1) / (m_variantSplit->bwi[1] * m_variantSplit->ls[1])) * 16; std::size_t gs[2] = {GlobalX, GlobalY}; cl_int error = 0; //M and N are not mod64 and are mod32 if (args.M % 64 != 0 && args.N % 64 != 0 && args.M % 32 == 0 && args.N % 32 == 0 && args.M >= 64 && args.N >= 64) { if (VERB) printf(" ===> EXECUTE KERNEL 0, 1, 2, 3 \n") ; error = clEnqueueNDRangeKernel(queue, Kernel[0], 2, NULL, gs, m_variantSplit->ls, args.numEventsInWaitList, args.eventWaitList,NULL); gs[0] = 16; error |= clEnqueueNDRangeKernel(queue, Kernel[1], 2, NULL, gs, m_variantSplit->ls, 0, NULL,NULL); gs[1] = 16; gs[0] = GlobalX; error |= clEnqueueNDRangeKernel(queue, Kernel[2], 2, NULL, gs, m_variantSplit->ls, 0, NULL,NULL); gs[0] = 16; gs[1] = 16; error |= clEnqueueNDRangeKernel(queue, Kernel[3], 2, NULL, gs, m_variantSplit->ls, 0, NULL,args.events); return error; } return clblasNotImplemented; } clblasStatus clBlashawaiiSgemmSplit64_32Functor::execute(Args &args) { cl_int err; cl_command_queue queue = args.queue; if (VERB) printf(" ===> EXECUTE KERNEL %s, alpha =%f ,beta = %f\n", this->m_variantSplit->kernel_name, args.alpha, args.beta) ; cl_kernel kernel[4]; int NBKernel = 0; for (int i=0; i<4; i++) { if (this->m_variantSplit->kernel_name[i]) { kernel[i ]= clCreateKernel( this->m_program, this->m_variantSplit->kernel_name[i], &err); if (err != CL_SUCCESS) return clblasStatus(err) ; NBKernel++; } else break; } if (NBKernel != 4) return clblasStatus(clblasBuildProgramFailure) ; if (VERB) { for (int i=0; i<NBKernel; i++) printf(" ===> FOUND %s\n", this->m_variantSplit->kernel_name[i]) ; } int M = args.M, N = args.N, K = args.K; int lda = args.lda, ldb = args.ldb, ldc = args.ldc; int offsetA = args.offA; int offsetB = args.offB; int offsetC = args.offC; int arg[4]={0, 0, 0, 0} ; //// All sgemm kernels shall have the same arguments: (A,B,C,M,N,K,alpha,beta,lda,ldb,ldc,offa,offb,offc) for (int i=0; i<NBKernel; i++) { setKernelArg<cl_mem>(kernel[i], arg[i]++, args.A); setKernelArg<cl_mem>(kernel[i], arg[i]++, args.B); setKernelArg<cl_mem>(kernel[i], arg[i]++, args.C); setKernelArg<int>(kernel[i], arg[i]++, M); setKernelArg<int>(kernel[i], arg[i]++, N); setKernelArg<int>(kernel[i], arg[i]++, K); setKernelArg<cl_float>(kernel[i], arg[i]++, args.alpha); //if (args.beta!=0 && this->m_variantSplit->mult.compare("__ALPHA")!=0) setKernelArg<cl_float>(kernel[i], arg[i]++, args.beta); setKernelArg<int>(kernel[i], arg[i]++, lda); setKernelArg<int>(kernel[i], arg[i]++, ldb); setKernelArg<int>(kernel[i], arg[i]++, ldc); setKernelArg<int>(kernel[i], arg[i]++, offsetA); setKernelArg<int>(kernel[i], arg[i]++, offsetB); setKernelArg<int>(kernel[i], arg[i]++, offsetC); } err = KernelsLaunch(queue, kernel, args); for (int i = 0; i<NBKernel; i++) clReleaseKernel(kernel[i]) ; if (VERB) printf(" ===> ERR=%d \n",(int)err) ; // err= clFinish(queue); return clblasStatus(err) ; } #endif
29.28066
180
0.649859
JishinMaster
a07802887ca355ae2fc2f57ed4b83041e3199f5c
2,834
cpp
C++
boost/libs/signals2/test/shared_connection_block_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
boost/libs/signals2/test/shared_connection_block_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
boost/libs/signals2/test/shared_connection_block_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Boost.Signals2 library // Copyright Douglas Gregor 2001-2003. // Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #include <boost/test/minimal.hpp> #include <boost/array.hpp> #include <boost/signals2/shared_connection_block.hpp> #include <boost/signals2/signal.hpp> #include <iostream> #include <sstream> #include <string> static boost::array<boost::signals2::connection, 4> connections; static std::ostringstream test_output; struct test_slot { explicit test_slot(int v = 0) : value(v) {} void operator()() const { test_output << value; } int value; }; int test_main(int, char* []) { boost::signals2::signal<void ()> s0; for(unsigned i = 0; i < connections.size(); ++i) { connections.at(i) = s0.connect(test_slot(i)); } { // Blocking 2 boost::signals2::shared_connection_block block(connections.at(2)); BOOST_CHECK(block.blocking()); test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "013"); } // Unblocking 2 test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "0123"); { // Blocking 1 through const connection const boost::signals2::connection conn = connections.at(1); boost::signals2::shared_connection_block block(conn); test_output.str(""); s0(); std::cout << test_output.str() << std::endl; BOOST_CHECK(test_output.str() == "023"); // Unblocking 1 block.unblock(); BOOST_CHECK(block.blocking() == false); test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "0123"); } { // initially unblocked boost::signals2::shared_connection_block block(connections.at(3), false); BOOST_CHECK(block.blocking() == false); test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "0123"); // block block.block(); test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "012"); } { // test default constructed block boost::signals2::shared_connection_block block; BOOST_CHECK(block.blocking() == true); block.unblock(); BOOST_CHECK(block.blocking() == false); block.block(); BOOST_CHECK(block.blocking() == true); // test assignment { block.unblock(); boost::signals2::shared_connection_block block2(connections.at(0)); BOOST_CHECK(block.connection() != block2.connection()); BOOST_CHECK(block.blocking() != block2.blocking()); block = block2; BOOST_CHECK(block.connection() == block2.connection()); BOOST_CHECK(block.blocking() == block2.blocking()); } test_output.str(""); s0(); BOOST_CHECK(test_output.str() == "123"); } return 0; }
25.079646
77
0.647848
randolphwong
a07c721942eee27a890fa710cd23d16785c9f452
6,498
cpp
C++
roomedit/owl-6.34/source/toolbox.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
119
2015-08-19T17:57:01.000Z
2022-03-30T01:41:51.000Z
roomedit/owl-6.34/source/toolbox.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
120
2015-01-01T13:02:04.000Z
2015-08-14T20:06:27.000Z
roomedit/owl-6.34/source/toolbox.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
46
2015-08-16T23:21:34.000Z
2022-02-05T01:08:22.000Z
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1992, 1996 by Borland International, All Rights Reserved // /// \file /// Implementation of class TToolBox, a 2-d arrangement of TButtonGadgets. //---------------------------------------------------------------------------- #include <owl/pch.h> #include <owl/toolbox.h> #include <owl/buttonga.h> #include <owl/uimetric.h> namespace owl { OWL_DIAGINFO; // /// Constructs a TToolBox object with the specified number of columns and rows and /// tiling direction. Overlaps the borders of the toolbox with those of the gadget /// and sets ShrinkWrapWidth to true. // TToolBox::TToolBox(TWindow* parent, int numColumns, int numRows, TTileDirection direction, TModule* module) : TGadgetWindow(parent, direction, new TGadgetWindowFont, module) { NumRows = numRows; NumColumns = numColumns; // Make the gadget borders (if any) overlap the tool box's borders // Margins.Units = TMargins::BorderUnits; Margins.Left = Margins.Right = 0; Margins.Top = Margins.Bottom = 0; ShrinkWrapWidth = true; } // /// Overrides TGadget's Insert function and tells the button not to notch its corners. /// /// Only TButtonGadgets or derived gadgets are supported. // void TToolBox::Insert(TGadget& g, TPlacement placement, TGadget* sibling) { TGadgetWindow::Insert(g, placement, sibling); // Notch the corners if it's a buttonGadget // TButtonGadget* bg = TYPESAFE_DOWNCAST(&g,TButtonGadget); if (bg) bg->SetNotchCorners(false); } // /// Sets the direction of the tiling--either horizontal or vertical. /// /// Swap the rows & columns count, and let our base class do the rest // void TToolBox::SetDirection(TTileDirection direction) { TTileDirection dir = Direction; if (dir != direction) { int t = NumRows; NumRows = NumColumns; NumColumns = t; } TGadgetWindow::SetDirection(direction); } // // Compute the numer of rows & columns, filling in rows OR columns if left // unspecified using AS_MANY_AS_NEEDED (but not both). // void TToolBox::ComputeNumRowsColumns(int& numRows, int& numColumns) { CHECK(NumRows != AS_MANY_AS_NEEDED || NumColumns != AS_MANY_AS_NEEDED); numRows = NumRows == AS_MANY_AS_NEEDED ? (NumGadgets + NumColumns - 1) / NumColumns : NumRows; numColumns = NumColumns == AS_MANY_AS_NEEDED ? (NumGadgets + NumRows - 1) / NumRows : NumColumns; } // // Compute the cell size which is determined by the widest and the highest // gadget // void TToolBox::ComputeCellSize(TSize& cellSize) { cellSize.cx = cellSize.cy = 0; for (TGadget* g = Gadgets; g; g = g->NextGadget()) { TSize desiredSize(0, 0); g->GetDesiredSize(desiredSize); if (desiredSize.cx > cellSize.cx) cellSize.cx = desiredSize.cx; if (desiredSize.cy > cellSize.cy) cellSize.cy = desiredSize.cy; } } // /// Overrides TGadget's GetDesiredSize function and computes the size of the cell by /// calling GetMargins to get the margins. // void TToolBox::GetDesiredSize(TSize& size) { // Get border sizes // int cxBorder = 0; int cyBorder = 0; int left, right, top, bottom; GetMargins(Margins, left, right, top, bottom); size.cx = left + right; size.cy = top + bottom; // Add in this window's border size if used // if (Attr.Style & WS_BORDER) { size.cx += 2 * TUIMetric::CxBorder; size.cy += 2 * TUIMetric::CyBorder; } TSize cellSize; ComputeCellSize(cellSize); int numRows, numColumns; ComputeNumRowsColumns(numRows, numColumns); size.cx += numColumns * cellSize.cx; size.cy += numRows * cellSize.cy; // Compensate for the gadgets overlapping if UI style does that // size.cx -= (numColumns - 1) * cxBorder; size.cy -= (numRows - 1) * cyBorder; } // /// Tiles the gadgets in the direction requested (horizontal or vertical). Derived /// classes can adjust the spacing between gadgets. /// /// Horizontal direction results in a row-major layout, /// and vertical direction results in column-major layout // TRect TToolBox::TileGadgets() { TSize cellSize; ComputeCellSize(cellSize); int numRows, numColumns; ComputeNumRowsColumns(numRows, numColumns); TRect innerRect; GetInnerRect(innerRect); TRect invalidRect; invalidRect.SetEmpty(); if (Direction == Horizontal) { // Row Major // int y = innerRect.top; TGadget* g = Gadgets; for (int r = 0; r < numRows; r++) { int x = innerRect.left; for (int c = 0; c < numColumns && g; c++) { TRect bounds(TPoint(x, y), cellSize); TRect originalBounds(g->GetBounds()); if (bounds != g->GetBounds()) { g->SetBounds(bounds); if (invalidRect.IsNull()) invalidRect = bounds; else invalidRect |= bounds; if (originalBounds.TopLeft() != TPoint(0, 0)) invalidRect |= originalBounds; } x += cellSize.cx; g = g->NextGadget(); } y += cellSize.cy; } } else { // Column Major // int x = innerRect.left; TGadget* g = Gadgets; for (int c = 0; c < numColumns; c++) { int y = innerRect.top; for (int r = 0; r < numRows && g; r++) { TRect bounds(TPoint(x, y), cellSize); TRect originalBounds(g->GetBounds()); if (bounds != originalBounds) { g->SetBounds(bounds); if (invalidRect.IsNull()) invalidRect = bounds; else invalidRect |= bounds; if (originalBounds.TopLeft() != TPoint(0, 0)) invalidRect |= originalBounds; } y += cellSize.cy; g = g->NextGadget(); } x += cellSize.cx; } } return invalidRect; } // /// Called when a change occurs in the size of the margins of the tool box or size /// of the gadgets, LayoutSession gets the desired size and moves the window to /// adjust to the desired change in size. /// /// Assumes it is used as a client in a frame. // void TToolBox::LayoutSession() { TGadgetWindow::LayoutSession(); TSize sz; GetDesiredSize(sz); SetWindowPos(0, 0,0, sz.cx, sz.cy, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER); } } // OWL namespace /* ========================================================================== */
24.520755
86
0.609418
Meridian59Kor
a07efb00ea164f009470f2d0bc847752ca3aec61
1,381
cpp
C++
Other_Judges/D. Ternary Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
Other_Judges/D. Ternary Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
Other_Judges/D. Ternary Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; long long cnt(long long i, long long n, vector<long long> &dp){ if(dp[i]!=0) return dp[i]; if(i>n) return 0; long long c = 1+cnt(i*10, n, dp) + cnt(i*10+1, n, dp) + cnt(i*10+2, n, dp); dp[i] = c; return c; } int main(){ int t; scanf("%d", &t); while(t--){ int n; scanf("%d",&n); //vector<long long> dp(n, 0); //printf("%lld\n", 1+cnt(1, n, dp)); int len = log10(n)+1; int ans = 0, cnt = 0; if(n==0) ans = 1; else if(n==1) ans = 2; else if(n==2) ans = 3; else { if(len>=2){ if(len==2) ans = 3; else if(len==3) ans = 9; else if(len==4) ans = 18; else if(len ==4) ans = 27; else if(len==5) ans = 36; else if(len==6) ans = 45; else if(len==7) ans = 54; else if(len==8) ans = 63; else if(len==9) ans = 72; else if(len==10) ans = 81; else if(len==11) ans = 90; else if(len==12) ans = 99; else if(len==13) ans = 108; else if(len==14) ans = 117; else if(len==15) ans = 126; int a = n%10; n/=10; a+= 10*(n%10); if(a==0) cnt = 1; else if(a==1) cnt = 2; else if(a==2) cnt = 3; if(a<11) cnt+=1; else if(a<12) cnt+=2; else if(a<20) cnt+=3; else if(a<21) cnt+=4; else if(a<22) cnt+=5; else if(a<23) cnt+=6; } } cout<<ans<<endl; } return 0; }
18.171053
76
0.47719
Sowmik23
a0816ebccf813b8477cc26c497a9d997686e8e4a
6,931
cpp
C++
src/training/ligature_table.cpp
docu9/tesseract
3501663a33f8eccaee78027613dc204a978ee8c1
[ "Apache-2.0" ]
2
2020-10-24T09:37:45.000Z
2020-11-24T09:58:42.000Z
src/training/ligature_table.cpp
docu9/tesseract
3501663a33f8eccaee78027613dc204a978ee8c1
[ "Apache-2.0" ]
null
null
null
src/training/ligature_table.cpp
docu9/tesseract
3501663a33f8eccaee78027613dc204a978ee8c1
[ "Apache-2.0" ]
1
2020-11-30T14:09:28.000Z
2020-11-30T14:09:28.000Z
/********************************************************************** * File: ligature_table.cpp * Description: Class for adding and removing optional latin ligatures, * conditional on codepoint support by a specified font * (if specified). * Author: Ranjith Unnikrishnan * Created: Mon Nov 18 2013 * * (C) Copyright 2013, Google Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************/ #include "ligature_table.h" #include <utility> #include "pango_font_info.h" #include "tlog.h" #include <tesseract/unichar.h> #include "unicharset.h" #include "unicode/errorcode.h" // from libicu #include "unicode/normlzr.h" // from libicu #include "unicode/unistr.h" // from libicu #include "unicode/utypes.h" // from libicu namespace tesseract { static std::string EncodeAsUTF8(const char32 ch32) { UNICHAR uni_ch(ch32); return std::string(uni_ch.utf8(), uni_ch.utf8_len()); } // Range of optional latin ligature characters in Unicode to build ligatures // from. Note that this range does not contain the custom ligatures that we // encode in the private use area. const int kMinLigature = 0xfb00; const int kMaxLigature = 0xfb17; // Don't put the wide Hebrew letters in. /* static */ std::unique_ptr<LigatureTable> LigatureTable::instance_; /* static */ LigatureTable* LigatureTable::Get() { if (instance_ == nullptr) { instance_.reset(new LigatureTable()); instance_->Init(); } return instance_.get(); } LigatureTable::LigatureTable() : min_lig_length_(0), max_lig_length_(0), min_norm_length_(0), max_norm_length_(0) {} void LigatureTable::Init() { if (norm_to_lig_table_.empty()) { for (char32 lig = kMinLigature; lig <= kMaxLigature; ++lig) { // For each char in the range, convert to utf8, nfkc normalize, and if // the strings are different put the both mappings in the hash_maps. std::string lig8 = EncodeAsUTF8(lig); icu::UnicodeString unicode_lig8(static_cast<UChar32>(lig)); icu::UnicodeString normed8_result; icu::ErrorCode status; icu::Normalizer::normalize(unicode_lig8, UNORM_NFKC, 0, normed8_result, status); std::string normed8; normed8_result.toUTF8String(normed8); // The icu::Normalizer maps the "LONG S T" ligature to "st". Correct that // here manually so that AddLigatures() will work as desired. if (lig8 == "\uFB05") normed8 = "ſt"; int lig_length = lig8.length(); int norm_length = normed8.size(); if (normed8 != lig8 && lig_length > 1 && norm_length > 1) { norm_to_lig_table_[normed8] = lig8; lig_to_norm_table_[lig8] = normed8; if (min_lig_length_ == 0 || lig_length < min_lig_length_) min_lig_length_ = lig_length; if (lig_length > max_lig_length_) max_lig_length_ = lig_length; if (min_norm_length_ == 0 || norm_length < min_norm_length_) min_norm_length_ = norm_length; if (norm_length > max_norm_length_) max_norm_length_ = norm_length; } } // Add custom extra ligatures. for (int i = 0; UNICHARSET::kCustomLigatures[i][0] != nullptr; ++i) { norm_to_lig_table_[UNICHARSET::kCustomLigatures[i][0]] = UNICHARSET::kCustomLigatures[i][1]; int norm_length = strlen(UNICHARSET::kCustomLigatures[i][0]); if (min_norm_length_ == 0 || norm_length < min_norm_length_) min_norm_length_ = norm_length; if (norm_length > max_norm_length_) max_norm_length_ = norm_length; lig_to_norm_table_[UNICHARSET::kCustomLigatures[i][1]] = UNICHARSET::kCustomLigatures[i][0]; } } } std::string LigatureTable::RemoveLigatures(const std::string& str) const { std::string result; UNICHAR::const_iterator it_begin = UNICHAR::begin(str.c_str(), str.length()); UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(), str.length()); char tmp[5]; int len; for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) { len = it.get_utf8(tmp); tmp[len] = '\0'; LigHash::const_iterator lig_it = lig_to_norm_table_.find(tmp); if (lig_it != lig_to_norm_table_.end()) { result += lig_it->second; } else { result += tmp; } } return result; } std::string LigatureTable::RemoveCustomLigatures(const std::string& str) const { std::string result; UNICHAR::const_iterator it_begin = UNICHAR::begin(str.c_str(), str.length()); UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(), str.length()); char tmp[5]; int len; int norm_ind; for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) { len = it.get_utf8(tmp); tmp[len] = '\0'; norm_ind = -1; for (int i = 0; UNICHARSET::kCustomLigatures[i][0] != nullptr && norm_ind < 0; ++i) { if (!strcmp(tmp, UNICHARSET::kCustomLigatures[i][1])) { norm_ind = i; } } if (norm_ind >= 0) { result += UNICHARSET::kCustomLigatures[norm_ind][0]; } else { result += tmp; } } return result; } std::string LigatureTable::AddLigatures(const std::string& str, const PangoFontInfo* font) const { std::string result; int len = str.size(); int step = 0; int i = 0; for (i = 0; i < len - min_norm_length_ + 1; i += step) { step = 0; for (int liglen = max_norm_length_; liglen >= min_norm_length_; --liglen) { if (i + liglen <= len) { std::string lig_cand = str.substr(i, liglen); LigHash::const_iterator it = norm_to_lig_table_.find(lig_cand); if (it != norm_to_lig_table_.end()) { tlog(3, "Considering %s -> %s\n", lig_cand.c_str(), it->second.c_str()); if (font) { // Test for renderability. if (!font->CanRenderString(it->second.data(), it->second.length())) continue; // Not renderable } // Found a match so convert it. step = liglen; result += it->second; tlog(2, "Substituted %s -> %s\n", lig_cand.c_str(), it->second.c_str()); break; } } } if (step == 0) { result += str[i]; step = 1; } } result += str.substr(i, len - i); return result; } } // namespace tesseract
35.54359
80
0.620545
docu9
a081ee2288f180d2259a8eb2a234073c82f914f4
12,528
hpp
C++
FDPS-5.0g/src/memory_pool.hpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
2
2019-05-23T21:00:41.000Z
2019-10-03T18:05:20.000Z
FDPS-5.0g/src/memory_pool.hpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
null
null
null
FDPS-5.0g/src/memory_pool.hpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
10
2018-08-22T00:55:26.000Z
2022-02-28T23:21:42.000Z
#include<iostream> #include<cstdlib> #include<cassert> #include<vector> #if defined(PARTICLE_SIMULATOR_THREAD_PARALLEL) && defined(_OPENMP) #include<omp.h> #endif namespace ParticleSimulator{ class MemoryPool{ private: enum{ ALIGN_SIZE = 8, N_SEGMENT_LIMIT = 10000, }; typedef struct { void * data; size_t cap; bool used; void * ptr_data; void * ptr_id_mpool; } EmergencyBuffer; MemoryPool(){} ~MemoryPool(){} MemoryPool(const MemoryPool & mem); MemoryPool & operator = (const MemoryPool & mem); void * bottom_; void * top_; size_t cap_; size_t size_; size_t n_segment_; size_t cap_per_seg_[N_SEGMENT_LIMIT]; bool used_per_seg_[N_SEGMENT_LIMIT]; void * ptr_data_per_seg_[N_SEGMENT_LIMIT]; std::vector<EmergencyBuffer> emerg_bufs_; static MemoryPool & getInstance(){ static MemoryPool inst; return inst; } static size_t getAlignSize(const size_t _size){ return (((_size-1)/ALIGN_SIZE)+1)*ALIGN_SIZE; } static bool isLastSegment(const int id_seg) { if (id_seg < N_SEGMENT_LIMIT && getInstance().n_segment_ > 0 && (size_t)id_seg == getInstance().n_segment_-1) { return true; } else { return false; } } static bool inParallelRegion() { #if defined(PARTICLE_SIMULATOR_THREAD_PARALLEL) && defined(_OPENMP) const int n_thread = omp_get_num_threads(); #else const int n_thread = 1; #endif if (n_thread > 1) return true; else return false; } public: static size_t getNSegment(){ return getInstance().n_segment_; } static size_t getSize(){ return getInstance().size_; } static void initialize(const size_t _cap){ getInstance().cap_ = _cap; getInstance().size_ = 0; getInstance().bottom_ = malloc(getInstance().cap_); if (getInstance().bottom_ != NULL) { getInstance().top_ = getInstance().bottom_; getInstance().n_segment_ = 0; for(size_t i=0; i<N_SEGMENT_LIMIT; i++){ getInstance().cap_per_seg_[i] = 0; getInstance().used_per_seg_[i] = false; } } else { std::cerr << "PS_ERROR: malloc failed. (function: " << __func__ << ", line: " << __LINE__ << ", file: " << __FILE__ << ")" <<std::endl; #if defined(PARTICLE_SIMULATOR_MPI_PARALLEL) MPI_Abort(MPI_COMM_WORLD,-1); #endif std::exit(-1); } } static void reInitialize(const size_t size_add){ const size_t cap_old = getInstance().cap_; const size_t cap_new = getInstance().getAlignSize( cap_old+size_add ); void * bottom_old = getInstance().bottom_; void * bottom_new = malloc(cap_new); if (bottom_new != NULL) { getInstance().bottom_ = bottom_new; const size_t diff = (size_t)getInstance().top_ - (size_t)bottom_old; getInstance().top_ = (void*)((char*)bottom_new + diff); getInstance().cap_ = cap_new; memcpy(bottom_new, bottom_old, cap_old); size_t cap_cum = 0; for(size_t i=0; i<getInstance().n_segment_; i++){ void * p_new = (void*)((char*)bottom_new + cap_cum); if (getInstance().used_per_seg_[i]) { memcpy(getInstance().ptr_data_per_seg_[i], &p_new, sizeof(void*)); } cap_cum += getInstance().cap_per_seg_[i]; } if (bottom_old != NULL) free(bottom_old); } else { std::cerr << "PS_ERROR: malloc failed. (function: " << __func__ << ", line: " << __LINE__ << ", file: " << __FILE__ << ")" <<std::endl; #if defined(PARTICLE_SIMULATOR_MPI_PARALLEL) MPI_Abort(MPI_COMM_WORLD,-1); #endif std::exit(-1); } } static void unifyMem() { const int n_emerg_bufs = getInstance().emerg_bufs_.size(); if (!inParallelRegion() && n_emerg_bufs > 0) { size_t size_add = 0; for (int i=0; i<n_emerg_bufs; i++) { if (getInstance().emerg_bufs_[i].used) size_add += getInstance().emerg_bufs_[i].cap; } if (getInstance().cap_ < getInstance().size_ + size_add) { reInitialize(size_add); } for (int i=0; i<n_emerg_bufs; i++) { if (!getInstance().emerg_bufs_[i].used) continue; void * data = getInstance().emerg_bufs_[i].data; const size_t cap = getInstance().emerg_bufs_[i].cap; void * ptr_data = getInstance().emerg_bufs_[i].ptr_data; void * ptr_id_mpool = getInstance().emerg_bufs_[i].ptr_id_mpool; void * top_prev = getInstance().top_; // Copy a single emergency buffer to the segment at the tail getInstance().top_ = (void *)((char*)getInstance().top_ + cap); getInstance().size_ += cap; getInstance().cap_per_seg_[getInstance().n_segment_] = cap; getInstance().used_per_seg_[getInstance().n_segment_] = true; getInstance().ptr_data_per_seg_[getInstance().n_segment_] = ptr_data; const int id_mpool = getInstance().n_segment_; getInstance().n_segment_++; memcpy(top_prev, data, cap); memcpy(ptr_data, &top_prev, sizeof(void *)); memcpy(ptr_id_mpool, &id_mpool, sizeof(int)); } // Release emergency buffers for (int i=0; i<n_emerg_bufs; i++) { if (getInstance().emerg_bufs_[i].data != NULL) free(getInstance().emerg_bufs_[i].data); } getInstance().emerg_bufs_.clear(); } } static void alloc(const size_t _size, int & _id_mpool, void * ptr_data, void *& ret){ if(_size <= 0) return; unifyMem(); const size_t size_align = getAlignSize(_size); size_t cap_cum = 0; bool flag_break = false; for(size_t i=0; i<getInstance().n_segment_; i++){ if( !getInstance().used_per_seg_[i] && getInstance().cap_per_seg_[i] >= size_align){ // insert to middle getInstance().used_per_seg_[i] = true; getInstance().ptr_data_per_seg_[i] = ptr_data; _id_mpool = i; ret = (void*)((char*)getInstance().bottom_ + cap_cum); flag_break = true; break; } cap_cum += getInstance().cap_per_seg_[i]; } if(!flag_break){ // In this case, we add a new segment to the tail of the memory pool assert(N_SEGMENT_LIMIT > getInstance().n_segment_+1); // Delete the last segment first if _id_mpool points to the last segment. if (isLastSegment(_id_mpool)) { getInstance().n_segment_--; getInstance().top_ = ((char*)getInstance().top_) - getInstance().cap_per_seg_[getInstance().n_segment_]; getInstance().size_ = getInstance().size_ - getInstance().cap_per_seg_[getInstance().n_segment_]; getInstance().cap_per_seg_[getInstance().n_segment_] = 0; getInstance().used_per_seg_[getInstance().n_segment_] = false; getInstance().ptr_data_per_seg_[getInstance().n_segment_] = NULL; } // Choose an operation mode bool flag_realloc = false; if (getInstance().cap_ < getInstance().size_ + size_align) flag_realloc = true; bool flag_use_emerg_bufs = false; if (flag_realloc && inParallelRegion()) flag_use_emerg_bufs = true; // Add a new segment to the tail of the memory pool. if (!flag_use_emerg_bufs) { if(flag_realloc) reInitialize(size_align); void * top_prev = getInstance().top_; getInstance().top_ = ((char*)getInstance().top_) + size_align; getInstance().size_ += size_align; getInstance().cap_per_seg_[getInstance().n_segment_] = size_align; getInstance().used_per_seg_[getInstance().n_segment_] = true; getInstance().ptr_data_per_seg_[getInstance().n_segment_] = ptr_data; _id_mpool = getInstance().n_segment_; getInstance().n_segment_++; ret = top_prev; } else { int n_emerg_bufs = getInstance().emerg_bufs_.size(); // Newly create an emergency buffer const int idx = n_emerg_bufs; n_emerg_bufs++; getInstance().emerg_bufs_.reserve(n_emerg_bufs); getInstance().emerg_bufs_.resize(n_emerg_bufs); void * data = malloc(size_align); if (data != NULL) { getInstance().emerg_bufs_[idx].data = data; getInstance().emerg_bufs_[idx].cap = size_align; getInstance().emerg_bufs_[idx].used = true; getInstance().emerg_bufs_[idx].ptr_data = ptr_data; getInstance().emerg_bufs_[idx].ptr_id_mpool = &_id_mpool; _id_mpool = idx + N_SEGMENT_LIMIT; ret = getInstance().emerg_bufs_[idx].data; } else { std::cerr << "PS_ERROR: malloc failed. (function: " << __func__ << ", line: " << __LINE__ << ", file: " << __FILE__ << ")" <<std::endl; #if defined(PARTICLE_SIMULATOR_MPI_PARALLEL) MPI_Abort(MPI_COMM_WORLD,-1); #endif std::exit(-1); } } } } static void freeMem(const int id_seg){ if(getInstance().cap_per_seg_[id_seg] <= 0) return; if (id_seg < N_SEGMENT_LIMIT) { getInstance().used_per_seg_[id_seg] = false; if((size_t)id_seg == getInstance().n_segment_-1){ for(int i=id_seg; i>=0; i--){ if(getInstance().used_per_seg_[i] == true) break; getInstance().size_ -= getInstance().cap_per_seg_[i]; getInstance().cap_per_seg_[i] = 0; getInstance().ptr_data_per_seg_[i] = NULL; getInstance().n_segment_--; } } getInstance().top_ = ((char*)getInstance().bottom_) + getInstance().size_; } else { const int idx = id_seg - N_SEGMENT_LIMIT; getInstance().emerg_bufs_[idx].used = false; } unifyMem(); } static void dump(){ std::cerr<<"bottom_= "<<getInstance().bottom_<<std::endl; std::cerr<<"top_= "<<getInstance().top_<<std::endl; std::cerr<<"cap_= "<<getInstance().cap_<<std::endl; std::cerr<<"size_= "<<getInstance().size_<<std::endl; std::cerr<<"n_segment= "<<getInstance().n_segment_<<std::endl; for(size_t i=0; i<getInstance().n_segment_; i++){ std::cerr<<"i= "<<i <<" cap= "<<getInstance().cap_per_seg_[i] <<" used= "<<getInstance().used_per_seg_[i] <<std::endl; } } }; }
45.064748
125
0.501117
subarutaro
a08335befa113d1a7b12dfe8517535383abdebbd
6,966
hpp
C++
includes/ConfigParser.hpp
majermou/webserv
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
[ "MIT" ]
null
null
null
includes/ConfigParser.hpp
majermou/webserv
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
[ "MIT" ]
null
null
null
includes/ConfigParser.hpp
majermou/webserv
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
[ "MIT" ]
1
2021-12-13T10:35:06.000Z
2021-12-13T10:35:06.000Z
#ifndef CONFIG_PARSER_HPP #define CONFIG_PARSER_HPP #include "ServerData.hpp" #include "Webserv.hpp" // fields identifiers fields definitions // server file configuration requirements openings #define SERVER_OP "server" #define PORT_OP "listen" #define HOST_OP "host" #define SERVER_NAME_OP "server_name" #define CLIENT_MAX_SIZE_BODY_OP "client_max_body_size" #define ERROR_PAGE_OP "error_page" #define ROOT_OP "root" #define LOCATION_OP "location" // location content fields identifiers #define LOC_PATH "loc_path" #define LOC_ROOT "root" #define LOC_AUTOINDEX "autoindex" #define LOC_INDEX "index" #define LOC_ALLOWED_METHODS "allow_methods" #define LOC_RETURN "return" #define LOC_CGI "fastcgi_pass" #define UPLOAD_LOC_ENABLE "upload_enable" #define UPLOAD_LOC_STORE "upload_store" #define NUMBER_OF_SERVER_PRIMITIVES 7 #define NUMBER_OF_LOCATION_PRIMITIVES 8 #define OPENNING_BRACE "{" #define CLOSING_BRACE "}" #define OPENNING_BRACKET '[' #define CLOSING_BRACKET ']' #define PHP_EXTENTION ".php" #define PYTHON_EXTENTION ".py" #define LOCALHOST "127.0.0.1" // error messages #define ERROR_FILE "Could not open configuration file" #define ERROR_FILE_EXTENSION \ "Configuration file has not the correct extension [.conf]" #define ERROR_BRACES \ "Curly braces are not written well in the configuration file or a server " \ "identifier used with no definition" #define ERROR_OPENING_BRACE_WITHOUT_SERVER_OR_LOC \ "Opening curly brace used without setting server or location identifier " \ "above it." #define ERROR_DOUBLE_BRACE "Only one curly brace is allowed per line" #define ERROR_BRACE_NOT_ALONE \ "The line which contains a curly brace must not contain something else: " \ "Error in this line -> " #define ERROR_DEFINE_SERVER_INSIDE_SERVER \ "You can't define a server inside another server" #define ERROR_EMPTY_SERVER_CONFIGURATION \ "A server must not have an empty configuration" #define ERROR_INVALID_CONFIGURATION \ "This configuration file is invalid: ERROR in this line -> " #define ERROR_EMPTY_CONFIGURATION \ "Your file does not contains any server configuration" #define ERROR_MISSING_ELEMENTS " necessary missing elements: " #define ERROR_MISSING_SEMICOLON "Missing a semicolon in this line: " #define ERROR_DOUBLE_SEMICOLON \ "Should be only one semicolon at the end of this line: " #define ERROR_PORT_NAN "The port value must be a positive number" #define ERROR_CLIENT_BODY_SIZE_UNITY \ "The client max body size must end with 'm' (refers to megabytes) as its " \ "unity" #define ERROR_CLIENT_BODY_SIZE_NAN \ "The value of client max body size must be a non-zero positive number" #define ERROR_ERRPAGE_CODE_NAN \ "The value of an error page code must be a non-zero positive number" #define ERROR_ALLOWED_METHODS_SYNTAX "Bad syntax for allowed methods in line: " #define ERROR_ALLOWED_METHOD_METHOD_NOT_FOUND \ "This method is not one of the webserv allowed methods: [ GET, POST, " \ "DELETE ], Error in this line: " #define ERROR_SERVER_DUPLICATE_FIELD "Duplicate server field in this line -> " #define ERROR_LOCATION_DUPLICATE_FIELD \ "Duplicate location field in this line -> " #define ERROR_EMPTY_LOCATION_CONFIG \ "The file configuration has an empty location configuration for this " \ "location-> " #define ERROR_LOCATION_WITH_SEMICOLON \ "Location field does not end with a semicolon: error in this line -> " #define ERROR_RETURN_CODE_NAN \ "The value of redirection code must be a non-zero positive number" #define ERROR_CGI_EXTENSION_ERROR \ "The CGI extension is invalid, it must be in this format: *.extention , " \ "e.g. *.php, *.py, Error in this line: " #define ERROR_CGI_NOT_FOUND \ "The fastcgi_pass field is not found after setting the cgi extension" #define DID_YOU_MEAN "Did you mean " #define IN_THIS_LINE " field in this line -> " #define ERROR_DUPLICATE_SERVER_NAME \ "Try to use a unique name for each server: duplicate name -> " #define ERROR_DUPLICATE_SERVER_HOST_AND_PORT \ "Two servers cannot have the same host and port, at least one must " \ "differ.duplicate host and port: " #define ERROR_INVALID_IDENTIFIER "Invalid identifier: in this line -> " #define CGI_NOT_SUPPORTED \ "Only these extensions are supported for CGI: [.php] and [.py], Error in " \ "this line:[ location " class ConfigParser { private: // attributes char const *_filename; std::vector<ServerData> _servers; std::vector<std::string> _fileLines; std::vector<int> _serversIndexing; std::map<std::string, bool> _checked_primitives; std::map<std::string, bool> _checked_location_primitives; // methods void _trim(std::string &); std::vector<std::string> _split(std::string const &); std::vector<std::string> _split(std::string const &, char); bool _isSet(std::string const &, int (*func)(int)); std::string const &_removeDuplicateChar(std::string &, char const); void _semicolonChecker(std::string &); void _getFileContent(); void _indexServers(); int _isPrimitive(std::string const &); int _isLocationPrimitive(std::string const &); void _parseArguments(int ac, char *av[]); // partial server fields parsers int _portParser(size_t, ServerData &); int _hostParser(size_t, ServerData &); int _serverNameParser(size_t, ServerData &); int _clientBodySizeParser(size_t, ServerData &); int _errorPageParser(size_t, ServerData &); int _rootDirParser(size_t, ServerData &); // partial server location fields parsers void _locationPathParser(size_t &, Location &); void _locRootDirParser(size_t, Location &); void _locAutoIndexParser(size_t, Location &); void _locIndexParser(size_t, Location &); void _locAllowedMethodsParser(size_t, Location &); void _locRedirectionParser(size_t, Location &); void _locUploadEnableParser(size_t, Location &); void _locUploadLocationParser(size_t, Location &); bool _isCGIsupportedExtension(std::string const &); void _locCGIParser(size_t, Location &); int _locationParser(size_t, ServerData &); void _parseContent(); void addServer(ServerData const &); public: ConfigParser(int ac, char *av[]); std::vector<ServerData> getServers() const; ~ConfigParser(); static std::string const primitives_openings[NUMBER_OF_SERVER_PRIMITIVES]; static std::string const location_identifiers[NUMBER_OF_LOCATION_PRIMITIVES]; }; typedef int (ConfigParser::*ParserFuncPtr)(size_t, ServerData &); typedef void (ConfigParser::*LocationFieldParserFuncPtr)(size_t, Location &); #endif // !CONFIG_PARSER_HPP
40.5
80
0.715619
majermou
a0863c63ed5d317b45a1756d93d0f7d4248ca2f7
8,858
cpp
C++
admin/wmi/wbem/providers/snmpprovider/common/sclcomm/window.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/snmpprovider/common/sclcomm/window.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/snmpprovider/common/sclcomm/window.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved /*--------------------------------------------------------- Filename: window.cpp Written By: B.Rajeev ----------------------------------------------------------*/ #include "precomp.h" #include "common.h" #include "timer.h" #include "window.h" extern HINSTANCE g_hInst ; WindowMapping Window::mapping; CriticalSection Window::window_CriticalSection; UINT Window :: g_TimerMessage = SNMP_WM_TIMER ; UINT Window :: g_SendErrorEvent = SEND_ERROR_EVENT ; UINT Window :: g_OperationCompletedEvent = OPERATION_COMPLETED_EVENT ; UINT Window :: g_MessageArrivalEvent = MESSAGE_ARRIVAL_EVENT ; UINT Window :: g_SentFrameEvent = SENT_FRAME_EVENT ; UINT Window :: g_NullEventId = NULL_EVENT_ID ; UINT Window :: g_DeleteSessionEvent = DELETE_SESSION_EVENT ; BOOL WaitPostMessage ( HWND window , UINT user_msg_id, WPARAM wParam, LPARAM lParam ) { BOOL status = FALSE ; while ( ! status ) { status = :: PostMessage ( window , user_msg_id, wParam, lParam ) ; if ( status ) { return status ; } DWORD lastError = GetLastError () ; if ( lastError != E_OUTOFMEMORY ) { TerminateProcess ( GetCurrentProcess () , lastError ) ; } } return FALSE ; } Window::Window ( char *templateCode, BOOL display ) : window_handle ( NULL ) { // is invalid is_valid = FALSE; // initialize the window Initialize ( templateCode, HandleGlobalEvent, display ) ; // if handle is null, return if ( window_handle == NULL ) return; is_valid = TRUE; } LONG_PTR CALLBACK WindowsMainProc ( HWND hWnd, UINT message , WPARAM wParam , LPARAM lParam ) { return DefWindowProc(hWnd, message, wParam, lParam); } BOOL Window::CreateCriticalSection () { return TRUE ; } void Window::DestroyCriticalSection() { } void Window::Initialize ( char *templateCode, WNDPROC EventHandler, BOOL display ) { WNDCLASS wc ; wc.style = CS_HREDRAW | CS_VREDRAW ; wc.lpfnWndProc = EventHandler ; wc.cbClsExtra = 0 ; wc.cbWndExtra = 0 ; wc.hInstance = g_hInst ; wc.hIcon = LoadIcon(NULL, IDI_HAND) ; wc.hCursor = LoadCursor(NULL, IDC_ARROW) ; wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1) ; wc.lpszMenuName = NULL ; wc.lpszClassName = L"templateCode" ; ATOM winClass = RegisterClass ( &wc ) ; if ( ! winClass ) { DWORD t_GetLastError = GetLastError () ; DebugMacro4( SnmpDebugLog :: s_SnmpDebugLog->WriteFileAndLine ( __FILE__,__LINE__, L"Window::Initialise: Error = %lx\n" , t_GetLastError ) ; ) } window_handle = CreateWindow ( L"templateCode" , // see RegisterClass() call L"templateCode" , // text for window title bar WS_OVERLAPPEDWINDOW , // window style CW_USEDEFAULT , // default horizontal position CW_USEDEFAULT , // default vertical position CW_USEDEFAULT , // default width CW_USEDEFAULT , // default height NULL , // overlapped windows have no parent NULL , // use the window class menu g_hInst, // instance (0 is used) NULL // pointer not needed ) ; if ( window_handle == NULL ) return; // obtain lock CriticalSectionLock lock(window_CriticalSection); // if cannot obtain lock, destroy the window // since the window cannot be registered, future messages to // it cannot be passed to it for processing if ( !lock.GetLock(INFINITE) ) { DestroyWindow(window_handle); window_handle = NULL; return; } // register the window with the mapping // (HWND,event_handler) try { mapping[window_handle] = this; } catch ( Heap_Exception e_He ) { DestroyWindow(window_handle); window_handle = NULL; return ; } // release lock lock.UnLock(); if ( display == TRUE ) { ShowWindow ( window_handle , SW_SHOW ) ; } } BOOL Window::InitializeStaticComponents() { return CreateCriticalSection(); } void Window::DestroyStaticComponents() { DestroyCriticalSection(); } // it determines the corresponding EventHandler and calls it // with the appropriate parameters LONG_PTR CALLBACK Window::HandleGlobalEvent ( HWND hWnd , UINT message , WPARAM wParam , LPARAM lParam ) { LONG_PTR rc = 0 ; // send timer events to the Timer if ( message == WM_TIMER ) { #if 1 UINT timerId = ( UINT ) wParam ; SnmpTimerObject *timerObject ; CriticalSectionLock session_lock(Timer::timer_CriticalSection); if ( !session_lock.GetLock(INFINITE) ) throw GeneralException ( Snmp_Error , Snmp_Local_Error,__FILE__,__LINE__ ) ; if ( SnmpTimerObject :: timerMap.Lookup ( timerId , timerObject ) ) { SnmpTimerObject :: TimerNotification ( timerObject->GetHWnd () , timerId ) ; } else { } #else UINT timerId = ( UINT ) wParam ; SnmpTimerObject *timerObject ; CriticalSectionLock session_lock(Timer::timer_CriticalSection); if ( !session_lock.GetLock(INFINITE) ) throw GeneralException ( Snmp_Error , Snmp_Local_Error,__FILE__,__LINE__ ) ; if ( SnmpTimerObject :: timerMap.Lookup ( timerId , timerObject ) ) { Timer::HandleGlobalEvent(timerObject->GetHWnd (), Timer :: g_SnmpWmTimer, timerId, lParam); } else { } #endif return rc ; } if ( message == Timer :: g_SnmpWmTimer ) { Timer::HandleGlobalEvent( hWnd, message, wParam, (DWORD)lParam ); return rc; } Window *window; // obtain lock CriticalSectionLock lock(window_CriticalSection); // if cannot obtain lock, print a debug error message // and return if ( !lock.GetLock(INFINITE) ) { DebugMacro4( SnmpDebugLog :: s_SnmpDebugLog->WriteFileAndLine ( __FILE__,__LINE__, L"Window::HandleGlobalEvent: ignoring window message (unable to obtain lock)\n" ) ; ) return rc; } BOOL found = mapping.Lookup(hWnd, window); // release lock lock.UnLock(); // if no such window, return if ( !found ) return DefWindowProc(hWnd, message, wParam, lParam); // let the window handle the event return window->HandleEvent(hWnd, message, wParam, lParam); } // calls the default handler // a deriving class may override this, but // must call this method explicitly for default // case handling LONG_PTR Window::HandleEvent ( HWND hWnd , UINT message , WPARAM wParam , LPARAM lParam ) { return DefWindowProc ( hWnd , message , wParam , lParam ); } bool WaitLock ( CriticalSectionLock &a_Lock , BOOL a_WaitCritical = TRUE ) { SetStructuredExceptionHandler t_StructuredException ; BOOL t_Do ; do { try { a_Lock.GetLock(INFINITE) ; return true ; } catch ( Structured_Exception & t_StructuredException ) { #ifdef DBG OutputDebugString ( L"CriticalSection exception" ) ; #endif t_Do = a_WaitCritical ; if ( t_Do ) { Sleep ( 1000 ) ; } if ( t_StructuredException.GetSENumber () == STATUS_NO_MEMORY ) { } else { return false ; } } catch ( ... ) { return false ; } } while ( t_Do ) ; return true ; } Window::~Window(void) { if ( window_handle != NULL ) { // obtain lock CriticalSectionLock lock(window_CriticalSection); if ( WaitLock ( lock ) ) { mapping.RemoveKey(window_handle); } else { throw GeneralException ( Snmp_Error , Snmp_Local_Error,__FILE__,__LINE__ ) ; } // release lock lock.UnLock(); DestroyWindow(window_handle); UnregisterClass ( L"templateCode" , 0 ) ; } } BOOL Window::PostMessage( UINT user_msg_id, WPARAM wParam, LPARAM lParam ) { return WaitPostMessage(GetWindowHandle(), user_msg_id, wParam, lParam); }
22.200501
104
0.569767
npocmaka
a08a5e12322ec37a4c6fb8a1fac9ced049d6c33d
2,486
cpp
C++
UnitTest/UnitTestCollection/FixedAccuracy/T_PowX.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
null
null
null
UnitTest/UnitTestCollection/FixedAccuracy/T_PowX.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
1
2019-01-14T04:00:23.000Z
2019-01-14T04:00:23.000Z
UnitTest/UnitTestCollection/FixedAccuracy/T_PowX.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved. This software is subject to the Apache v2.0 License. */ #include "UnitTestFramework.h" #include "FixedAccuracy.h" #include "FunctionSignatures.h" #include "fwSignal.h" class TestPowx_32f_A11 : public SrcConstDstLen< F32,F32 > { public: TestPowx_32f_A11( UnitTestCatalogBase & parent ) : SrcConstDstLen< F32,F32 >( parent, "fwsPowx_32f_A11", fwsPowx_32f_A11 ) {} virtual void RunAll() { int len = 8; F32 cval = 2; RunTest( "1 2.456783 3 4 5 6 7 8", cval, "1 6.0357828 9 16 25 36 49 64",len); } }; class TestPowx_32f_A21 : public SrcConstDstLen< F32,F32 > { public: TestPowx_32f_A21( UnitTestCatalogBase & parent ) : SrcConstDstLen< F32,F32 >( parent, "fwsPowx_32f_A21", fwsPowx_32f_A21 ) {} virtual void RunAll() { int len = 8; F32 cval = 2; RunTest( "1 2.456783 3 4 5 6 7 8", cval, "1 6.0357828 9 16 25 36 49 64",len); } }; class TestPowx_32f_A24 : public SrcConstDstLen< F32,F32 > { public: TestPowx_32f_A24( UnitTestCatalogBase & parent ) : SrcConstDstLen< F32,F32 >( parent, "fwsPowx_32f_A24", fwsPowx_32f_A24 ) {} virtual void RunAll() { int len = 8; F32 cval = 2; RunTest( "1 2.456783 3 4 5 6 7 8", cval, "1 6.0357827090890011 9 16 25 36 49 64",len); } }; class TestPowx_64f_A50 : public SrcConstDstLen< F64,F64 > { public: TestPowx_64f_A50( UnitTestCatalogBase & parent ) : SrcConstDstLen< F64,F64 >( parent, "fwsPowx_64f_A50", fwsPowx_64f_A50 ) {} virtual void RunAll() { int len = 8; F32 cval = 2; RunTest( "1 2.456783 3 4 5 6 7 8", cval, "1 6.0357827090890011 9 16 25 36 49 64",len); } }; class TestPowx_64f_A53 : public SrcConstDstLen< F64,F64 > { public: TestPowx_64f_A53( UnitTestCatalogBase & parent ) : SrcConstDstLen< F64,F64 >( parent, "fwsPowx_64f_A53", fwsPowx_64f_A53 ) {} virtual void RunAll() { int len = 8; F32 cval = 2; RunTest( "1 2.456783 3 4 5 6 7 8", cval, "1 6.0357827090890011 9 16 25 36 49 64",len); } }; DEFINE_TEST_TABLE( PowXTestCatalog ) TEST_ENTRY( TestPowx_32f_A11 ) TEST_ENTRY( TestPowx_32f_A21 ) TEST_ENTRY( TestPowx_32f_A24 ) TEST_ENTRY( TestPowx_64f_A50 ) TEST_ENTRY( TestPowx_64f_A53 ) END_TEST_TABLE()
24.135922
95
0.619871
dbremner
a08befae821f0be9f8724a9a6ca6be58539b3edb
551
cpp
C++
test/CErrRedirecter.cpp
asura/logger
3bbf95dd30adb32110855ac78d4055511bf43970
[ "MIT" ]
null
null
null
test/CErrRedirecter.cpp
asura/logger
3bbf95dd30adb32110855ac78d4055511bf43970
[ "MIT" ]
9
2019-09-15T21:29:20.000Z
2019-10-16T18:15:04.000Z
test/CErrRedirecter.cpp
asura/logger
3bbf95dd30adb32110855ac78d4055511bf43970
[ "MIT" ]
null
null
null
#include "CErrRedirecter.h" #include <cassert> #include <cstring> // memset #include <iostream> CErrRedirecter::CErrRedirecter() : m_locker(m_mutex) , m_fp(open_memstream(&m_buffer, &m_size)) , m_buffer(nullptr) , m_size(0) , m_old(stderr) { if (!m_fp) { throw std::runtime_error("open_memstream failed"); } assert(m_old != nullptr); stderr = m_fp; } CErrRedirecter::~CErrRedirecter() { stderr = m_old; std::fclose(m_fp); if (m_buffer != nullptr) { free(m_buffer); } }
16.69697
58
0.607985
asura
a08cc2d0ce250e2de1602d71d894615a3108c1b4
13,519
cpp
C++
src/Framework/Graphics.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Graphics.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Graphics.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
#include "Graphics.hpp" #include <glad/glad.h> #include <glm/gtc/type_ptr.hpp> #include <iostream> #define ASSERT(expr) assert(expr) bool CheckGLError() { GLenum err; while ((err = glGetError()) != GL_NO_ERROR) switch (err) { case GL_INVALID_ENUM: std::cout << "GL_INVALID_ENUM" << std::endl; return false; case GL_INVALID_VALUE: std::cout << "GL_INVALID_VALUE" << std::endl; return false; case GL_INVALID_OPERATION: std::cout << "GL_INVALID_OPERATION" << std::endl; return false; case GL_INVALID_FRAMEBUFFER_OPERATION: std::cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << std::endl; return false; case GL_OUT_OF_MEMORY: std::cout << "GL_OUT_OF_MEMORY" << std::endl; return false; } return true; } bool CheckShaderStatus(Shader shader, bool linked) { ASSERT(shader != 0); int success; char infoLog[512]; if (!linked) { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 512, NULL, infoLog); std::cout << "COMPILATION_FAILED:\n" << infoLog << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 512, NULL, infoLog); std::cout << "LINKING_FAILED:\n" << infoLog << std::endl; } } return success; } void Graphics::Initialize() { gladLoadGL(); } void Graphics::SetViewport(float x, float y, float width, float height) { glViewport(x, y, width, height); ASSERT(CheckGLError()); } void Graphics::SetClearColor(float r, float g, float b, float a) { glClearColor(r, g, b, a); ASSERT(CheckGLError()); } void Graphics::SetClearDepth(float depth) { glClearDepth(depth); ASSERT(CheckGLError()); } void Graphics::SetClearStencil(unsigned int mask) { glStencilMask(mask); ASSERT(CheckGLError()); } void Graphics::ClearScreen(bool color, bool depth, bool stencil) { GLbitfield mask = 0; mask |= color ? GL_COLOR_BUFFER_BIT : 0; mask |= depth ? GL_DEPTH_BUFFER_BIT : 0; mask |= stencil ? GL_STENCIL_BUFFER_BIT : 0; glClear(mask); ASSERT(CheckGLError()); } void Graphics::SetCull(bool enable) { if (enable) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); ASSERT(CheckGLError()); } void Graphics::SetCullFace(CullFace face) { switch (face) { case CullFace::FRONT: glCullFace(GL_FRONT); break; case CullFace::BACK: glCullFace(GL_BACK); break; case CullFace::BOTH: glCullFace(GL_FRONT_AND_BACK); break; } ASSERT(CheckGLError()); } void Graphics::SetFaceWinding(bool ccw) { if (ccw) glFrontFace(GL_CCW); else glFrontFace(GL_CW); ASSERT(CheckGLError()); } void Graphics::SetBlend(bool enable) { if (enable) glEnable(GL_BLEND); else glDisable(GL_BLEND); ASSERT(CheckGLError()); } void Graphics::SetBlendFunc(BlendFunc func) { switch (func) { case BlendFunc::ADD: glBlendFunc(GL_ONE, GL_ONE); break; case BlendFunc::MULTIPLY: glBlendFunc(GL_DST_COLOR, GL_ZERO); break; case BlendFunc::INTERPOLATE: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } ASSERT(CheckGLError()); } void Graphics::SetDepthTest(bool enable) { if (enable) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); ASSERT(CheckGLError()); } void Graphics::SetDepthWrite(bool enable) { glDepthMask(enable); ASSERT(CheckGLError()); } void Graphics::SetDepthFunc(DepthFunc func) { switch (func) { case DepthFunc::NEVER: glDepthFunc(GL_NEVER); break; case DepthFunc::LESS: glDepthFunc(GL_LESS); break; case DepthFunc::EQUAL: glDepthFunc(GL_EQUAL); break; case DepthFunc::LEQUAL: glDepthFunc(GL_LEQUAL); break; case DepthFunc::GREATER: glDepthFunc(GL_GREATER); break; case DepthFunc::NOTEQUAL: glDepthFunc(GL_NOTEQUAL); break; case DepthFunc::GEQUAL: glDepthFunc(GL_GEQUAL); break; case DepthFunc::ALWAYS: glDepthFunc(GL_ALWAYS); break; } ASSERT(CheckGLError()); } void Graphics::SetSmoothing(bool enable) { if (enable) { glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); } else { glDisable(GL_LINE_SMOOTH); glDisable(GL_POLYGON_SMOOTH); } ASSERT(CheckGLError()); } Buffer Graphics::CreateBuffer(int bufferCount, int dataCount, const void* data, bool index, bool dynamic) { Buffer buffer; glGenBuffers(bufferCount, &buffer); if (index) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, dataCount * sizeof(unsigned int), data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } else { glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, dataCount * sizeof(float), data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } ASSERT(CheckGLError()); return buffer; } void Graphics::DeleteBuffer(int count, Buffer buffer) { ASSERT(buffer != 0); glDeleteBuffers(count, &buffer); buffer = 0; ASSERT(CheckGLError()); } void Graphics::UpdateBuffer(Buffer buffer, int count, const void* data, bool index) { ASSERT(buffer != 0); // TODO ASSERT(CheckGLError()); } void Graphics::BindBuffer(Buffer buffer, bool index) { ASSERT(buffer != 0); if (index) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); else glBindBuffer(GL_ARRAY_BUFFER, buffer); ASSERT(CheckGLError()); } void Graphics::DetachBuffer() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); ASSERT(CheckGLError()); } Shader Graphics::CreateShader(const char* vSrc, const char* pSrc, const char* gSrc) { ASSERT(vSrc != nullptr); ASSERT(pSrc != nullptr); Shader vShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vShader, 1, &vSrc, NULL); glCompileShader(vShader); ASSERT(CheckShaderStatus(vShader, false)); Shader pShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(pShader, 1, &pSrc, NULL); glCompileShader(pShader); ASSERT(CheckShaderStatus(pShader, false)); Shader program = glCreateProgram(); glAttachShader(program, vShader); glAttachShader(program, pShader); glLinkProgram(program); ASSERT(CheckShaderStatus(program, true)); glDeleteShader(vShader); glDeleteShader(pShader); ASSERT(CheckGLError()); return program; } void Graphics::DeleteShader(Shader shader) { ASSERT(shader != 0); glDeleteShader(shader); ASSERT(CheckGLError()); } void Graphics::BindShader(Shader shader, const std::vector<AttributeFormat>& attributeFormat) { ASSERT(shader != 0); glUseProgram(shader); int stride = 0; for (int i = 0; i < attributeFormat.size(); ++i) stride += attributeFormat[i].format; stride *= sizeof(float); int offset = 0; for (int i = 0; i < attributeFormat.size(); ++i) { int loc = glGetAttribLocation(shader, attributeFormat[i].attribute.c_str()); if (loc != -1) { glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, attributeFormat[i].format, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof(float) * offset)); } offset += attributeFormat[i].format; } ASSERT(CheckGLError()); } void Graphics::DetachShader() { glUseProgram(0); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, int* i) { ASSERT(shader != 0); glUniform1iv(glGetUniformLocation(shader, name), count, i); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, float* f) { ASSERT(shader != 0); glUniform1fv(glGetUniformLocation(shader, name), count, f); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec2* v2) { ASSERT(shader != 0); glUniform2fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v2[0])); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec3* v3) { ASSERT(shader != 0); glUniform3fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v3[0])); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec4* v4) { ASSERT(shader != 0); glUniform4fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v4[0])); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat2* m2) { ASSERT(shader != 0); glUniformMatrix2fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m2[0])); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat3* m3) { ASSERT(shader != 0); glUniformMatrix3fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m3[0])); ASSERT(CheckGLError()); } void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat4* m4) { ASSERT(shader != 0); glUniformMatrix4fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m4[0])); ASSERT(CheckGLError()); } void Graphics::DrawVertices(Primitive primitive, int offset, int count) { switch (primitive) { case Primitive::POINTS: glDrawArrays(GL_POINTS, offset, count); break; case Primitive::LINES: glDrawArrays(GL_LINES, offset, count); break; case Primitive::TRIANGLES: glDrawArrays(GL_TRIANGLES, offset, count); break; } ASSERT(CheckGLError()); } void Graphics::DrawIndexed(Primitive primitive, int count) { switch (primitive) { case Primitive::POINTS: glDrawElements(GL_POINTS, count, GL_UNSIGNED_INT, 0); break; case Primitive::LINES: glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, 0); break; case Primitive::TRIANGLES: glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, 0); break; } ASSERT(CheckGLError()); } Texture Graphics::CreateTexture(TextureFormat format, int count, int width, int height, const void* data, bool mipmap) { Texture texture; glGenTextures(count, &texture); glBindTexture(GL_TEXTURE_2D, texture); switch (format) { case TextureFormat::RBG24: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); break; case TextureFormat::RBGA32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); break; } if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); return texture; ASSERT(CheckGLError()); } void Graphics::DeleteTexture(int count, Texture texture) { ASSERT(texture != 0); glDeleteTextures(count, &texture); texture = 0; ASSERT(CheckGLError()); } void Graphics::FilterTexture(Texture texture, TextureWrap s, TextureWrap t, TextureFilter min, TextureFilter mag) { ASSERT(texture != 0); glBindTexture(GL_TEXTURE_2D, texture); switch (s) { case TextureWrap::REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); break; case TextureWrap::MIRROR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); break; case TextureWrap::EDGE_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break; case TextureWrap::BORDER_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); break; } switch (t) { case TextureWrap::REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); break; case TextureWrap::MIRROR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); break; case TextureWrap::EDGE_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break; case TextureWrap::BORDER_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); break; } switch (min) { case TextureFilter::NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); break; case TextureFilter::LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); break; case TextureFilter::NEAREST_NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); break; case TextureFilter::NEAREST_LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); break; case TextureFilter::LINEAR_NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); break; case TextureFilter::LINEAR_LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); break; } switch (mag) { case TextureFilter::NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case TextureFilter::LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break; } glBindTexture(GL_TEXTURE_2D, 0); ASSERT(CheckGLError()); } void Graphics::BindTexture(Texture texture, int loc) { ASSERT(texture != 0); glBindTexture(GL_TEXTURE_2D, texture); glActiveTexture(GL_TEXTURE0 + loc); ASSERT(CheckGLError()); } void Graphics::DetachTexture() { glBindTexture(GL_TEXTURE_2D, 0); ASSERT(CheckGLError()); }
26.984032
130
0.691767
Belfer
a08f5e9809d1100e7ef695a0a60945e07fd795bd
2,157
cpp
C++
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
1
2020-07-09T00:20:49.000Z
2020-07-09T00:20:49.000Z
/***************************************************************************** * jlp_gsegraf.cpp * JLP_Gsegraf class * * JLP * Version 14/12/2016 *****************************************************************************/ #include "jlp_gsegraf.h" // JLP_Gsegraf /**************************************************************************** * Constructors: *****************************************************************************/ JLP_Gsegraf::JLP_Gsegraf(JLP_Gseg *jlp_gseg0, char *parameter_file_0, char **save_filename_0, int *close_flag_0) { char font_name0[64]; double font_size_date_time0, font_size_legend0, font_size_text0; double font_size_tick_labels0, font_size_axis_labels0, font_size_title0; strcpy(font_name0, "Sans"); // For safety: jlp_gseg1 = NULL; GSEG_InitializePlot(jlp_gseg0, parameter_file_0, save_filename_0, close_flag_0, font_name0, &font_size_date_time0, &font_size_legend0, &font_size_text0, &font_size_tick_labels0, &font_size_axis_labels0, &font_size_title0); } /**************************************************************************** * Constructor: *****************************************************************************/ JLP_Gsegraf::JLP_Gsegraf(JLP_Gseg *jlp_gseg0, char *parameter_file_0, char **save_filename_0, int *close_flag_0, char *font_name0, double *font_size_date_time0, double *font_size_legend0, double *font_size_text0, double *font_size_tick_labels0, double *font_size_axis_labels0, double *font_size_title0) { // For safety: jlp_gseg1 = NULL; GSEG_InitializePlot(jlp_gseg0, parameter_file_0, save_filename_0, close_flag_0, font_name0, font_size_date_time0, font_size_legend0, font_size_text0, font_size_tick_labels0, font_size_axis_labels0, font_size_title0); }
39.944444
80
0.481688
jlprieur
a0911081b67ccc9a9b81ca5d615c2d2706505d6d
380
cpp
C++
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include <iostream> void moveDisk(int n, char src, char dest, char trans) { if (n == 1) { std::cout << src << "->" << dest << std::endl; return; } moveDisk(n - 1, src, trans, dest); std::cout << src << "->" << dest << std::endl; moveDisk(n - 1, trans, dest, src); } int main() { int n; std::cin >> n; moveDisk(n, 'A', 'C', 'B'); }
22.352941
55
0.476316
Guyutongxue
a091eb9f455024b9109bb0e7aa7947136856dbca
956
hpp
C++
Enginelib/src/components/textcomponent.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
Enginelib/src/components/textcomponent.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
Enginelib/src/components/textcomponent.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <SDL_ttf.h> #include <cstdint> #include "../basics/sprite.hpp" #include "../basics/vector2d.hpp" #include "../graphicsmanager.hpp" #include "../gameobject.hpp" #include "../filesystem/resourcearchive.hpp" #include "../basics/helpers.hpp" class TextComponent : public Component { public: TextComponent(GameObject *); ~TextComponent(); void initialize(ResourceFile * file, int size = 16); void set_font_size(int); std::string get_text(); void set_text(const std::string &); void set_color(uint8_t, uint8_t, uint8_t, uint8_t = 0); void render() final override; private: std::string m_text = ""; Sprite m_sprite; TTF_Font * m_font = nullptr; ResourceFile * m_font_source; Vector2D m_scale = {1, 1}; double m_angle = 0; bool m_centered = false; SDL_RendererFlip m_flip = SDL_FLIP_NONE; SDL_Color m_color = {255, 255, 255, 1}; const int default_font_size = 16; const std::string m_default_font = ""; };
28.117647
56
0.722803
kalsipp
a09441f579cc07e3807baa174c1655b8583eecf1
8,293
hpp
C++
clients/include/testing_getrs_strided_batched.hpp
rkamd/hipBLAS
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
[ "MIT" ]
null
null
null
clients/include/testing_getrs_strided_batched.hpp
rkamd/hipBLAS
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
[ "MIT" ]
null
null
null
clients/include/testing_getrs_strided_batched.hpp
rkamd/hipBLAS
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright (C) 2016-2022 Advanced Micro Devices, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, 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 <fstream> #include <iostream> #include <stdlib.h> #include <vector> #include "testing_common.hpp" template <typename T> hipblasStatus_t testing_getrs_strided_batched(const Arguments& argus) { using U = real_t<T>; bool FORTRAN = argus.fortran; auto hipblasGetrsStridedBatchedFn = FORTRAN ? hipblasGetrsStridedBatched<T, true> : hipblasGetrsStridedBatched<T, false>; int N = argus.N; int lda = argus.lda; int ldb = argus.ldb; int batch_count = argus.batch_count; double stride_scale = argus.stride_scale; hipblasStride strideA = size_t(lda) * N * stride_scale; hipblasStride strideB = size_t(ldb) * 1 * stride_scale; hipblasStride strideP = size_t(N) * stride_scale; size_t A_size = strideA * batch_count; size_t B_size = strideB * batch_count; size_t Ipiv_size = strideP * batch_count; // Check to prevent memory allocation error if(N < 0 || lda < N || ldb < N || batch_count < 0) { return HIPBLAS_STATUS_INVALID_VALUE; } if(batch_count == 0) { return HIPBLAS_STATUS_SUCCESS; } // Naming: dK is in GPU (device) memory. hK is in CPU (host) memory host_vector<T> hA(A_size); host_vector<T> hX(B_size); host_vector<T> hB(B_size); host_vector<T> hB1(B_size); host_vector<int> hIpiv(Ipiv_size); host_vector<int> hIpiv1(Ipiv_size); int info; device_vector<T> dA(A_size); device_vector<T> dB(B_size); device_vector<int> dIpiv(Ipiv_size); double gpu_time_used, hipblas_error; hipblasLocalHandle handle(argus); // Initial hA, hB, hX on CPU srand(1); hipblasOperation_t op = HIPBLAS_OP_N; for(int b = 0; b < batch_count; b++) { T* hAb = hA.data() + b * strideA; T* hXb = hX.data() + b * strideB; T* hBb = hB.data() + b * strideB; int* hIpivb = hIpiv.data() + b * strideP; hipblas_init<T>(hAb, N, N, lda); hipblas_init<T>(hXb, N, 1, ldb); // scale A to avoid singularities for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(i == j) hAb[i + j * lda] += 400; else hAb[i + j * lda] -= 4; } } // Calculate hB = hA*hX; cblas_gemm<T>(op, op, N, 1, N, (T)1, hAb, lda, hXb, ldb, (T)0, hBb, ldb); // LU factorize hA on the CPU info = cblas_getrf<T>(N, N, hAb, lda, hIpivb); if(info != 0) { std::cerr << "LU decomposition failed" << std::endl; return HIPBLAS_STATUS_INTERNAL_ERROR; } } // Copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dA, hA, A_size * sizeof(T), hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dB, hB, B_size * sizeof(T), hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dIpiv, hIpiv, Ipiv_size * sizeof(int), hipMemcpyHostToDevice)); if(argus.unit_check || argus.norm_check) { /* ===================================================================== HIPBLAS =================================================================== */ CHECK_HIPBLAS_ERROR(hipblasGetrsStridedBatchedFn(handle, op, N, 1, dA, lda, strideA, dIpiv, strideP, dB, ldb, strideB, &info, batch_count)); // copy output from device to CPU CHECK_HIP_ERROR(hipMemcpy(hB1.data(), dB, B_size * sizeof(T), hipMemcpyDeviceToHost)); CHECK_HIP_ERROR( hipMemcpy(hIpiv1.data(), dIpiv, Ipiv_size * sizeof(int), hipMemcpyDeviceToHost)); /* ===================================================================== CPU LAPACK =================================================================== */ for(int b = 0; b < batch_count; b++) { cblas_getrs('N', N, 1, hA.data() + b * strideA, lda, hIpiv.data() + b * strideP, hB.data() + b * strideB, ldb); } hipblas_error = norm_check_general<T>('F', N, 1, ldb, strideB, hB, hB1, batch_count); if(argus.unit_check) { U eps = std::numeric_limits<U>::epsilon(); double tolerance = N * eps * 100; unit_check_error(hipblas_error, tolerance); } } if(argus.timing) { hipStream_t stream; CHECK_HIPBLAS_ERROR(hipblasGetStream(handle, &stream)); int runs = argus.cold_iters + argus.iters; for(int iter = 0; iter < runs; iter++) { if(iter == argus.cold_iters) gpu_time_used = get_time_us_sync(stream); CHECK_HIPBLAS_ERROR(hipblasGetrsStridedBatchedFn(handle, op, N, 1, dA, lda, strideA, dIpiv, strideP, dB, ldb, strideB, &info, batch_count)); } gpu_time_used = get_time_us_sync(stream) - gpu_time_used; ArgumentModel<e_N, e_lda, e_stride_a, e_ldb, e_stride_b, e_batch_count>{}.log_args<T>( std::cout, argus, gpu_time_used, getrs_gflop_count<T>(N, 1), ArgumentLogging::NA_value, hipblas_error); } return HIPBLAS_STATUS_SUCCESS; }
39.679426
95
0.450983
rkamd
90b3e4f1b399089ad8f4f719f8709714f266e7ec
1,454
cpp
C++
test/datastruct/bindtree2d/random.cpp
ttalvitie/libcontest
c4fd9743d73a5127af41fe8ed171e1e45ce8f1ee
[ "Unlicense" ]
3
2015-12-17T21:19:13.000Z
2021-02-01T22:20:19.000Z
test/datastruct/bindtree2d/random.cpp
ttalvitie/libcontest
c4fd9743d73a5127af41fe8ed171e1e45ce8f1ee
[ "Unlicense" ]
null
null
null
test/datastruct/bindtree2d/random.cpp
ttalvitie/libcontest
c4fd9743d73a5127af41fe8ed171e1e45ce8f1ee
[ "Unlicense" ]
null
null
null
#include "datastruct/bindtree2d.hpp" #include "datastruct/querysegtree2d.hpp" Z QuerySegmentTree2D::oper(Z a, Z b) { return a + b; } struct CmpImpl { CmpImpl(int w, int h) : tree(w, vector<Z>(h, 0)) { } void change(int x, int y, Z v) { tree[x][y] += v; } Z sum(int x, int y) { Z ret = 0; for(int i = 0; i < x; ++i) { for(int j = 0; j < y; ++j) { ret += tree[i][j]; } } return ret; } vector<vector<Z>> tree; }; int main() { mt19937 rng; uniform_int_distribution<int> length_dist(0, 30); uniform_int_distribution<Z> val_dist(INT_MIN, INT_MAX); for(int t = 0; t < 1000; ++t) { int w = length_dist(rng); int h = length_dist(rng); BinIndexedTree2D a(w, h); CmpImpl b(w, h); QuerySegmentTree2D c(w, h); uniform_int_distribution<int> indx_dist(0, max(w - 1, 0)); uniform_int_distribution<int> indy_dist(0, max(h - 1, 0)); uniform_int_distribution<int> endx_dist(0, w); uniform_int_distribution<int> endy_dist(0, h); for(int t2 = 0; t2 < 1000; ++t2) { if(w != 0 && h != 0) { for(int t3 = 0; t3 < 15; ++t3) { int x = indx_dist(rng); int y = indy_dist(rng); Z v = val_dist(rng); a.change(x, y, v); b.change(x, y, v); c.set(x, y, c.query(x, y, x + 1, y + 1) + v); } } int x = endx_dist(rng); int y = endy_dist(rng); Z A = a.sum(x, y); Z B = b.sum(x, y); Z C = c.query(0, 0, x, y); if(A != B || B != C) fail(); } } return 0; }
21.382353
60
0.555708
ttalvitie
90b477e81806d45ca33c2a7d1922e15c7ce161ba
2,349
cpp
C++
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.cpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
23
2021-10-31T00:20:21.000Z
2022-03-26T07:24:40.000Z
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.cpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
5
2021-10-31T18:44:51.000Z
2022-03-25T18:04:26.000Z
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.cpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
18
2021-10-20T02:31:56.000Z
2022-02-01T11:44:36.000Z
// Arquivo cmd_my_room_item.cpp // Criado em 22/03/2018 as 20:44 por Acrisio // Implementa��o da classe CmdMyRoomItem #if defined(_WIN32) #pragma pack(1) #endif #include "cmd_my_room_item.hpp" using namespace stdA; CmdMyRoomItem::CmdMyRoomItem(bool _waiter) : pangya_db(_waiter), m_uid(0u), m_item_id(-1), m_type(ALL), v_mri() { } CmdMyRoomItem::CmdMyRoomItem(uint32_t _uid, TYPE _type, int32_t _item_id, bool _waiter) : pangya_db(_waiter), m_uid(_uid), m_type(_type), m_item_id(_item_id), v_mri() { } CmdMyRoomItem::~CmdMyRoomItem() { } void CmdMyRoomItem::lineResult(result_set::ctx_res* _result, uint32_t /*_index_result*/) { checkColumnNumber(9, (uint32_t)_result->cols); MyRoomItem mri{ 0 }; uint32_t uid_req = 0u; mri.id = IFNULL(atoi, _result->data[0]); uid_req = IFNULL(atoi, _result->data[1]); mri._typeid = IFNULL(atoi, _result->data[2]); mri.number = (unsigned short)IFNULL(atoi, _result->data[3]); mri.location.x = (float)IFNULL(atof, _result->data[4]); mri.location.y = (float)IFNULL(atof, _result->data[5]); mri.location.z = (float)IFNULL(atof, _result->data[6]); mri.location.r = (float)IFNULL(atof, _result->data[7]); mri.equiped = (unsigned char)IFNULL(atoi, _result->data[8]); v_mri.push_back(mri); if (uid_req != m_uid) throw exception("[CmdMyRoomItem::lineResult][Error] o uid do my room item requisitado do player e diferente. UID_req: " + std::to_string(uid_req) + " != " + std::to_string(m_uid), STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 3, 0)); } response* CmdMyRoomItem::prepareConsulta(database& _db) { v_mri.clear(); v_mri.shrink_to_fit(); auto r = procedure(_db, (m_type == ALL) ? m_szConsulta[0] : m_szConsulta[1], std::to_string(m_uid) + (m_type == ONE ? ", " + std::to_string(m_item_id) : std::string())); checkResponse(r, "nao conseguiu pegar o(s) item(ns) do my room do player: " + std::to_string(m_uid)); return r; } std::vector< MyRoomItem >& CmdMyRoomItem::getMyRoomItem() { return v_mri; } uint32_t CmdMyRoomItem::getUID() { return m_uid; } void CmdMyRoomItem::setUID(uint32_t _uid) { m_uid = _uid; } int32_t CmdMyRoomItem::getItemID() { return m_item_id; } void CmdMyRoomItem::setItemID(int32_t _item_id) { m_item_id = _item_id; } CmdMyRoomItem::TYPE CmdMyRoomItem::getType() { return m_type; } void CmdMyRoomItem::setType(TYPE _type) { m_type = _type; }
27.635294
233
0.713069
CCasusensa
90b587d331f36cf5ea2001c22923f69679ca578a
1,724
hpp
C++
src/backend/cpp/reach-tube.hpp
C2E2-Development-Team/C2E2-Tool
36631bfd75c0c0fb56389f13a9aba68cbed1680f
[ "MIT" ]
1
2021-10-04T19:56:25.000Z
2021-10-04T19:56:25.000Z
src/backend/cpp/reach-tube.hpp
C2E2-Development-Team/C2E2-Tool
36631bfd75c0c0fb56389f13a9aba68cbed1680f
[ "MIT" ]
null
null
null
src/backend/cpp/reach-tube.hpp
C2E2-Development-Team/C2E2-Tool
36631bfd75c0c0fb56389f13a9aba68cbed1680f
[ "MIT" ]
null
null
null
/** * \file reach-tube.hpp * \class ReachTube * * \author parasara * \author Lucas Brown * \date July, 2014 * \date April 2, 2019 * * \brief LMBTODO */ #ifndef REACHTUBE_H_ #define REACHTUBE_H_ #include <ppl.hh> #include <stack> #include <string> #include <vector> #include "annotation.hpp" #include "point.hpp" #include "rep-point.hpp" class ReachTube { public: ReachTube(); ~ReachTube(); int getSize(); Point getUpperBound(int index); Point getLowerBound(int index); void parseInvariantTube(char const* filename, int hasMode); void printReachTube(const std::string, int flag); void clear(int from); ReachTube bloatReachTube(std::vector<double> delta_array, Annotation annotation); int getNextSetStack(std::stack<RepPoint>& itr_stack, RepPoint parent_rep_point); void addGuards(std::vector<std::pair<std::NNC_Polyhedron, int> > guards); double getMinCoordinate(int dim, int cur_mode); double getMaxCoordinate(int dim, int cur_mode); int checkIntersection(int cur_mode, Point cur_point, std::vector<double> delta_array); double getMinTime(int cur_mode, Point cur_point, std::vector<double> delta_array); int getDimensions(); void setDimensions(int val); int getMode(); void setMode(int val); // Setting mode also sets the isReachTube bool std::vector<int> getModeVec(); void setModeVec(std::vector<int> vec); void addLowerBoundState(Point obj); void addUpperBoundState(Point obj); private: int dimensions; int isReachTube; int reachTubeMode; std::vector<int> color; std::vector<int> mode; std::vector<Point> upper_bound; std::vector<Point> lower_bound; }; #endif /* REACHTUBE_H_ */
24.628571
85
0.703016
C2E2-Development-Team
90b5ba3d3a99e64f0e3290bf7b22b5b06652c50b
10,615
cpp
C++
src/l_CollisionComponent.cpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
2
2018-05-13T05:27:29.000Z
2018-05-29T06:35:57.000Z
src/l_CollisionComponent.cpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
src/l_CollisionComponent.cpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
#include "l_CollisionComponent.hpp" CollisionComponent* lua_pushcollisionComponent( lua_State *L, CollisionComponent* collisioncomponent = nullptr) { if (collisioncomponent == nullptr) { std::cerr << "Warning: CollisionComponent - this will not work, nullptr" << std::endl; collisioncomponent = new CollisionComponent(""); } CollisionComponent** collisioncomponentPtr = static_cast<CollisionComponent**> (lua_newuserdata(L, sizeof(CollisionComponent*))); //storing the address directly. Lua can be seen as a window, //looking in at the engine. This could be a good source for a lot //of problems. *collisioncomponentPtr = collisioncomponent; luaL_getmetatable(L, LUA_USERDATA_COLLISIONCOMPONENT); lua_setmetatable(L, -2); return collisioncomponent; } CollisionComponent* lua_tocollisionComponent(lua_State *L, int index) { CollisionComponent* collisioncomponent = *static_cast<CollisionComponent**> (luaL_checkudata(L, index, LUA_USERDATA_COLLISIONCOMPONENT)); if (collisioncomponent == NULL) { luaL_error(L, "Provided userdata is not of type 'CollisionComponent'"); } return collisioncomponent; } boolType lua_iscollisionComponent(lua_State* L, int index) { if (lua_isuserdata(L, index)) { auto chk = lua_isUserdataType(L, index, LUA_USERDATA_COLLISIONCOMPONENT); return chk; } return false; } static int l_CollisionComponent_CollisionComponent(lua_State *L) { stringType componentName = luaL_checkstring(L, 1); boolType isParent = lua_toboolean(L, 2); auto component = new CollisionComponent( componentName, !isParent); lua_pushcollisionComponent(L, component); return 1; } static int l_CollisionComponent_isCollisionComponent(lua_State *L) { if (lua_iscollisionComponent(L, 1)) { lua_pushboolean(L, 1); } else { lua_pushboolean(L, 0); } return 1; } static const struct luaL_Reg l_CollisionComponent_Registry [] = { {"CollisionComponent", l_CollisionComponent_CollisionComponent}, {"isCollisionComponent", l_CollisionComponent_isCollisionComponent}, {NULL, NULL} }; static int l_CollisionComponent_gc(lua_State *L) { return 0; } static int l_CollisionComponent_tostring(lua_State *L) { auto component = lua_tocomponent(L, 1); stringType msg = "Component:COLLISION:"; msg += component->getName(); lua_pushstring(L, msg.c_str()); return 1; } static int l_CollisionComponent_getFamily(lua_State *L) { lua_pushstring(L, "COLLISION"); return 1; } static int l_CollisionComponent_createChild(lua_State *L) { auto component = lua_tocomponent(L, 1); stringType childComponentName = luaL_checkstring(L, 2); auto childComponent = component->createChild(childComponentName); CollisionComponent* childComponent_cast = static_cast<CollisionComponent*> (childComponent); lua_pushcollisionComponent(L, childComponent_cast); return 1; } static int l_CollisionComponent_setPhysicsRelation(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); //get the physics component auto p_component = lua_tocomponent(L, 2); auto physicsComponent = static_cast<PhysicsComponent*> (p_component); collisionComponent->setPhysicsRelation(physicsComponent); return 0; } static int l_CollisionComponent_getPhysicsRelation(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto p_component = collisionComponent->getPhysicsRelation(); if (p_component != nullptr) { lua_pushphysicsComponent(L, p_component); } else { lua_pushnil(L); } return 1; } static int l_CollisionComponent_setOffset(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto vector = lua_tovector(L, 2); collisionComponent->setOffset(*vector); return 0; } static int l_CollisionComponent_getOffset(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto vector = collisionComponent->getOffset(); lua_pushvector(L, new Vector3(vector)); return 1; } static int l_CollisionComponent_setOrigin(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto vector = lua_tovector(L, 2); collisionComponent->setOrigin(*vector); return 0; } static int l_CollisionComponent_getOrigin(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto vector = collisionComponent->getOrigin(); lua_pushvector(L, new Vector3(vector)); return 1; } static int l_CollisionComponent_setOrientation(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto quat = lua_toquaternion(L, 2); collisionComponent->setOrientation(*quat); return 0; } static int l_CollisionComponent_getOrientation(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto quat = collisionComponent->getOrientation(); lua_pushquaternion(L, new Quaternion(quat)); return 1; } static int l_CollisionComponent_setType(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); stringType typeString = luaL_checkstring(L, 2); collisionComponent->setCollisionTypeString(typeString); return 0; } static int l_CollisionComponent_getType(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component);\ auto typeString = collisionComponent->getCollisionTypeString(); lua_pushstring(L, typeString.c_str()); return 1; } static int l_CollisionComponent_setRadius(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = luaL_checknumber(L, 2); collisionComponent->setRadius(floatValue); return 0; } static int l_CollisionComponent_getRadius(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = collisionComponent->getRadius(); lua_pushnumber(L, floatValue); return 1; } static int l_CollisionComponent_setWidth(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = luaL_checknumber(L, 2); collisionComponent->setWidth(floatValue); return 0; } static int l_CollisionComponent_getWidth(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = collisionComponent->getWidth(); lua_pushnumber(L, floatValue); return 1; } static int l_CollisionComponent_setHeight(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = luaL_checknumber(L, 2); collisionComponent->setHeight(floatValue); return 0; } static int l_CollisionComponent_getHeight(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); floatType floatValue = collisionComponent->getHeight(); lua_pushnumber(L, floatValue); return 1; } static int l_CollisionComponent_setVectorList(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); if (!lua_istable(L, 2)) { luaL_error(L, "2nd argument must be a table of kf.Vector3's"); } integerType tableLength = lua_objlen(L, 2); std::vector<Vector3> vectorList; for (int i = 0; i < tableLength; i++) { lua_rawgeti(L, 2, i+1); auto vector = lua_tovector(L, -1); vectorList.push_back(*vector); } collisionComponent->setVectorList(vectorList); return 0; } static int l_CollisionComponent_getVectorList(lua_State *L) { auto component = lua_tocomponent(L, 1); auto collisionComponent = static_cast<CollisionComponent*> (component); auto vectorList = collisionComponent->getVectorList(); lua_createtable(L, vectorList.size(), 0); for(int i = 0; i < vectorList.size(); i++) { auto vector = new Vector3(vectorList[i]); lua_pushvector(L, vector); lua_rawseti(L, -2, i+1); } return 1; } static const struct luaL_Reg l_CollisionComponent [] = { {"__gc", l_CollisionComponent_gc}, {"__tostring", l_CollisionComponent_tostring}, {"getFamily", l_CollisionComponent_getFamily}, {"createChild", l_CollisionComponent_createChild}, {"setPhysicsRelation", l_CollisionComponent_setPhysicsRelation}, {"getPhysicsRelation", l_CollisionComponent_getPhysicsRelation}, {"setOffset", l_CollisionComponent_setOffset}, {"getOffset", l_CollisionComponent_getOffset}, {"setOrigin", l_CollisionComponent_setOrigin}, {"getOrigin", l_CollisionComponent_getOrigin}, {"setOrientation", l_CollisionComponent_setOrientation}, {"getOrientation", l_CollisionComponent_getOrientation}, {"setType", l_CollisionComponent_setType}, {"getType", l_CollisionComponent_getType}, {"setRadius", l_CollisionComponent_setRadius}, {"getRadius", l_CollisionComponent_getRadius}, {"setWidth", l_CollisionComponent_setWidth}, {"getWidth", l_CollisionComponent_getWidth}, {"setHeight", l_CollisionComponent_setHeight}, {"getHeight", l_CollisionComponent_getHeight}, {"setVectorList", l_CollisionComponent_setVectorList}, {"getVectorList", l_CollisionComponent_getVectorList}, {NULL, NULL} }; int luaopen_collisionComponent(lua_State *L) { //CollisionComponent luaL_newmetatable(L, LUA_USERDATA_COLLISIONCOMPONENT); lua_pushvalue(L, -1); luaL_getmetatable(L, LUA_USERDATA_ABSTRACTCOMPONENT); lua_setmetatable(L, -2); lua_setfield(L, -2, "__index"); luaL_register(L, NULL, l_CollisionComponent); lua_pop(L, 1); luaL_register(L, KF_LUA_LIBNAME, l_CollisionComponent_Registry); return 1; }
32.166667
87
0.735751
benzap
90b7c22a322dade4043e073f3e786f5ff495fb1f
872
cpp
C++
app/Helper/GridHelper.cpp
LNAV/Sudoku_Solver_Cpp
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
1
2020-05-17T11:46:46.000Z
2020-05-17T11:46:46.000Z
app/Helper/GridHelper.cpp
LNAV/VeronixApp-Sudoku_Solver
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
null
null
null
app/Helper/GridHelper.cpp
LNAV/VeronixApp-Sudoku_Solver
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
null
null
null
/* * GridHelper.cpp * * Created on: Jan 1, 2020 * Author: LavishK1 */ #include "GridHelper.h" namespace Veronix { namespace App { namespace helper { GridHelper::GridHelper() { } GridHelper::~GridHelper() { } bool GridHelper::findNewClue(sudosolver::container::GridContainer &grid) { //TODO findNewClueInTable(grid.getRowContainer()); findNewClueInTable(grid.getColContainer()); findNewClueInTable(grid.getBoxContainer()); return true; } bool GridHelper::findNewClueInTable(sudosolver::container::TableContainer &table) { //TODO for (int index = constants::valueZero; index < constants::squareSize; ++index) findNewClueInTableRow(table[index]); return true; } bool GridHelper::findNewClueInTableRow(sudosolver::container::TableRow &tableRow) { //TODO return true; } } /* namespace helper */ } /* namespace App */ } /* namespace Veronix */
16.148148
81
0.723624
LNAV
90ba6086e7b70f03afbf53793d07c1e63289a1dd
6,351
cc
C++
src/rdf++/writer/nquads.cc
datagraph/librdf
6697c6a2bfeb00978118968ea88eabb1612c892c
[ "Unlicense" ]
10
2015-12-23T05:17:49.000Z
2020-06-16T14:21:34.000Z
src/rdf++/writer/nquads.cc
datagraph/librdf
6697c6a2bfeb00978118968ea88eabb1612c892c
[ "Unlicense" ]
3
2015-06-15T14:15:33.000Z
2016-01-17T19:18:09.000Z
src/rdf++/writer/nquads.cc
datagraph/librdf
6697c6a2bfeb00978118968ea88eabb1612c892c
[ "Unlicense" ]
3
2015-02-14T23:16:01.000Z
2018-03-03T15:07:48.000Z
/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "nquads.h" #include "../format.h" #include "../quad.h" #include "../term.h" #include "../triple.h" #include <cassert> /* for assert() */ #include <cstdio> /* for FILE, std::f*() */ #include <cstring> /* for std::strcmp() */ //////////////////////////////////////////////////////////////////////////////// namespace { class implementation final : public rdf::writer::implementation { FILE* _stream {nullptr}; bool _ntriples{false}; public: implementation(FILE* stream, const char* content_type, const char* charset, const char* base_uri); virtual ~implementation() noexcept override; virtual void configure(const char* key, const char* value) override; virtual void begin() override; virtual void finish() override; virtual void write_triple(const rdf::triple& triple) override; virtual void write_quad(const rdf::quad& quad) override; virtual void write_comment(const char* comment) override; virtual void flush() override; protected: void write_term(const rdf::term& term); void write_escaped_iriref(const char* string); void write_escaped_string(const char* string); }; } //////////////////////////////////////////////////////////////////////////////// rdf::writer::implementation* rdf_writer_for_nquads(FILE* const stream, const char* const content_type, const char* const charset, const char* const base_uri) { return new implementation(stream, content_type, charset, base_uri); } //////////////////////////////////////////////////////////////////////////////// implementation::implementation(FILE* const stream, const char* const content_type, const char* const /*charset*/, const char* const /*base_uri*/) : _stream{stream} { assert(stream != nullptr); const rdf::format* const format = rdf::format::find_for_content_type(content_type); assert(format); if (std::strcmp(format->serializer_name, "ntriples") == 0) { _ntriples = true; } } implementation::~implementation() noexcept {} //////////////////////////////////////////////////////////////////////////////// void implementation::configure(const char* const /*key*/, const char* const /*value*/) { /* no configuration parameters supported at present */ } void implementation::begin() {} void implementation::finish() {} void implementation::write_triple(const rdf::triple& triple) { assert(triple.subject); write_term(*triple.subject); std::fputc(' ', _stream); assert(triple.predicate); write_term(*triple.predicate); std::fputc(' ', _stream); assert(triple.object); write_term(*triple.object); std::fputc(' ', _stream); std::fputs(".\n", _stream); } void implementation::write_quad(const rdf::quad& quad) { assert(quad.subject); write_term(*quad.subject); std::fputc(' ', _stream); assert(quad.predicate); write_term(*quad.predicate); std::fputc(' ', _stream); assert(quad.object); write_term(*quad.object); std::fputc(' ', _stream); if (quad.context && !_ntriples) { write_term(*quad.context); std::fputc(' ', _stream); } std::fputs(".\n", _stream); } void implementation::write_comment(const char* const comment) { std::fprintf(_stream, "# %s\n", comment); // TODO: handle multi-line comments. } void implementation::flush() { std::fflush(_stream); } void implementation::write_term(const rdf::term& term_) { switch (term_.type) { case rdf::term_type::uri_reference: { const auto& term = dynamic_cast<const rdf::uri_reference&>(term_); std::fputc('<', _stream); write_escaped_iriref(term.string.c_str()); std::fputc('>', _stream); break; } case rdf::term_type::blank_node: { const auto& term = dynamic_cast<const rdf::blank_node&>(term_); std::fprintf(_stream, "_:%s", term.string.c_str()); break; } case rdf::term_type::plain_literal: { const auto& term = dynamic_cast<const rdf::plain_literal&>(term_); std::fputc('"', _stream); write_escaped_string(term.string.c_str()); std::fputc('"', _stream); if (!term.language_tag.empty()) { std::fprintf(_stream, "@%s", term.language_tag.c_str()); } break; } case rdf::term_type::typed_literal: { const auto& term = dynamic_cast<const rdf::typed_literal&>(term_); std::fputc('"', _stream); write_escaped_string(term.string.c_str()); std::fputs("\"^^<", _stream); write_escaped_iriref(term.datatype_uri.c_str()); std::fputc('>', _stream); break; } default: { assert(false && "invalid term type for #write_term"); } } } void implementation::write_escaped_iriref(const char* string) { // @see http://www.w3.org/TR/n-quads/#grammar-production-IRIREF char c; while ((c = *string++) != '\0') { switch (c) { // @see http://www.w3.org/TR/n-quads/#grammar-production-UCHAR case '\x00'...'\x20': case '<': case '>': case '"': case '{': case '}': case '|': case '^': case '`': case '\\': std::fprintf(_stream, "\\u%04X", c); break; default: std::fputc(c, _stream); // TODO: implement UCHAR escaping } } } void implementation::write_escaped_string(const char* string) { // @see http://www.w3.org/TR/n-quads/#grammar-production-STRING_LITERAL_QUOTE char c; while ((c = *string++) != '\0') { switch (c) { // @see http://www.w3.org/TR/n-quads/#grammar-production-ECHAR case '\t': std::fputs("\\t", _stream); break; case '\b': std::fputs("\\b", _stream); break; case '\n': std::fputs("\\n", _stream); break; case '\r': std::fputs("\\r", _stream); break; case '\f': std::fputs("\\f", _stream); break; case '"': std::fputs("\\\"", _stream); break; //case '\'': std::fputs("\\'", _stream); /* not needed */ case '\\': std::fputs("\\\\", _stream); break; // @see http://www.w3.org/TR/n-quads/#grammar-production-UCHAR default: std::fputc(c, _stream); // TODO: implement UCHAR escaping } } }
28.737557
85
0.585105
datagraph
90c0087c3162b691e8ec9d1d48204870220d6bdc
3,103
hpp
C++
include/NatSuite/Devices/FlashMode.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/NatSuite/Devices/FlashMode.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/NatSuite/Devices/FlashMode.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: NatSuite.Devices namespace NatSuite::Devices { // Forward declaring type: FlashMode struct FlashMode; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::NatSuite::Devices::FlashMode, "NatSuite.Devices", "FlashMode"); // Type namespace: NatSuite.Devices namespace NatSuite::Devices { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: NatSuite.Devices.FlashMode // [TokenAttribute] Offset: FFFFFFFF // [DocAttribute] Offset: 66BAAC struct FlashMode/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: FlashMode constexpr FlashMode(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // [DocAttribute] Offset: 0x677EAC // static field const value: static public NatSuite.Devices.FlashMode Off static constexpr const int Off = 0; // Get static field: static public NatSuite.Devices.FlashMode Off static ::NatSuite::Devices::FlashMode _get_Off(); // Set static field: static public NatSuite.Devices.FlashMode Off static void _set_Off(::NatSuite::Devices::FlashMode value); // [DocAttribute] Offset: 0x677EE4 // static field const value: static public NatSuite.Devices.FlashMode On static constexpr const int On = 1; // Get static field: static public NatSuite.Devices.FlashMode On static ::NatSuite::Devices::FlashMode _get_On(); // Set static field: static public NatSuite.Devices.FlashMode On static void _set_On(::NatSuite::Devices::FlashMode value); // [DocAttribute] Offset: 0x677F1C // static field const value: static public NatSuite.Devices.FlashMode Auto static constexpr const int Auto = 2; // Get static field: static public NatSuite.Devices.FlashMode Auto static ::NatSuite::Devices::FlashMode _get_Auto(); // Set static field: static public NatSuite.Devices.FlashMode Auto static void _set_Auto(::NatSuite::Devices::FlashMode value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // NatSuite.Devices.FlashMode #pragma pack(pop) static check_size<sizeof(FlashMode), 0 + sizeof(int)> __NatSuite_Devices_FlashModeSizeCheck; static_assert(sizeof(FlashMode) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
41.932432
94
0.70448
RedBrumbler
90c2cf008684b706cb500d3e55e916a574996fdd
33,844
cc
C++
chrome/browser/ui/views/payments/payment_request_browsertest_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/payments/payment_request_browsertest_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/payments/payment_request_browsertest_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/payments/payment_request_browsertest_base.h" #include <algorithm> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/payments/payment_request_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/payments/editor_view_controller.h" #include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h" #include "chrome/browser/ui/views/payments/validating_combobox.h" #include "chrome/browser/ui/views/payments/validating_textfield.h" #include "chrome/browser/ui/views/payments/view_stack.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/ui/address_combobox_model.h" #include "components/network_session_configurator/common/network_switches.h" #include "components/payments/content/payment_request.h" #include "components/payments/content/payment_request_web_contents_manager.h" #include "components/payments/core/payment_prefs.h" #include "components/prefs/pref_service.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/test/ui_controls.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" #include "ui/gfx/animation/test_animation_delegate.h" #include "ui/gfx/geometry/point.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/styled_label.h" namespace payments { namespace { const auto kBillingAddressType = autofill::ADDRESS_BILLING_LINE1; // This is preferred to SelectValue, since only SetSelectedRow fires the events // as if done by a user. void SelectComboboxRowForValue(views::Combobox* combobox, const base::string16& text) { int i; for (i = 0; i < combobox->GetRowCount(); i++) { if (combobox->GetTextForRow(i) == text) break; } DCHECK(i < combobox->GetRowCount()) << "Combobox does not contain " << text; combobox->SetSelectedRow(i); } } // namespace PersonalDataLoadedObserverMock::PersonalDataLoadedObserverMock() = default; PersonalDataLoadedObserverMock::~PersonalDataLoadedObserverMock() = default; PaymentRequestBrowserTestBase::PaymentRequestBrowserTestBase() = default; PaymentRequestBrowserTestBase::~PaymentRequestBrowserTestBase() = default; void PaymentRequestBrowserTestBase::SetUpCommandLine( base::CommandLine* command_line) { // HTTPS server only serves a valid cert for localhost, so this is needed to // load pages from "a.com" without an interstitial. command_line->AppendSwitch(switches::kIgnoreCertificateErrors); command_line->AppendSwitch(switches::kEnableExperimentalWebPlatformFeatures); } void PaymentRequestBrowserTestBase::SetUpOnMainThread() { // Setup the https server. https_server_ = std::make_unique<net::EmbeddedTestServer>( net::EmbeddedTestServer::TYPE_HTTPS); host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(https_server_->InitializeAndListen()); https_server_->ServeFilesFromSourceDirectory("components/test/data/payments"); https_server_->StartAcceptingConnections(); Observe(GetActiveWebContents()); // Starting now, PaymentRequest Mojo messages sent by the renderer will // create PaymentRequest objects via this test's CreatePaymentRequestForTest, // allowing the test to inject itself as a dialog observer. payments::SetPaymentRequestFactoryForTesting(base::BindRepeating( &PaymentRequestBrowserTestBase::CreatePaymentRequestForTest, base::Unretained(this))); // Set a test sync service so that all types of cards work. GetDataManager()->SetSyncServiceForTest(&sync_service_); // Register all prefs with our pref testing service. payments::RegisterProfilePrefs(prefs_.registry()); } void PaymentRequestBrowserTestBase::NavigateTo(const std::string& file_path) { if (file_path.find("data:") == 0U) { ui_test_utils::NavigateToURL(browser(), GURL(file_path)); } else { ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("a.com", file_path)); } } void PaymentRequestBrowserTestBase::SetIncognito() { is_incognito_ = true; } void PaymentRequestBrowserTestBase::SetInvalidSsl() { is_valid_ssl_ = false; } void PaymentRequestBrowserTestBase::SetBrowserWindowInactive() { is_browser_window_active_ = false; } void PaymentRequestBrowserTestBase::SetSkipUiForForBasicCard() { skip_ui_for_basic_card_ = true; } void PaymentRequestBrowserTestBase::OnCanMakePaymentCalled() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CAN_MAKE_PAYMENT_CALLED); } void PaymentRequestBrowserTestBase::OnCanMakePaymentReturned() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CAN_MAKE_PAYMENT_RETURNED); } void PaymentRequestBrowserTestBase::OnHasEnrolledInstrumentCalled() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::HAS_ENROLLED_INSTRUMENT_CALLED); } void PaymentRequestBrowserTestBase::OnHasEnrolledInstrumentReturned() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::HAS_ENROLLED_INSTRUMENT_RETURNED); } void PaymentRequestBrowserTestBase::OnNotSupportedError() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::NOT_SUPPORTED_ERROR); } void PaymentRequestBrowserTestBase::OnConnectionTerminated() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::DIALOG_CLOSED); } void PaymentRequestBrowserTestBase::OnAbortCalled() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::ABORT_CALLED); } void PaymentRequestBrowserTestBase::OnDialogOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::DIALOG_OPENED); } void PaymentRequestBrowserTestBase::OnOrderSummaryOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::ORDER_SUMMARY_OPENED); } void PaymentRequestBrowserTestBase::OnPaymentMethodOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::PAYMENT_METHOD_OPENED); } void PaymentRequestBrowserTestBase::OnShippingAddressSectionOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::SHIPPING_ADDRESS_SECTION_OPENED); } void PaymentRequestBrowserTestBase::OnShippingOptionSectionOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::SHIPPING_OPTION_SECTION_OPENED); } void PaymentRequestBrowserTestBase::OnCreditCardEditorOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CREDIT_CARD_EDITOR_OPENED); } void PaymentRequestBrowserTestBase::OnShippingAddressEditorOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::SHIPPING_ADDRESS_EDITOR_OPENED); } void PaymentRequestBrowserTestBase::OnContactInfoEditorOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CONTACT_INFO_EDITOR_OPENED); } void PaymentRequestBrowserTestBase::OnBackNavigation() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::BACK_NAVIGATION); } void PaymentRequestBrowserTestBase::OnBackToPaymentSheetNavigation() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::BACK_TO_PAYMENT_SHEET_NAVIGATION); } void PaymentRequestBrowserTestBase::OnContactInfoOpened() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CONTACT_INFO_OPENED); } void PaymentRequestBrowserTestBase::OnEditorViewUpdated() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::EDITOR_VIEW_UPDATED); } void PaymentRequestBrowserTestBase::OnErrorMessageShown() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::ERROR_MESSAGE_SHOWN); } void PaymentRequestBrowserTestBase::OnSpecDoneUpdating() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::SPEC_DONE_UPDATING); } void PaymentRequestBrowserTestBase::OnCvcPromptShown() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::CVC_PROMPT_SHOWN); } void PaymentRequestBrowserTestBase::OnProcessingSpinnerShown() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::PROCESSING_SPINNER_SHOWN); } void PaymentRequestBrowserTestBase::OnProcessingSpinnerHidden() { if (event_waiter_) event_waiter_->OnEvent(DialogEvent::PROCESSING_SPINNER_HIDDEN); } void PaymentRequestBrowserTestBase::InvokePaymentRequestUI() { ResetEventWaiterForDialogOpened(); content::WebContents* web_contents = GetActiveWebContents(); const std::string click_buy_button_js = "(function() { document.getElementById('buy').click(); })();"; ASSERT_TRUE(content::ExecuteScript(web_contents, click_buy_button_js)); WaitForObservedEvent(); // The web-modal dialog should be open. web_modal::WebContentsModalDialogManager* web_contents_modal_dialog_manager = web_modal::WebContentsModalDialogManager::FromWebContents(web_contents); EXPECT_TRUE(web_contents_modal_dialog_manager->IsDialogActive()); } void PaymentRequestBrowserTestBase::ExpectBodyContains( const std::vector<std::string>& expected_strings) { content::WebContents* web_contents = GetActiveWebContents(); const std::string extract_contents_js = "(function() { " "window.domAutomationController.send(window.document.body.textContent); " "})()"; std::string contents; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents, extract_contents_js, &contents)); for (const std::string& expected_string : expected_strings) { EXPECT_NE(std::string::npos, contents.find(expected_string)) << "String \"" << expected_string << "\" is not present in the content \"" << contents << "\""; } } void PaymentRequestBrowserTestBase::OpenOrderSummaryScreen() { ResetEventWaiter(DialogEvent::ORDER_SUMMARY_OPENED); ClickOnDialogViewAndWait(DialogViewID::PAYMENT_SHEET_SUMMARY_SECTION); } void PaymentRequestBrowserTestBase::OpenPaymentMethodScreen() { ResetEventWaiter(DialogEvent::PAYMENT_METHOD_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::OpenShippingAddressSectionScreen() { ResetEventWaiter(DialogEvent::SHIPPING_ADDRESS_SECTION_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::OpenShippingOptionSectionScreen() { ResetEventWaiter(DialogEvent::SHIPPING_OPTION_SECTION_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION); } void PaymentRequestBrowserTestBase::OpenContactInfoScreen() { ResetEventWaiter(DialogEvent::CONTACT_INFO_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::OpenCreditCardEditorScreen() { ResetEventWaiter(DialogEvent::CREDIT_CARD_EDITOR_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_METHOD_ADD_CARD_BUTTON)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::OpenShippingAddressEditorScreen() { ResetEventWaiter(DialogEvent::SHIPPING_ADDRESS_EDITOR_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_METHOD_ADD_SHIPPING_BUTTON)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::OpenContactInfoEditorScreen() { ResetEventWaiter(DialogEvent::CONTACT_INFO_EDITOR_OPENED); views::View* view = delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAYMENT_METHOD_ADD_CONTACT_BUTTON)); if (!view) { view = delegate_->dialog_view()->GetViewByID(static_cast<int>( DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON)); } EXPECT_TRUE(view); ClickOnDialogViewAndWait(view); } void PaymentRequestBrowserTestBase::ClickOnBackArrow() { ResetEventWaiter(DialogEvent::BACK_NAVIGATION); ClickOnDialogViewAndWait(DialogViewID::BACK_BUTTON); } void PaymentRequestBrowserTestBase::ClickOnCancel() { ResetEventWaiter(DialogEvent::DIALOG_CLOSED); ClickOnDialogViewAndWait(DialogViewID::CANCEL_BUTTON, false); } content::WebContents* PaymentRequestBrowserTestBase::GetActiveWebContents() { return browser()->tab_strip_model()->GetActiveWebContents(); } const std::vector<PaymentRequest*> PaymentRequestBrowserTestBase::GetPaymentRequests( content::WebContents* web_contents) { PaymentRequestWebContentsManager* manager = PaymentRequestWebContentsManager::GetOrCreateForWebContents(web_contents); if (!manager) return std::vector<PaymentRequest*>(); std::vector<PaymentRequest*> payment_requests_ptrs; for (const auto& p : manager->payment_requests_) payment_requests_ptrs.push_back(p.first); return payment_requests_ptrs; } autofill::PersonalDataManager* PaymentRequestBrowserTestBase::GetDataManager() { return autofill::PersonalDataManagerFactory::GetForProfile( Profile::FromBrowserContext(GetActiveWebContents()->GetBrowserContext())); } void PaymentRequestBrowserTestBase::AddAutofillProfile( const autofill::AutofillProfile& profile) { autofill::PersonalDataManager* personal_data_manager = GetDataManager(); size_t profile_count = personal_data_manager->GetProfiles().size(); PersonalDataLoadedObserverMock personal_data_observer; personal_data_manager->AddObserver(&personal_data_observer); base::RunLoop data_loop; EXPECT_CALL(personal_data_observer, OnPersonalDataFinishedProfileTasks()) .WillOnce(QuitMessageLoop(&data_loop)); EXPECT_CALL(personal_data_observer, OnPersonalDataChanged()) .Times(testing::AnyNumber()); personal_data_manager->AddProfile(profile); data_loop.Run(); personal_data_manager->RemoveObserver(&personal_data_observer); EXPECT_EQ(profile_count + 1, personal_data_manager->GetProfiles().size()); } void PaymentRequestBrowserTestBase::AddCreditCard( const autofill::CreditCard& card) { autofill::PersonalDataManager* personal_data_manager = GetDataManager(); if (card.record_type() != autofill::CreditCard::LOCAL_CARD) { personal_data_manager->AddServerCreditCardForTest( std::make_unique<autofill::CreditCard>(card)); return; } size_t card_count = personal_data_manager->GetCreditCards().size(); PersonalDataLoadedObserverMock personal_data_observer; personal_data_manager->AddObserver(&personal_data_observer); base::RunLoop data_loop; EXPECT_CALL(personal_data_observer, OnPersonalDataFinishedProfileTasks()) .WillOnce(QuitMessageLoop(&data_loop)); EXPECT_CALL(personal_data_observer, OnPersonalDataChanged()) .Times(testing::AnyNumber()); personal_data_manager->AddCreditCard(card); data_loop.Run(); personal_data_manager->RemoveObserver(&personal_data_observer); EXPECT_EQ(card_count + 1, personal_data_manager->GetCreditCards().size()); } void PaymentRequestBrowserTestBase::WaitForOnPersonalDataChanged() { autofill::PersonalDataManager* personal_data_manager = GetDataManager(); PersonalDataLoadedObserverMock personal_data_observer; personal_data_manager->AddObserver(&personal_data_observer); base::RunLoop run_loop; EXPECT_CALL(personal_data_observer, OnPersonalDataFinishedProfileTasks()) .WillOnce(QuitMessageLoop(&run_loop)); EXPECT_CALL(personal_data_observer, OnPersonalDataChanged()) .Times(testing::AnyNumber()); run_loop.Run(); } void PaymentRequestBrowserTestBase::CreatePaymentRequestForTest( mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, content::RenderFrameHost* render_frame_host) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); DCHECK(web_contents); std::unique_ptr<TestChromePaymentRequestDelegate> delegate = std::make_unique<TestChromePaymentRequestDelegate>( web_contents, this /* observer */, &prefs_, is_incognito_, is_valid_ssl_, is_browser_window_active_, skip_ui_for_basic_card_); delegate_ = delegate.get(); PaymentRequestWebContentsManager::GetOrCreateForWebContents(web_contents) ->CreatePaymentRequest(web_contents->GetMainFrame(), web_contents, std::move(delegate), std::move(receiver), this); } void PaymentRequestBrowserTestBase::ClickOnDialogViewAndWait( DialogViewID view_id, bool wait_for_animation) { ClickOnDialogViewAndWait(view_id, delegate_->dialog_view(), wait_for_animation); } void PaymentRequestBrowserTestBase::ClickOnDialogViewAndWait( DialogViewID view_id, PaymentRequestDialogView* dialog_view, bool wait_for_animation) { views::View* view = dialog_view->GetViewByID(static_cast<int>(view_id)); DCHECK(view); ClickOnDialogViewAndWait(view, dialog_view, wait_for_animation); } void PaymentRequestBrowserTestBase::ClickOnDialogViewAndWait( views::View* view, bool wait_for_animation) { ClickOnDialogViewAndWait(view, delegate_->dialog_view(), wait_for_animation); } void PaymentRequestBrowserTestBase::ClickOnDialogViewAndWait( views::View* view, PaymentRequestDialogView* dialog_view, bool wait_for_animation) { DCHECK(view); ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); view->OnMousePressed(pressed); ui::MouseEvent released_event = ui::MouseEvent( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); view->OnMouseReleased(released_event); if (wait_for_animation) WaitForAnimation(dialog_view); WaitForObservedEvent(); } void PaymentRequestBrowserTestBase::ClickOnChildInListViewAndWait( size_t child_index, size_t total_num_children, DialogViewID list_view_id, bool wait_for_animation) { views::View* list_view = dialog_view()->GetViewByID(static_cast<int>(list_view_id)); EXPECT_TRUE(list_view); EXPECT_EQ(total_num_children, list_view->children().size()); ClickOnDialogViewAndWait(list_view->children()[child_index], wait_for_animation); } std::vector<base::string16> PaymentRequestBrowserTestBase::GetProfileLabelValues( DialogViewID parent_view_id) { std::vector<base::string16> line_labels; views::View* parent_view = dialog_view()->GetViewByID(static_cast<int>(parent_view_id)); EXPECT_TRUE(parent_view); views::View* view = parent_view->GetViewByID( static_cast<int>(DialogViewID::PROFILE_LABEL_LINE_1)); if (view) line_labels.push_back(static_cast<views::Label*>(view)->GetText()); view = parent_view->GetViewByID( static_cast<int>(DialogViewID::PROFILE_LABEL_LINE_2)); if (view) line_labels.push_back(static_cast<views::Label*>(view)->GetText()); view = parent_view->GetViewByID( static_cast<int>(DialogViewID::PROFILE_LABEL_LINE_3)); if (view) line_labels.push_back(static_cast<views::Label*>(view)->GetText()); view = parent_view->GetViewByID( static_cast<int>(DialogViewID::PROFILE_LABEL_ERROR)); if (view) line_labels.push_back(static_cast<views::Label*>(view)->GetText()); return line_labels; } std::vector<base::string16> PaymentRequestBrowserTestBase::GetShippingOptionLabelValues( DialogViewID parent_view_id) { std::vector<base::string16> labels; views::View* parent_view = dialog_view()->GetViewByID(static_cast<int>(parent_view_id)); EXPECT_TRUE(parent_view); views::View* view = parent_view->GetViewByID( static_cast<int>(DialogViewID::SHIPPING_OPTION_DESCRIPTION)); DCHECK(view); labels.push_back(static_cast<views::Label*>(view)->GetText()); view = parent_view->GetViewByID( static_cast<int>(DialogViewID::SHIPPING_OPTION_AMOUNT)); DCHECK(view); labels.push_back(static_cast<views::Label*>(view)->GetText()); return labels; } void PaymentRequestBrowserTestBase::OpenCVCPromptWithCVC( const base::string16& cvc) { OpenCVCPromptWithCVC(cvc, delegate_->dialog_view()); } void PaymentRequestBrowserTestBase::OpenCVCPromptWithCVC( const base::string16& cvc, PaymentRequestDialogView* dialog_view) { ResetEventWaiter(DialogEvent::CVC_PROMPT_SHOWN); ClickOnDialogViewAndWait(DialogViewID::PAY_BUTTON, dialog_view); views::Textfield* cvc_field = static_cast<views::Textfield*>(dialog_view->GetViewByID( static_cast<int>(DialogViewID::CVC_PROMPT_TEXT_FIELD))); cvc_field->InsertOrReplaceText(cvc); } void PaymentRequestBrowserTestBase::PayWithCreditCardAndWait( const base::string16& cvc) { PayWithCreditCardAndWait(cvc, delegate_->dialog_view()); } void PaymentRequestBrowserTestBase::PayWithCreditCardAndWait( const base::string16& cvc, PaymentRequestDialogView* dialog_view) { OpenCVCPromptWithCVC(cvc, dialog_view); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); ClickOnDialogViewAndWait(DialogViewID::CVC_PROMPT_CONFIRM_BUTTON, dialog_view); } void PaymentRequestBrowserTestBase::PayWithCreditCard( const base::string16& cvc) { OpenCVCPromptWithCVC(cvc, delegate_->dialog_view()); ResetEventWaiter(DialogEvent::PROCESSING_SPINNER_SHOWN); ClickOnDialogViewAndWait(DialogViewID::CVC_PROMPT_CONFIRM_BUTTON, delegate_->dialog_view()); } void PaymentRequestBrowserTestBase::RetryPaymentRequest( const std::string& validation_errors, PaymentRequestDialogView* dialog_view) { EXPECT_EQ(2U, dialog_view->view_stack_for_testing()->size()); ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::SPEC_DONE_UPDATING, DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::BACK_TO_PAYMENT_SHEET_NAVIGATION}); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "retry(" + validation_errors + ");")); WaitForObservedEvent(); } void PaymentRequestBrowserTestBase::RetryPaymentRequest( const std::string& validation_errors, const DialogEvent& dialog_event, PaymentRequestDialogView* dialog_view) { EXPECT_EQ(2U, dialog_view->view_stack_for_testing()->size()); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::SPEC_DONE_UPDATING, DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::BACK_TO_PAYMENT_SHEET_NAVIGATION, dialog_event}); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "retry(" + validation_errors + ");")); WaitForObservedEvent(); } base::string16 PaymentRequestBrowserTestBase::GetEditorTextfieldValue( autofill::ServerFieldType type) { ValidatingTextfield* textfield = static_cast<ValidatingTextfield*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(textfield); return textfield->GetText(); } void PaymentRequestBrowserTestBase::SetEditorTextfieldValue( const base::string16& value, autofill::ServerFieldType type) { ValidatingTextfield* textfield = static_cast<ValidatingTextfield*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(textfield); textfield->SetText(base::string16()); textfield->InsertText(value); textfield->OnBlur(); } base::string16 PaymentRequestBrowserTestBase::GetComboboxValue( autofill::ServerFieldType type) { ValidatingCombobox* combobox = static_cast<ValidatingCombobox*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(combobox); return combobox->model()->GetItemAt(combobox->GetSelectedIndex()); } void PaymentRequestBrowserTestBase::SetComboboxValue( const base::string16& value, autofill::ServerFieldType type) { ValidatingCombobox* combobox = static_cast<ValidatingCombobox*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(combobox); SelectComboboxRowForValue(combobox, value); combobox->OnBlur(); } void PaymentRequestBrowserTestBase::SelectBillingAddress( const std::string& billing_address_id) { views::Combobox* address_combobox( static_cast<views::Combobox*>(dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(kBillingAddressType)))); ASSERT_NE(address_combobox, nullptr); autofill::AddressComboboxModel* address_combobox_model( static_cast<autofill::AddressComboboxModel*>(address_combobox->model())); address_combobox->SetSelectedRow( address_combobox_model->GetIndexOfIdentifier(billing_address_id)); address_combobox->OnBlur(); } bool PaymentRequestBrowserTestBase::IsEditorTextfieldInvalid( autofill::ServerFieldType type) { ValidatingTextfield* textfield = static_cast<ValidatingTextfield*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(textfield); return textfield->GetInvalid(); } bool PaymentRequestBrowserTestBase::IsEditorComboboxInvalid( autofill::ServerFieldType type) { ValidatingCombobox* combobox = static_cast<ValidatingCombobox*>(delegate_->dialog_view()->GetViewByID( EditorViewController::GetInputFieldViewId(type))); DCHECK(combobox); return combobox->GetInvalid(); } bool PaymentRequestBrowserTestBase::IsPayButtonEnabled() { views::Button* button = static_cast<views::Button*>(delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAY_BUTTON))); DCHECK(button); return button->GetEnabled(); } base::string16 PaymentRequestBrowserTestBase::GetPrimaryButtonLabel() const { return static_cast<views::MdTextButton*>( delegate_->dialog_view()->GetViewByID( static_cast<int>(DialogViewID::PAY_BUTTON))) ->GetText(); } void PaymentRequestBrowserTestBase::WaitForAnimation() { WaitForAnimation(delegate_->dialog_view()); } void PaymentRequestBrowserTestBase::WaitForAnimation( PaymentRequestDialogView* dialog_view) { ViewStack* view_stack = dialog_view->view_stack_for_testing(); if (view_stack->slide_in_animator_->IsAnimating()) { view_stack->slide_in_animator_->SetAnimationDuration( base::TimeDelta::FromMilliseconds(1)); view_stack->slide_in_animator_->SetAnimationDelegate( view_stack->top(), std::unique_ptr<gfx::AnimationDelegate>( new gfx::TestAnimationDelegate())); base::RunLoop().Run(); } else if (view_stack->slide_out_animator_->IsAnimating()) { view_stack->slide_out_animator_->SetAnimationDuration( base::TimeDelta::FromMilliseconds(1)); view_stack->slide_out_animator_->SetAnimationDelegate( view_stack->top(), std::unique_ptr<gfx::AnimationDelegate>( new gfx::TestAnimationDelegate())); base::RunLoop().Run(); } } const base::string16& PaymentRequestBrowserTestBase::GetLabelText( DialogViewID view_id) { views::View* view = dialog_view()->GetViewByID(static_cast<int>(view_id)); DCHECK(view); return static_cast<views::Label*>(view)->GetText(); } const base::string16& PaymentRequestBrowserTestBase::GetStyledLabelText( DialogViewID view_id) { views::View* view = dialog_view()->GetViewByID(static_cast<int>(view_id)); DCHECK(view); return static_cast<views::StyledLabel*>(view)->GetText(); } const base::string16& PaymentRequestBrowserTestBase::GetErrorLabelForType( autofill::ServerFieldType type) { views::View* view = dialog_view()->GetViewByID( static_cast<int>(DialogViewID::ERROR_LABEL_OFFSET) + type); DCHECK(view); return static_cast<views::Label*>(view)->GetText(); } void PaymentRequestBrowserTestBase::SetCanMakePaymentEnabledPref( bool can_make_payment_enabled) { prefs_.SetBoolean(kCanMakePaymentEnabled, can_make_payment_enabled); } void PaymentRequestBrowserTestBase::ResetEventWaiter(DialogEvent event) { event_waiter_ = std::make_unique<autofill::EventWaiter<DialogEvent>>( std::list<DialogEvent>{event}); } void PaymentRequestBrowserTestBase::ResetEventWaiterForSequence( std::list<DialogEvent> event_sequence) { event_waiter_ = std::make_unique<autofill::EventWaiter<DialogEvent>>( std::move(event_sequence)); } void PaymentRequestBrowserTestBase::ResetEventWaiterForDialogOpened() { ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::DIALOG_OPENED}); } void PaymentRequestBrowserTestBase::WaitForObservedEvent() { event_waiter_->Wait(); } } // namespace payments std::ostream& operator<<( std::ostream& out, payments::PaymentRequestBrowserTestBase::DialogEvent event) { using DialogEvent = payments::PaymentRequestBrowserTestBase::DialogEvent; switch (event) { case DialogEvent::DIALOG_OPENED: out << "DIALOG_OPENED"; break; case DialogEvent::DIALOG_CLOSED: out << "DIALOG_CLOSED"; break; case DialogEvent::ORDER_SUMMARY_OPENED: out << "ORDER_SUMMARY_OPENED"; break; case DialogEvent::PAYMENT_METHOD_OPENED: out << "PAYMENT_METHOD_OPENED"; break; case DialogEvent::SHIPPING_ADDRESS_SECTION_OPENED: out << "SHIPPING_ADDRESS_SECTION_OPENED"; break; case DialogEvent::SHIPPING_OPTION_SECTION_OPENED: out << "SHIPPING_OPTION_SECTION_OPENED"; break; case DialogEvent::CREDIT_CARD_EDITOR_OPENED: out << "CREDIT_CARD_EDITOR_OPENED"; break; case DialogEvent::SHIPPING_ADDRESS_EDITOR_OPENED: out << "SHIPPING_ADDRESS_EDITOR_OPENED"; break; case DialogEvent::CONTACT_INFO_EDITOR_OPENED: out << "CONTACT_INFO_EDITOR_OPENED"; break; case DialogEvent::BACK_NAVIGATION: out << "BACK_NAVIGATION"; break; case DialogEvent::BACK_TO_PAYMENT_SHEET_NAVIGATION: out << "BACK_TO_PAYMENT_SHEET_NAVIGATION"; break; case DialogEvent::CONTACT_INFO_OPENED: out << "CONTACT_INFO_OPENED"; break; case DialogEvent::EDITOR_VIEW_UPDATED: out << "EDITOR_VIEW_UPDATED"; break; case DialogEvent::CAN_MAKE_PAYMENT_CALLED: out << "CAN_MAKE_PAYMENT_CALLED"; break; case DialogEvent::CAN_MAKE_PAYMENT_RETURNED: out << "CAN_MAKE_PAYMENT_RETURNED"; break; case DialogEvent::HAS_ENROLLED_INSTRUMENT_CALLED: out << "HAS_ENROLLED_INSTRUMENT_CALLED"; break; case DialogEvent::HAS_ENROLLED_INSTRUMENT_RETURNED: out << "HAS_ENROLLED_INSTRUMENT_RETURNED"; break; case DialogEvent::ERROR_MESSAGE_SHOWN: out << "ERROR_MESSAGE_SHOWN"; break; case DialogEvent::SPEC_DONE_UPDATING: out << "SPEC_DONE_UPDATING"; break; case DialogEvent::CVC_PROMPT_SHOWN: out << "CVC_PROMPT_SHOWN"; break; case DialogEvent::NOT_SUPPORTED_ERROR: out << "NOT_SUPPORTED_ERROR"; break; case DialogEvent::ABORT_CALLED: out << "ABORT_CALLED"; break; case DialogEvent::PROCESSING_SPINNER_SHOWN: out << "PROCESSING_SPINNER_SHOWN"; break; case DialogEvent::PROCESSING_SPINNER_HIDDEN: out << "PROCESSING_SPINNER_HIDDEN"; break; } return out; }
36.627706
80
0.760992
sarang-apps
90c5c4d35c216fd5a4f689cbbb4f551bb9a5174f
3,313
cpp
C++
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
#include <GameEnginePCH.h> #include <Core/WorldSerializer/WorldReader.h> #include <Core/WorldSerializer/WorldWriter.h> #include <Foundation/Configuration/Singleton.h> #include <Foundation/Profiling/Profiling.h> #include <GameEngine/VirtualReality/DeviceTrackingComponent.h> #include <GameEngine/VirtualReality/StageSpaceComponent.h> ////////////////////////////////////////////////////////////////////////// // clang-format off EZ_BEGIN_STATIC_REFLECTED_ENUM(ezVRTransformSpace, 1) EZ_BITFLAGS_CONSTANTS(ezVRTransformSpace::Local, ezVRTransformSpace::Global) EZ_END_STATIC_REFLECTED_ENUM; EZ_BEGIN_COMPONENT_TYPE(ezDeviceTrackingComponent, 1, ezComponentMode::Dynamic) { EZ_BEGIN_PROPERTIES { EZ_ENUM_ACCESSOR_PROPERTY("DeviceType", ezVRDeviceType, GetDeviceType, SetDeviceType), EZ_ENUM_ACCESSOR_PROPERTY("TransformSpace", ezVRTransformSpace, GetTransformSpace, SetTransformSpace) } EZ_END_PROPERTIES; EZ_BEGIN_ATTRIBUTES { new ezCategoryAttribute("Virtual Reality"), } EZ_END_ATTRIBUTES; } EZ_END_COMPONENT_TYPE // clang-format on ezDeviceTrackingComponent::ezDeviceTrackingComponent() = default; ezDeviceTrackingComponent::~ezDeviceTrackingComponent() = default; void ezDeviceTrackingComponent::SetDeviceType(ezEnum<ezVRDeviceType> type) { m_deviceType = type; } ezEnum<ezVRDeviceType> ezDeviceTrackingComponent::GetDeviceType() const { return m_deviceType; } void ezDeviceTrackingComponent::SetTransformSpace(ezEnum<ezVRTransformSpace> space) { m_space = space; } ezEnum<ezVRTransformSpace> ezDeviceTrackingComponent::GetTransformSpace() const { return m_space; } void ezDeviceTrackingComponent::SerializeComponent(ezWorldWriter& stream) const { SUPER::SerializeComponent(stream); ezStreamWriter& s = stream.GetStream(); s << m_deviceType; s << m_space; } void ezDeviceTrackingComponent::DeserializeComponent(ezWorldReader& stream) { SUPER::DeserializeComponent(stream); // const ezUInt32 uiVersion = stream.GetComponentTypeVersion(GetStaticRTTI()); ezStreamReader& s = stream.GetStream(); s >> m_deviceType; s >> m_space; } void ezDeviceTrackingComponent::Update() { if (ezVRInterface* pVRInterface = ezSingletonRegistry::GetSingletonInstance<ezVRInterface>()) { ezVRDeviceID deviceID = pVRInterface->GetDeviceIDByType(m_deviceType); if (deviceID != -1) { const ezVRDeviceState& state = pVRInterface->GetDeviceState(deviceID); if (state.m_bPoseIsValid) { if (m_space == ezVRTransformSpace::Local) { GetOwner()->SetLocalPosition(state.m_vPosition); GetOwner()->SetLocalRotation(state.m_qRotation); } else { ezTransform add; add.SetIdentity(); if (const ezStageSpaceComponentManager* pStageMan = GetWorld()->GetComponentManager<ezStageSpaceComponentManager>()) { if (const ezStageSpaceComponent* pStage = pStageMan->GetSingletonComponent()) { add = pStage->GetOwner()->GetGlobalTransform(); } } ezTransform local(state.m_vPosition, state.m_qRotation); GetOwner()->SetGlobalTransform(local * add); } } } } } EZ_STATICLINK_FILE(GameEngine, GameEngine_VirtualReality_Implementation_DeviceTrackingComponent);
29.318584
126
0.728041
fereeh
90c6154eb2f96f95ae35b71ae2cb9827cae4fa49
123
cpp
C++
dbmodel/persistent.cpp
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
null
null
null
dbmodel/persistent.cpp
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
1
2015-08-21T06:31:32.000Z
2015-08-21T06:32:06.000Z
dbmodel/persistent.cpp
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
1
2016-07-23T04:03:15.000Z
2016-07-23T04:03:15.000Z
//persistent.cpp //copyright : Copyright (c) 2014 arsee. //license : GNU GPL v2. //author : arsee #include "persistent.h"
17.571429
39
0.691057
arsee11
90c6fd3a1c859d2efea4b58afc025bca63b6c205
2,487
cpp
C++
src_R/culex.cpp
slwu89/culex-model
eee653b2b633b26b735034303e21e3a67341c119
[ "MIT" ]
null
null
null
src_R/culex.cpp
slwu89/culex-model
eee653b2b633b26b735034303e21e3a67341c119
[ "MIT" ]
null
null
null
src_R/culex.cpp
slwu89/culex-model
eee653b2b633b26b735034303e21e3a67341c119
[ "MIT" ]
null
null
null
#include "culex.hpp" // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::plugins(cpp14)]] // ---------- stochastic model interface ---------- using culex_stochastic = culex<int>; // [[Rcpp::export]] Rcpp::XPtr<culex_stochastic> create_culex_stochastic(const int p, const std::vector<int>& tau_E, const std::vector<int>& tau_L, const std::vector<int>& tau_P, const double dt, const arma::Mat<double>& psi) { return Rcpp::XPtr<culex_stochastic>( new culex<int>(p, tau_E, tau_L, tau_P, dt, psi), true ); }; // [[Rcpp::export]] void step_culex_stochastic(Rcpp::XPtr<culex_stochastic> mod, const Rcpp::List& parameters) { mod->update(parameters); } // [[Rcpp::export]] void set_A_stochastic(Rcpp::XPtr<culex_stochastic> mod, arma::Row<int> A) { mod->A = A; }; // [[Rcpp::export]] arma::Row<int> get_A_stochastic(Rcpp::XPtr<culex_stochastic> mod) { return mod->A; }; // [[Rcpp::export]] arma::Row<int> get_E_stochastic(Rcpp::XPtr<culex_stochastic> mod) { return arma::sum(mod->E, 0); }; // [[Rcpp::export]] arma::Row<int> get_L_stochastic(Rcpp::XPtr<culex_stochastic> mod) { return arma::sum(mod->L, 0); }; // [[Rcpp::export]] arma::Row<int> get_P_stochastic(Rcpp::XPtr<culex_stochastic> mod) { return arma::sum(mod->P, 0); }; // ---------- deterministic model interface ---------- using culex_deterministic = culex<double>; // [[Rcpp::export]] Rcpp::XPtr<culex_deterministic> create_culex_deterministic(const int p, const std::vector<int>& tau_E, const std::vector<int>& tau_L, const std::vector<int>& tau_P, const double dt, const arma::Mat<double>& psi) { return Rcpp::XPtr<culex_deterministic>( new culex<double>(p, tau_E, tau_L, tau_P, dt, psi), true ); }; // [[Rcpp::export]] void step_culex_deterministic(Rcpp::XPtr<culex_deterministic> mod, const Rcpp::List& parameters) { mod->update(parameters); } // [[Rcpp::export]] void set_A_deterministic(Rcpp::XPtr<culex_deterministic> mod, arma::Row<double> A) { mod->A = A; }; // [[Rcpp::export]] arma::Row<double> get_A_deterministic(Rcpp::XPtr<culex_deterministic> mod) { return mod->A; }; // [[Rcpp::export]] arma::Row<double> get_E_deterministic(Rcpp::XPtr<culex_deterministic> mod) { return arma::sum(mod->E, 0); }; // [[Rcpp::export]] arma::Row<double> get_L_deterministic(Rcpp::XPtr<culex_deterministic> mod) { return arma::sum(mod->L, 0); }; // [[Rcpp::export]] arma::Row<double> get_P_deterministic(Rcpp::XPtr<culex_deterministic> mod) { return arma::sum(mod->P, 0); };
27.633333
213
0.676719
slwu89
90c7946c59987651ee16b40cd64210aaabe2a9ca
1,273
hpp
C++
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
7
2019-08-22T20:48:15.000Z
2021-12-31T16:08:59.000Z
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
10
2019-08-22T21:40:43.000Z
2020-09-03T14:21:21.000Z
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
2
2019-08-22T21:08:28.000Z
2019-08-23T21:31:56.000Z
#ifndef VIRTPP_ENUM_STORAGE_VOLRESIZEFLAG_HPP #define VIRTPP_ENUM_STORAGE_VOLRESIZEFLAG_HPP #include "../../StorageVol.hpp" #include "virt_wrap/enums/Base.hpp" #include "virt_wrap/utility.hpp" #include <libvirt/libvirt-storage.h> namespace virt { class StorageVol::ResizeFlag : private VirtEnumStorage<virStorageVolResizeFlags>, public VirtEnumBase<ResizeFlag>, public EnumSetHelper<ResizeFlag> { friend VirtEnumBase<ResizeFlag>; friend EnumSetHelper<ResizeFlag>; enum class Underlying { ALLOCATE = VIR_STORAGE_VOL_RESIZE_ALLOCATE, /* force allocation of new size */ DELTA = VIR_STORAGE_VOL_RESIZE_DELTA, /* size is relative to current */ SHRINK = VIR_STORAGE_VOL_RESIZE_SHRINK, /* allow decrease in capacity */ } constexpr static default_value{}; protected: constexpr static std::array values = {"allocate", "delta", "shrink"}; public: using VirtEnumBase::VirtEnumBase; constexpr static auto from_string(std::string_view sv) { return EnumSetHelper{}.from_string_base(sv); } // using enum Underlying; constexpr static auto ALLOCATE = Underlying::ALLOCATE; constexpr static auto DELTA = Underlying::DELTA; constexpr static auto SHRINK = Underlying::SHRINK; }; } // namespace virt #endif
38.575758
149
0.744698
AeroStun
90c9563d52c67684b1bee6efdd96acaca6843d38
13,863
cpp
C++
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution(the "License").All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file.Do not * remove or modify any license notices.This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "WwiseBuilderComponent.h" #include <AzCore/Debug/Trace.h> #include <AzCore/IO/SystemFile.h> #include <AzCore/JSON/rapidjson.h> #include <AzCore/JSON/document.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzFramework/IO/LocalFileIO.h> #include <AzFramework/StringFunc/StringFunc.h> namespace WwiseBuilder { const char WwiseBuilderWindowName[] = "WwiseBuilder"; namespace Internal { const char SoundbankExtension[] = ".bnk"; const char SoundbankDependencyFileExtension[] = ".bankdeps"; const char InitBankFullFileName[] = "init.bnk"; const char JsonDependencyKey[] = "dependencies"; AZ::Outcome<AZStd::string, AZStd::string> GetDependenciesFromMetadata(const rapidjson::Value& rootObject, AZStd::vector<AZStd::string>& fileNames) { if (!rootObject.IsObject()) { return AZ::Failure(AZStd::string("The root of the metadata file is not an object. Please regenerate the metadata for this soundbank.")); } // If the file doesn't define a dependency field, then there are no dependencies. if (!rootObject.HasMember(JsonDependencyKey)) { AZStd::string addingDefaultDependencyWarning = AZStd::string::format( "Dependencies array does not exist. The file was likely manually edited. Registering a default " "dependency on %s. Please regenerate the metadata for this bank.", InitBankFullFileName); return AZ::Success(addingDefaultDependencyWarning); } const rapidjson::Value& dependenciesArray = rootObject[JsonDependencyKey]; if (!dependenciesArray.IsArray()) { return AZ::Failure(AZStd::string("Dependency field is not an array. Please regenerate the metadata for this soundbank.")); } for (rapidjson::SizeType dependencyIndex = 0; dependencyIndex < dependenciesArray.Size(); ++dependencyIndex) { fileNames.push_back(dependenciesArray[dependencyIndex].GetString()); } // The dependency array is empty, which likely means it was modified by hand. However, every bank is dependent // on init.bnk (other than itself), so just force add it as a dependency here. and emit a warning. if (fileNames.size() == 0) { AZStd::string addingDefaultDependencyWarning = AZStd::string::format( "Dependencies array is empty. The file was likely manually edited. Registering a default " "dependency on %s. Please regenerate the metadata for this bank.", InitBankFullFileName); return AZ::Success(addingDefaultDependencyWarning); } // Make sure init.bnk is in the dependency list. Force add it if it's not else if (AZStd::find(fileNames.begin(), fileNames.end(), InitBankFullFileName) == fileNames.end()) { AZStd::string addingDefaultDependencyWarning = AZStd::string::format( "Dependencies does not contain the initialization bank. The file was likely manually edited to remove " "it, however it is necessary for all banks to have the initialization bank loaded. Registering a " "default dependency on %s. Please regenerate the metadata for this bank.", InitBankFullFileName); fileNames.push_back(InitBankFullFileName); return AZ::Success(addingDefaultDependencyWarning); } return AZ::Success(AZStd::string()); } } BuilderPluginComponent::BuilderPluginComponent() { } BuilderPluginComponent::~BuilderPluginComponent() { } void BuilderPluginComponent::Init() { } void BuilderPluginComponent::Activate() { // Register Wwise builder AssetBuilderSDK::AssetBuilderDesc builderDescriptor; builderDescriptor.m_name = "WwiseBuilderWorker"; builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.bnk", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.wem", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); builderDescriptor.m_busId = WwiseBuilderWorker::GetUUID(); builderDescriptor.m_version = 2; builderDescriptor.m_createJobFunction = AZStd::bind(&WwiseBuilderWorker::CreateJobs, &m_wwiseBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); builderDescriptor.m_processJobFunction = AZStd::bind(&WwiseBuilderWorker::ProcessJob, &m_wwiseBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); // (optimization) this builder does not emit source dependencies: builderDescriptor.m_flags |= AssetBuilderSDK::AssetBuilderDesc::BF_EmitsNoDependencies; m_wwiseBuilder.BusConnect(builderDescriptor.m_busId); AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBus::Events::RegisterBuilderInformation, builderDescriptor); } void BuilderPluginComponent::Deactivate() { m_wwiseBuilder.BusDisconnect(); } void BuilderPluginComponent::Reflect(AZ::ReflectContext* context) { } WwiseBuilderWorker::WwiseBuilderWorker() { } WwiseBuilderWorker::~WwiseBuilderWorker() { } void WwiseBuilderWorker::ShutDown() { // This will be called on a different thread than the process job thread m_isShuttingDown = true; } AZ::Uuid WwiseBuilderWorker::GetUUID() { return AZ::Uuid::CreateString("{85224E40-9211-4C05-9397-06E056470171}"); } // This happens early on in the file scanning pass. // This function should always create the same jobs and not do any checking whether the job is up to date. void WwiseBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) { if (m_isShuttingDown) { response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown; return; } for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms) { AssetBuilderSDK::JobDescriptor descriptor; descriptor.m_jobKey = "Wwise"; descriptor.m_critical = true; descriptor.SetPlatformIdentifier(info.m_identifier.c_str()); descriptor.m_priority = 0; response.m_createJobOutputs.push_back(descriptor); } response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; } // The request will contain the CreateJobResponse you constructed earlier, including any keys and // values you placed into the hash table void WwiseBuilderWorker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) { AZ_TracePrintf(AssetBuilderSDK::InfoWindow, "Starting Job.\n"); AZStd::string fileName; AzFramework::StringFunc::Path::GetFullFileName(request.m_fullPath.c_str(), fileName); if (m_isShuttingDown) { AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Cancelled job %s because shutdown was requested.\n", request.m_fullPath.c_str()); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled; return; } else { response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; AssetBuilderSDK::JobProduct jobProduct(request.m_fullPath); // if the file is a bnk AZStd::string requestExtension; if (AzFramework::StringFunc::Path::GetExtension(request.m_fullPath.c_str(), requestExtension) && requestExtension == Internal::SoundbankExtension) { AssetBuilderSDK::ProductPathDependencySet dependencyPaths; // Push assets back into the response's product list // Assets you created in your temp path can be specified using paths relative to the temp path // since that is assumed where you're writing stuff. AZ::Outcome<AZStd::string, AZStd::string> gatherProductDependenciesResponse = GatherProductDependencies(request.m_fullPath, request.m_sourceFile, dependencyPaths); if (!gatherProductDependenciesResponse.IsSuccess()) { AZ_Error(WwiseBuilderWindowName, false, "Dependency gathering for %s failed. %s", request.m_fullPath.c_str(), gatherProductDependenciesResponse.GetError().c_str()); } else { if (gatherProductDependenciesResponse.GetValue().empty()) { AZ_Warning(WwiseBuilderWindowName, false, gatherProductDependenciesResponse.GetValue().c_str()); } jobProduct.m_pathDependencies = AZStd::move(dependencyPaths); } } jobProduct.m_dependenciesHandled = true; // We've output the dependencies immediately above so it's OK to tell the AP we've handled dependencies response.m_outputProducts.push_back(jobProduct); } } AZ::Outcome<AZStd::string, AZStd::string> WwiseBuilderWorker::GatherProductDependencies(const AZStd::string& fullPath, const AZStd::string& relativePath, AssetBuilderSDK::ProductPathDependencySet& dependencies) { AZStd::string bankMetadataPath = fullPath; AzFramework::StringFunc::Path::ReplaceExtension(bankMetadataPath, Internal::SoundbankDependencyFileExtension); AZStd::string relativeSoundsPath = relativePath; AzFramework::StringFunc::Path::StripFullName(relativeSoundsPath); AZStd::string success_message; // Look for the corresponding .bankdeps file next to the bank itself. if (!AZ::IO::SystemFile::Exists(bankMetadataPath.c_str())) { // If this is the init bank, skip it. Otherwise, register the init bank as a dependency, and warn that a full // dependency graph can't be created without a .bankdeps file for the bank. AZStd::string requestFileName; AzFramework::StringFunc::Path::GetFullFileName(fullPath.c_str(), requestFileName); if (requestFileName != Internal::InitBankFullFileName) { success_message = AZStd::string::format("Failed to find the metadata file %s for soundbank %s. Full dependency information cannot be determined without the metadata file. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str(), fullPath.c_str()); } return AZ::Success(success_message); } AZ::u64 fileSize = AZ::IO::SystemFile::Length(bankMetadataPath.c_str()); if (fileSize == 0) { return AZ::Failure(AZStd::string::format("Soundbank metadata file at path %s is an empty file. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str())); } AZStd::vector<char> buffer(fileSize + 1); buffer[fileSize] = 0; if (!AZ::IO::SystemFile::Read(bankMetadataPath.c_str(), buffer.data())) { return AZ::Failure(AZStd::string::format("Failed to read the soundbank metadata file at path %s. Please make sure the file is not open or being edited by another program.", bankMetadataPath.c_str())); } // load the file rapidjson::Document bankMetadataDoc; bankMetadataDoc.Parse(buffer.data()); if (bankMetadataDoc.GetParseError() != rapidjson::ParseErrorCode::kParseErrorNone) { return AZ::Failure(AZStd::string::format("Failed to parse soundbank metadata at path %s into JSON. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str())); } AZStd::vector<AZStd::string> wwiseFiles; AZ::Outcome<AZStd::string, AZStd::string> gatherDependenciesResult = Internal::GetDependenciesFromMetadata(bankMetadataDoc, wwiseFiles); if (!gatherDependenciesResult.IsSuccess()) { return AZ::Failure(AZStd::string::format("Failed to gather dependencies for %s from metadata file %s. %s", fullPath.c_str(), bankMetadataPath.c_str(), gatherDependenciesResult.GetError().c_str())); } else if (!gatherDependenciesResult.GetValue().empty()) { success_message = AZStd::string::format("Dependency information for %s was unavailable in the metadata file %s. %s", fullPath.c_str(), bankMetadataPath.c_str(), gatherDependenciesResult.GetValue().c_str()); } // Register dependencies stored in the file to the job response. (they'll be relative to the bank itself.) for (const AZStd::string& wwiseFile : wwiseFiles) { dependencies.emplace(relativeSoundsPath + wwiseFile, AssetBuilderSDK::ProductPathDependencyType::ProductFile); } return AZ::Success(success_message); } }
48.81338
284
0.664575
yuriy0
90cd7835b25fa9b3b79bec0ea988af5651b6cb3d
80,931
cpp
C++
CWE-399/source_files/CVE-2013-1674/firefox_20.0b7_CVE_2013_1674_content_base_src_nsFrameLoader.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-399/source_files/CVE-2013-1674/firefox_20.0b7_CVE_2013_1674_content_base_src_nsFrameLoader.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-399/source_files/CVE-2013-1674/firefox_20.0b7_CVE_2013_1674_content_base_src_nsFrameLoader.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 sw=2 et tw=78: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Class for managing loading of a subframe (creation of the docshell, * handling of loads in it, recursion-checking). */ #include "base/basictypes.h" #include "prenv.h" #include "mozIApplication.h" #include "nsIDOMHTMLIFrameElement.h" #include "nsIDOMHTMLFrameElement.h" #include "nsIDOMMozBrowserFrame.h" #include "nsIDOMWindow.h" #include "nsIPresShell.h" #include "nsIContent.h" #include "nsIContentViewer.h" #include "nsIDocument.h" #include "nsIDOMDocument.h" #include "nsIDOMFile.h" #include "nsPIDOMWindow.h" #include "nsIWebNavigation.h" #include "nsIWebProgress.h" #include "nsIDocShell.h" #include "nsIDocShellTreeItem.h" #include "nsIDocShellTreeNode.h" #include "nsIDocShellTreeOwner.h" #include "nsIDocShellLoadInfo.h" #include "nsIDOMApplicationRegistry.h" #include "nsIBaseWindow.h" #include "nsContentUtils.h" #include "nsIXPConnect.h" #include "nsIJSContextStack.h" #include "nsUnicharUtils.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptSecurityManager.h" #include "nsIScrollable.h" #include "nsFrameLoader.h" #include "nsIDOMEventTarget.h" #include "nsIFrame.h" #include "nsIScrollableFrame.h" #include "nsSubDocumentFrame.h" #include "nsError.h" #include "nsGUIEvent.h" #include "nsEventDispatcher.h" #include "nsISHistory.h" #include "nsISHistoryInternal.h" #include "nsIDocShellHistory.h" #include "nsIDOMHTMLDocument.h" #include "nsIXULWindow.h" #include "nsIEditor.h" #include "nsIEditorDocShell.h" #include "nsIMozBrowserFrame.h" #include "nsIPermissionManager.h" #include "nsLayoutUtils.h" #include "nsView.h" #include "nsAsyncDOMEvent.h" #include "nsIURI.h" #include "nsIURL.h" #include "nsNetUtil.h" #include "nsGkAtoms.h" #include "nsINameSpaceManager.h" #include "nsThreadUtils.h" #include "nsIDOMChromeWindow.h" #include "nsInProcessTabChildGlobal.h" #include "Layers.h" #include "AppProcessPermissions.h" #include "ContentParent.h" #include "TabParent.h" #include "mozilla/GuardObjects.h" #include "mozilla/Preferences.h" #include "mozilla/unused.h" #include "mozilla/dom/Element.h" #include "mozilla/layout/RenderFrameParent.h" #include "nsIAppsService.h" #include "jsapi.h" #include "nsHTMLIFrameElement.h" #include "nsSandboxFlags.h" #include "mozilla/dom/StructuredCloneUtils.h" #ifdef MOZ_XUL #include "nsXULPopupManager.h" #endif using namespace mozilla; using namespace mozilla::dom; using namespace mozilla::dom::ipc; using namespace mozilla::layers; using namespace mozilla::layout; typedef FrameMetrics::ViewID ViewID; class nsAsyncDocShellDestroyer : public nsRunnable { public: nsAsyncDocShellDestroyer(nsIDocShell* aDocShell) : mDocShell(aDocShell) { } NS_IMETHOD Run() { nsCOMPtr<nsIBaseWindow> base_win(do_QueryInterface(mDocShell)); if (base_win) { base_win->Destroy(); } return NS_OK; } nsRefPtr<nsIDocShell> mDocShell; }; NS_IMPL_ISUPPORTS1(nsContentView, nsIContentView) bool nsContentView::IsRoot() const { return mScrollId == FrameMetrics::ROOT_SCROLL_ID; } nsresult nsContentView::Update(const ViewConfig& aConfig) { if (aConfig == mConfig) { return NS_OK; } mConfig = aConfig; // View changed. Try to locate our subdoc frame and invalidate // it if found. if (!mFrameLoader) { if (IsRoot()) { // Oops, don't have a frame right now. That's OK; the view // config persists and will apply to the next frame we get, if we // ever get one. return NS_OK; } else { // This view is no longer valid. return NS_ERROR_NOT_AVAILABLE; } } if (RenderFrameParent* rfp = mFrameLoader->GetCurrentRemoteFrame()) { rfp->ContentViewScaleChanged(this); } return NS_OK; } NS_IMETHODIMP nsContentView::ScrollTo(float aXpx, float aYpx) { ViewConfig config(mConfig); config.mScrollOffset = nsPoint(nsPresContext::CSSPixelsToAppUnits(aXpx), nsPresContext::CSSPixelsToAppUnits(aYpx)); return Update(config); } NS_IMETHODIMP nsContentView::ScrollBy(float aDXpx, float aDYpx) { ViewConfig config(mConfig); config.mScrollOffset.MoveBy(nsPresContext::CSSPixelsToAppUnits(aDXpx), nsPresContext::CSSPixelsToAppUnits(aDYpx)); return Update(config); } NS_IMETHODIMP nsContentView::SetScale(float aXScale, float aYScale) { ViewConfig config(mConfig); config.mXScale = aXScale; config.mYScale = aYScale; return Update(config); } NS_IMETHODIMP nsContentView::GetScrollX(float* aViewScrollX) { *aViewScrollX = nsPresContext::AppUnitsToFloatCSSPixels( mConfig.mScrollOffset.x); return NS_OK; } NS_IMETHODIMP nsContentView::GetScrollY(float* aViewScrollY) { *aViewScrollY = nsPresContext::AppUnitsToFloatCSSPixels( mConfig.mScrollOffset.y); return NS_OK; } NS_IMETHODIMP nsContentView::GetViewportWidth(float* aWidth) { *aWidth = nsPresContext::AppUnitsToFloatCSSPixels(mViewportSize.width); return NS_OK; } NS_IMETHODIMP nsContentView::GetViewportHeight(float* aHeight) { *aHeight = nsPresContext::AppUnitsToFloatCSSPixels(mViewportSize.height); return NS_OK; } NS_IMETHODIMP nsContentView::GetContentWidth(float* aWidth) { *aWidth = nsPresContext::AppUnitsToFloatCSSPixels(mContentSize.width); return NS_OK; } NS_IMETHODIMP nsContentView::GetContentHeight(float* aHeight) { *aHeight = nsPresContext::AppUnitsToFloatCSSPixels(mContentSize.height); return NS_OK; } NS_IMETHODIMP nsContentView::GetId(nsContentViewId* aId) { NS_ASSERTION(sizeof(nsContentViewId) == sizeof(ViewID), "ID size for XPCOM ID and internal ID type are not the same!"); *aId = mScrollId; return NS_OK; } // Bug 136580: Limit to the number of nested content frames that can have the // same URL. This is to stop content that is recursively loading // itself. Note that "#foo" on the end of URL doesn't affect // whether it's considered identical, but "?foo" or ";foo" are // considered and compared. // Bug 228829: Limit this to 1, like IE does. #define MAX_SAME_URL_CONTENT_FRAMES 1 // Bug 8065: Limit content frame depth to some reasonable level. This // does not count chrome frames when determining depth, nor does it // prevent chrome recursion. Number is fairly arbitrary, but meant to // keep number of shells to a reasonable number on accidental recursion with a // small (but not 1) branching factor. With large branching factors the number // of shells can rapidly become huge and run us out of memory. To solve that, // we'd need to re-institute a fixed version of bug 98158. #define MAX_DEPTH_CONTENT_FRAMES 10 NS_IMPL_CYCLE_COLLECTION_CLASS(nsFrameLoader) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsFrameLoader) NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocShell) NS_IMPL_CYCLE_COLLECTION_UNLINK(mMessageManager) NS_IMPL_CYCLE_COLLECTION_UNLINK(mChildMessageManager) NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsFrameLoader) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocShell) NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "nsFrameLoader::mMessageManager"); cb.NoteXPCOMChild(static_cast<nsIContentFrameMessageManager*>(tmp->mMessageManager.get())); NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChildMessageManager) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTING_ADDREF(nsFrameLoader) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsFrameLoader) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsFrameLoader) NS_INTERFACE_MAP_ENTRY(nsIFrameLoader) NS_INTERFACE_MAP_ENTRY(nsIContentViewManager) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIFrameLoader) NS_INTERFACE_MAP_END nsFrameLoader::nsFrameLoader(Element* aOwner, bool aNetworkCreated) : mOwnerContent(aOwner) , mAppIdSentToPermissionManager(nsIScriptSecurityManager::NO_APP_ID) , mDetachedSubdocViews(nullptr) , mDepthTooGreat(false) , mIsTopLevelContent(false) , mDestroyCalled(false) , mNeedsAsyncDestroy(false) , mInSwap(false) , mInShow(false) , mHideCalled(false) , mNetworkCreated(aNetworkCreated) , mDelayRemoteDialogs(false) , mRemoteBrowserShown(false) , mRemoteFrame(false) , mClipSubdocument(true) , mClampScrollPosition(true) , mRemoteBrowserInitialized(false) , mObservingOwnerContent(false) , mCurrentRemoteFrame(nullptr) , mRemoteBrowser(nullptr) , mRenderMode(RENDER_MODE_DEFAULT) , mEventMode(EVENT_MODE_NORMAL_DISPATCH) { ResetPermissionManagerStatus(); } nsFrameLoader* nsFrameLoader::Create(Element* aOwner, bool aNetworkCreated) { NS_ENSURE_TRUE(aOwner, nullptr); nsIDocument* doc = aOwner->OwnerDoc(); NS_ENSURE_TRUE(!doc->GetDisplayDocument() && ((!doc->IsLoadedAsData() && aOwner->GetCurrentDoc()) || doc->IsStaticDocument()), nullptr); return new nsFrameLoader(aOwner, aNetworkCreated); } NS_IMETHODIMP nsFrameLoader::LoadFrame() { NS_ENSURE_TRUE(mOwnerContent, NS_ERROR_NOT_INITIALIZED); nsAutoString src; GetURL(src); src.Trim(" \t\n\r"); if (src.IsEmpty()) { src.AssignLiteral("about:blank"); } nsIDocument* doc = mOwnerContent->OwnerDoc(); if (doc->IsStaticDocument()) { return NS_OK; } nsCOMPtr<nsIURI> base_uri = mOwnerContent->GetBaseURI(); const nsAFlatCString &doc_charset = doc->GetDocumentCharacterSet(); const char *charset = doc_charset.IsEmpty() ? nullptr : doc_charset.get(); nsCOMPtr<nsIURI> uri; nsresult rv = NS_NewURI(getter_AddRefs(uri), src, charset, base_uri); // If the URI was malformed, try to recover by loading about:blank. if (rv == NS_ERROR_MALFORMED_URI) { rv = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_STRING("about:blank"), charset, base_uri); } if (NS_SUCCEEDED(rv)) { rv = LoadURI(uri); } if (NS_FAILED(rv)) { FireErrorEvent(); return rv; } return NS_OK; } void nsFrameLoader::FireErrorEvent() { if (mOwnerContent) { nsRefPtr<nsAsyncDOMEvent> event = new nsLoadBlockingAsyncDOMEvent(mOwnerContent, NS_LITERAL_STRING("error"), false, false); event->PostDOMEvent(); } } NS_IMETHODIMP nsFrameLoader::LoadURI(nsIURI* aURI) { if (!aURI) return NS_ERROR_INVALID_POINTER; NS_ENSURE_STATE(!mDestroyCalled && mOwnerContent); nsCOMPtr<nsIDocument> doc = mOwnerContent->OwnerDoc(); nsresult rv = CheckURILoad(aURI); NS_ENSURE_SUCCESS(rv, rv); mURIToLoad = aURI; rv = doc->InitializeFrameLoader(this); if (NS_FAILED(rv)) { mURIToLoad = nullptr; } return rv; } nsresult nsFrameLoader::ReallyStartLoading() { nsresult rv = ReallyStartLoadingInternal(); if (NS_FAILED(rv)) { FireErrorEvent(); } return rv; } nsresult nsFrameLoader::ReallyStartLoadingInternal() { NS_ENSURE_STATE(mURIToLoad && mOwnerContent && mOwnerContent->IsInDoc()); nsresult rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) { return rv; } if (mRemoteFrame) { if (!mRemoteBrowser) { TryRemoteBrowser(); if (!mRemoteBrowser) { NS_WARNING("Couldn't create child process for iframe."); return NS_ERROR_FAILURE; } } if (mRemoteBrowserShown || ShowRemoteFrame(nsIntSize(0, 0))) { // FIXME get error codes from child mRemoteBrowser->LoadURL(mURIToLoad); } else { NS_WARNING("[nsFrameLoader] ReallyStartLoadingInternal tried but couldn't show remote browser.\n"); } return NS_OK; } NS_ASSERTION(mDocShell, "MaybeCreateDocShell succeeded with a null mDocShell"); // Just to be safe, recheck uri. rv = CheckURILoad(mURIToLoad); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDocShellLoadInfo> loadInfo; mDocShell->CreateLoadInfo(getter_AddRefs(loadInfo)); NS_ENSURE_TRUE(loadInfo, NS_ERROR_FAILURE); // Is this an <iframe> with a sandbox attribute or a parent which is // sandboxed ? nsHTMLIFrameElement* iframe = nsHTMLIFrameElement::FromContent(mOwnerContent); uint32_t sandboxFlags = 0; if (iframe) { sandboxFlags = iframe->GetSandboxFlags(); uint32_t parentSandboxFlags = iframe->OwnerDoc()->GetSandboxFlags(); if (sandboxFlags || parentSandboxFlags) { // The child can only add restrictions, not remove them. sandboxFlags |= parentSandboxFlags; mDocShell->SetSandboxFlags(sandboxFlags); } } // If this is an <iframe> and it's sandboxed with respect to origin // we will set it up with a null principal later in nsDocShell::DoURILoad. // We do it there to correctly sandbox content that was loaded into // the iframe via other methods than the src attribute. // We'll use our principal, not that of the document loaded inside us. This // is very important; needed to prevent XSS attacks on documents loaded in // subframes! loadInfo->SetOwner(mOwnerContent->NodePrincipal()); nsCOMPtr<nsIURI> referrer; rv = mOwnerContent->NodePrincipal()->GetURI(getter_AddRefs(referrer)); NS_ENSURE_SUCCESS(rv, rv); loadInfo->SetReferrer(referrer); // Default flags: int32_t flags = nsIWebNavigation::LOAD_FLAGS_NONE; // Flags for browser frame: if (OwnerIsBrowserFrame()) { flags = nsIWebNavigation::LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP | nsIWebNavigation::LOAD_FLAGS_DISALLOW_INHERIT_OWNER; } // Kick off the load... bool tmpState = mNeedsAsyncDestroy; mNeedsAsyncDestroy = true; rv = mDocShell->LoadURI(mURIToLoad, loadInfo, flags, false); mNeedsAsyncDestroy = tmpState; mURIToLoad = nullptr; NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } nsresult nsFrameLoader::CheckURILoad(nsIURI* aURI) { // Check for security. The fun part is trying to figure out what principals // to use. The way I figure it, if we're doing a LoadFrame() accidentally // (eg someone created a frame/iframe node, we're being parsed, XUL iframes // are being reframed, etc.) then we definitely want to use the node // principal of mOwnerContent for security checks. If, on the other hand, // someone's setting the src on our owner content, or created it via script, // or whatever, then they can clearly access it... and we should still use // the principal of mOwnerContent. I don't think that leads to privilege // escalation, and it's reasonably guaranteed to not lead to XSS issues // (since caller can already access mOwnerContent in this case). So just use // the principal of mOwnerContent no matter what. If script wants to run // things with its own permissions, which differ from those of mOwnerContent // (which means the script is privileged in some way) it should set // window.location instead. nsIScriptSecurityManager *secMan = nsContentUtils::GetSecurityManager(); // Get our principal nsIPrincipal* principal = mOwnerContent->NodePrincipal(); // Check if we are allowed to load absURL nsresult rv = secMan->CheckLoadURIWithPrincipal(principal, aURI, nsIScriptSecurityManager::STANDARD); if (NS_FAILED(rv)) { return rv; // We're not } // Bail out if this is an infinite recursion scenario rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) { return rv; } if (mRemoteFrame) { return NS_OK; } return CheckForRecursiveLoad(aURI); } NS_IMETHODIMP nsFrameLoader::GetDocShell(nsIDocShell **aDocShell) { *aDocShell = nullptr; nsresult rv = NS_OK; // If we have an owner, make sure we have a docshell and return // that. If not, we're most likely in the middle of being torn down, // then we just return null. if (mOwnerContent) { nsresult rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) return rv; if (mRemoteFrame) { NS_WARNING("No docshells for remote frames!"); return rv; } NS_ASSERTION(mDocShell, "MaybeCreateDocShell succeeded, but null mDocShell"); } *aDocShell = mDocShell; NS_IF_ADDREF(*aDocShell); return rv; } void nsFrameLoader::Finalize() { nsCOMPtr<nsIBaseWindow> base_win(do_QueryInterface(mDocShell)); if (base_win) { base_win->Destroy(); } mDocShell = nullptr; } static void FirePageHideEvent(nsIDocShellTreeItem* aItem, nsIDOMEventTarget* aChromeEventHandler) { nsCOMPtr<nsIDOMDocument> doc = do_GetInterface(aItem); nsCOMPtr<nsIDocument> internalDoc = do_QueryInterface(doc); NS_ASSERTION(internalDoc, "What happened here?"); internalDoc->OnPageHide(true, aChromeEventHandler); int32_t childCount = 0; aItem->GetChildCount(&childCount); nsAutoTArray<nsCOMPtr<nsIDocShellTreeItem>, 8> kids; kids.AppendElements(childCount); for (int32_t i = 0; i < childCount; ++i) { aItem->GetChildAt(i, getter_AddRefs(kids[i])); } for (uint32_t i = 0; i < kids.Length(); ++i) { if (kids[i]) { FirePageHideEvent(kids[i], aChromeEventHandler); } } } // The pageshow event is fired for a given document only if IsShowing() returns // the same thing as aFireIfShowing. This gives us a way to fire pageshow only // on documents that are still loading or only on documents that are already // loaded. static void FirePageShowEvent(nsIDocShellTreeItem* aItem, nsIDOMEventTarget* aChromeEventHandler, bool aFireIfShowing) { int32_t childCount = 0; aItem->GetChildCount(&childCount); nsAutoTArray<nsCOMPtr<nsIDocShellTreeItem>, 8> kids; kids.AppendElements(childCount); for (int32_t i = 0; i < childCount; ++i) { aItem->GetChildAt(i, getter_AddRefs(kids[i])); } for (uint32_t i = 0; i < kids.Length(); ++i) { if (kids[i]) { FirePageShowEvent(kids[i], aChromeEventHandler, aFireIfShowing); } } nsCOMPtr<nsIDOMDocument> doc = do_GetInterface(aItem); nsCOMPtr<nsIDocument> internalDoc = do_QueryInterface(doc); NS_ASSERTION(internalDoc, "What happened here?"); if (internalDoc->IsShowing() == aFireIfShowing) { internalDoc->OnPageShow(true, aChromeEventHandler); } } static void SetTreeOwnerAndChromeEventHandlerOnDocshellTree(nsIDocShellTreeItem* aItem, nsIDocShellTreeOwner* aOwner, nsIDOMEventTarget* aHandler) { NS_PRECONDITION(aItem, "Must have item"); aItem->SetTreeOwner(aOwner); int32_t childCount = 0; aItem->GetChildCount(&childCount); for (int32_t i = 0; i < childCount; ++i) { nsCOMPtr<nsIDocShellTreeItem> item; aItem->GetChildAt(i, getter_AddRefs(item)); if (aHandler) { nsCOMPtr<nsIDocShell> shell(do_QueryInterface(item)); shell->SetChromeEventHandler(aHandler); } SetTreeOwnerAndChromeEventHandlerOnDocshellTree(item, aOwner, aHandler); } } /** * Set the type of the treeitem and hook it up to the treeowner. * @param aItem the treeitem we're working with * @param aTreeOwner the relevant treeowner; might be null * @param aParentType the nsIDocShellTreeItem::GetType of our parent docshell * @param aParentNode if non-null, the docshell we should be added as a child to * * @return whether aItem is top-level content */ bool nsFrameLoader::AddTreeItemToTreeOwner(nsIDocShellTreeItem* aItem, nsIDocShellTreeOwner* aOwner, int32_t aParentType, nsIDocShellTreeNode* aParentNode) { NS_PRECONDITION(aItem, "Must have docshell treeitem"); NS_PRECONDITION(mOwnerContent, "Must have owning content"); nsAutoString value; bool isContent = false; mOwnerContent->GetAttr(kNameSpaceID_None, TypeAttrName(), value); // we accept "content" and "content-xxx" values. // at time of writing, we expect "xxx" to be "primary" or "targetable", but // someday it might be an integer expressing priority or something else. isContent = value.LowerCaseEqualsLiteral("content") || StringBeginsWith(value, NS_LITERAL_STRING("content-"), nsCaseInsensitiveStringComparator()); // Force mozbrowser frames to always be typeContent, even if the // mozbrowser interfaces are disabled. nsCOMPtr<nsIDOMMozBrowserFrame> mozbrowser = do_QueryInterface(mOwnerContent); if (mozbrowser) { bool isMozbrowser = false; mozbrowser->GetMozbrowser(&isMozbrowser); isContent |= isMozbrowser; } if (isContent) { // The web shell's type is content. aItem->SetItemType(nsIDocShellTreeItem::typeContent); } else { // Inherit our type from our parent docshell. If it is // chrome, we'll be chrome. If it is content, we'll be // content. aItem->SetItemType(aParentType); } // Now that we have our type set, add ourselves to the parent, as needed. if (aParentNode) { aParentNode->AddChild(aItem); } bool retval = false; if (aParentType == nsIDocShellTreeItem::typeChrome && isContent) { retval = true; bool is_primary = value.LowerCaseEqualsLiteral("content-primary"); if (aOwner) { bool is_targetable = is_primary || value.LowerCaseEqualsLiteral("content-targetable"); mOwnerContent->AddMutationObserver(this); mObservingOwnerContent = true; aOwner->ContentShellAdded(aItem, is_primary, is_targetable, value); } } return retval; } static bool AllDescendantsOfType(nsIDocShellTreeItem* aParentItem, int32_t aType) { int32_t childCount = 0; aParentItem->GetChildCount(&childCount); for (int32_t i = 0; i < childCount; ++i) { nsCOMPtr<nsIDocShellTreeItem> kid; aParentItem->GetChildAt(i, getter_AddRefs(kid)); int32_t kidType; kid->GetItemType(&kidType); if (kidType != aType || !AllDescendantsOfType(kid, aType)) { return false; } } return true; } /** * A class that automatically sets mInShow to false when it goes * out of scope. */ class NS_STACK_CLASS AutoResetInShow { private: nsFrameLoader* mFrameLoader; MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER public: AutoResetInShow(nsFrameLoader* aFrameLoader MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : mFrameLoader(aFrameLoader) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } ~AutoResetInShow() { mFrameLoader->mInShow = false; } }; bool nsFrameLoader::Show(int32_t marginWidth, int32_t marginHeight, int32_t scrollbarPrefX, int32_t scrollbarPrefY, nsSubDocumentFrame* frame) { if (mInShow) { return false; } // Reset mInShow if we exit early. AutoResetInShow resetInShow(this); mInShow = true; nsresult rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) { return false; } if (!mRemoteFrame) { if (!mDocShell) return false; mDocShell->SetMarginWidth(marginWidth); mDocShell->SetMarginHeight(marginHeight); nsCOMPtr<nsIScrollable> sc = do_QueryInterface(mDocShell); if (sc) { sc->SetDefaultScrollbarPreferences(nsIScrollable::ScrollOrientation_X, scrollbarPrefX); sc->SetDefaultScrollbarPreferences(nsIScrollable::ScrollOrientation_Y, scrollbarPrefY); } nsCOMPtr<nsIPresShell> presShell = mDocShell->GetPresShell(); if (presShell) { // Ensure root scroll frame is reflowed in case scroll preferences or // margins have changed nsIFrame* rootScrollFrame = presShell->GetRootScrollFrame(); if (rootScrollFrame) { presShell->FrameNeedsReflow(rootScrollFrame, nsIPresShell::eResize, NS_FRAME_IS_DIRTY); } return true; } } nsView* view = frame->EnsureInnerView(); if (!view) return false; if (mRemoteFrame) { return ShowRemoteFrame(GetSubDocumentSize(frame)); } nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(mDocShell); NS_ASSERTION(baseWindow, "Found a nsIDocShell that isn't a nsIBaseWindow."); nsIntSize size; if (!(frame->GetStateBits() & NS_FRAME_FIRST_REFLOW)) { // We have a useful size already; use it, since we might get no // more size updates. size = GetSubDocumentSize(frame); } else { // Pick some default size for now. Using 10x10 because that's what the // code here used to do. size.SizeTo(10, 10); } baseWindow->InitWindow(nullptr, view->GetWidget(), 0, 0, size.width, size.height); // This is kinda whacky, this "Create()" call doesn't really // create anything, one starts to wonder why this was named // "Create"... baseWindow->Create(); baseWindow->SetVisibility(true); // Trigger editor re-initialization if midas is turned on in the // sub-document. This shouldn't be necessary, but given the way our // editor works, it is. See // https://bugzilla.mozilla.org/show_bug.cgi?id=284245 nsCOMPtr<nsIPresShell> presShell = mDocShell->GetPresShell(); if (presShell) { nsCOMPtr<nsIDOMHTMLDocument> doc = do_QueryInterface(presShell->GetDocument()); if (doc) { nsAutoString designMode; doc->GetDesignMode(designMode); if (designMode.EqualsLiteral("on")) { // Hold on to the editor object to let the document reattach to the // same editor object, instead of creating a new one. nsCOMPtr<nsIEditorDocShell> editorDocshell = do_QueryInterface(mDocShell); nsCOMPtr<nsIEditor> editor; nsresult rv = editorDocshell->GetEditor(getter_AddRefs(editor)); NS_ENSURE_SUCCESS(rv, false); doc->SetDesignMode(NS_LITERAL_STRING("off")); doc->SetDesignMode(NS_LITERAL_STRING("on")); } else { // Re-initialize the presentation for contenteditable documents nsCOMPtr<nsIEditorDocShell> editorDocshell = do_QueryInterface(mDocShell); if (editorDocshell) { bool editable = false, hasEditingSession = false; editorDocshell->GetEditable(&editable); editorDocshell->GetHasEditingSession(&hasEditingSession); nsCOMPtr<nsIEditor> editor; editorDocshell->GetEditor(getter_AddRefs(editor)); if (editable && hasEditingSession && editor) { editor->PostCreate(); } } } } } mInShow = false; if (mHideCalled) { mHideCalled = false; Hide(); return false; } return true; } void nsFrameLoader::MarginsChanged(uint32_t aMarginWidth, uint32_t aMarginHeight) { // We assume that the margins are always zero for remote frames. if (mRemoteFrame) return; // If there's no docshell, we're probably not up and running yet. // nsFrameLoader::Show() will take care of setting the right // margins. if (!mDocShell) return; // Set the margins mDocShell->SetMarginWidth(aMarginWidth); mDocShell->SetMarginHeight(aMarginHeight); // Trigger a restyle if there's a prescontext nsRefPtr<nsPresContext> presContext; mDocShell->GetPresContext(getter_AddRefs(presContext)); if (presContext) presContext->RebuildAllStyleData(nsChangeHint(0)); } bool nsFrameLoader::ShowRemoteFrame(const nsIntSize& size) { NS_ASSERTION(mRemoteFrame, "ShowRemote only makes sense on remote frames."); if (!mRemoteBrowser) { TryRemoteBrowser(); if (!mRemoteBrowser) { NS_ERROR("Couldn't create child process."); return false; } } // FIXME/bug 589337: Show()/Hide() is pretty expensive for // cross-process layers; need to figure out what behavior we really // want here. For now, hack. if (!mRemoteBrowserShown) { if (!mOwnerContent || !mOwnerContent->GetCurrentDoc()) { return false; } nsRefPtr<layers::LayerManager> layerManager = nsContentUtils::LayerManagerForDocument(mOwnerContent->GetCurrentDoc()); if (!layerManager) { // This is just not going to work. return false; } mRemoteBrowser->Show(size); mRemoteBrowserShown = true; EnsureMessageManager(); nsCOMPtr<nsIObserverService> os = services::GetObserverService(); if (OwnerIsBrowserOrAppFrame() && os && !mRemoteBrowserInitialized) { os->NotifyObservers(NS_ISUPPORTS_CAST(nsIFrameLoader*, this), "remote-browser-frame-shown", NULL); mRemoteBrowserInitialized = true; } } else { nsRect dimensions; NS_ENSURE_SUCCESS(GetWindowDimensions(dimensions), false); mRemoteBrowser->UpdateDimensions(dimensions, size); } return true; } void nsFrameLoader::Hide() { if (mHideCalled) { return; } if (mInShow) { mHideCalled = true; return; } if (!mDocShell) return; nsCOMPtr<nsIContentViewer> contentViewer; mDocShell->GetContentViewer(getter_AddRefs(contentViewer)); if (contentViewer) contentViewer->SetSticky(false); nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(mDocShell); NS_ASSERTION(baseWin, "Found an nsIDocShell which doesn't implement nsIBaseWindow."); baseWin->SetVisibility(false); baseWin->SetParentWidget(nullptr); } nsresult nsFrameLoader::SwapWithOtherLoader(nsFrameLoader* aOther, nsRefPtr<nsFrameLoader>& aFirstToSwap, nsRefPtr<nsFrameLoader>& aSecondToSwap) { NS_PRECONDITION((aFirstToSwap == this && aSecondToSwap == aOther) || (aFirstToSwap == aOther && aSecondToSwap == this), "Swapping some sort of random loaders?"); NS_ENSURE_STATE(!mInShow && !aOther->mInShow); Element* ourContent = mOwnerContent; Element* otherContent = aOther->mOwnerContent; if (!ourContent || !otherContent) { // Can't handle this return NS_ERROR_NOT_IMPLEMENTED; } // Make sure there are no same-origin issues bool equal; nsresult rv = ourContent->NodePrincipal()->Equals(otherContent->NodePrincipal(), &equal); if (NS_FAILED(rv) || !equal) { // Security problems loom. Just bail on it all return NS_ERROR_DOM_SECURITY_ERR; } nsCOMPtr<nsIDocShell> ourDocshell = GetExistingDocShell(); nsCOMPtr<nsIDocShell> otherDocshell = aOther->GetExistingDocShell(); if (!ourDocshell || !otherDocshell) { // How odd return NS_ERROR_NOT_IMPLEMENTED; } // To avoid having to mess with session history, avoid swapping // frameloaders that don't correspond to root same-type docshells, // unless both roots have session history disabled. nsCOMPtr<nsIDocShellTreeItem> ourTreeItem = do_QueryInterface(ourDocshell); nsCOMPtr<nsIDocShellTreeItem> otherTreeItem = do_QueryInterface(otherDocshell); nsCOMPtr<nsIDocShellTreeItem> ourRootTreeItem, otherRootTreeItem; ourTreeItem->GetSameTypeRootTreeItem(getter_AddRefs(ourRootTreeItem)); otherTreeItem->GetSameTypeRootTreeItem(getter_AddRefs(otherRootTreeItem)); nsCOMPtr<nsIWebNavigation> ourRootWebnav = do_QueryInterface(ourRootTreeItem); nsCOMPtr<nsIWebNavigation> otherRootWebnav = do_QueryInterface(otherRootTreeItem); if (!ourRootWebnav || !otherRootWebnav) { return NS_ERROR_NOT_IMPLEMENTED; } nsCOMPtr<nsISHistory> ourHistory; nsCOMPtr<nsISHistory> otherHistory; ourRootWebnav->GetSessionHistory(getter_AddRefs(ourHistory)); otherRootWebnav->GetSessionHistory(getter_AddRefs(otherHistory)); if ((ourRootTreeItem != ourTreeItem || otherRootTreeItem != otherTreeItem) && (ourHistory || otherHistory)) { return NS_ERROR_NOT_IMPLEMENTED; } // Also make sure that the two docshells are the same type. Otherwise // swapping is certainly not safe. If this needs to be changed then // the code below needs to be audited as it assumes identical types. int32_t ourType = nsIDocShellTreeItem::typeChrome; int32_t otherType = nsIDocShellTreeItem::typeChrome; ourTreeItem->GetItemType(&ourType); otherTreeItem->GetItemType(&otherType); if (ourType != otherType) { return NS_ERROR_NOT_IMPLEMENTED; } // One more twist here. Setting up the right treeowners in a heterogeneous // tree is a bit of a pain. So make sure that if ourType is not // nsIDocShellTreeItem::typeContent then all of our descendants are the same // type as us. if (ourType != nsIDocShellTreeItem::typeContent && (!AllDescendantsOfType(ourTreeItem, ourType) || !AllDescendantsOfType(otherTreeItem, otherType))) { return NS_ERROR_NOT_IMPLEMENTED; } // Save off the tree owners, frame elements, chrome event handlers, and // docshell and document parents before doing anything else. nsCOMPtr<nsIDocShellTreeOwner> ourOwner, otherOwner; ourTreeItem->GetTreeOwner(getter_AddRefs(ourOwner)); otherTreeItem->GetTreeOwner(getter_AddRefs(otherOwner)); // Note: it's OK to have null treeowners. nsCOMPtr<nsIDocShellTreeItem> ourParentItem, otherParentItem; ourTreeItem->GetParent(getter_AddRefs(ourParentItem)); otherTreeItem->GetParent(getter_AddRefs(otherParentItem)); if (!ourParentItem || !otherParentItem) { return NS_ERROR_NOT_IMPLEMENTED; } // Make sure our parents are the same type too int32_t ourParentType = nsIDocShellTreeItem::typeContent; int32_t otherParentType = nsIDocShellTreeItem::typeContent; ourParentItem->GetItemType(&ourParentType); otherParentItem->GetItemType(&otherParentType); if (ourParentType != otherParentType) { return NS_ERROR_NOT_IMPLEMENTED; } nsCOMPtr<nsPIDOMWindow> ourWindow = do_GetInterface(ourDocshell); nsCOMPtr<nsPIDOMWindow> otherWindow = do_GetInterface(otherDocshell); nsCOMPtr<nsIDOMElement> ourFrameElement = ourWindow->GetFrameElementInternal(); nsCOMPtr<nsIDOMElement> otherFrameElement = otherWindow->GetFrameElementInternal(); nsCOMPtr<nsIDOMEventTarget> ourChromeEventHandler = do_QueryInterface(ourWindow->GetChromeEventHandler()); nsCOMPtr<nsIDOMEventTarget> otherChromeEventHandler = do_QueryInterface(otherWindow->GetChromeEventHandler()); NS_ASSERTION(SameCOMIdentity(ourFrameElement, ourContent) && SameCOMIdentity(otherFrameElement, otherContent) && SameCOMIdentity(ourChromeEventHandler, ourContent) && SameCOMIdentity(otherChromeEventHandler, otherContent), "How did that happen, exactly?"); nsCOMPtr<nsIDocument> ourChildDocument = do_QueryInterface(ourWindow->GetExtantDocument()); nsCOMPtr<nsIDocument> otherChildDocument = do_QueryInterface(otherWindow->GetExtantDocument()); if (!ourChildDocument || !otherChildDocument) { // This shouldn't be happening return NS_ERROR_NOT_IMPLEMENTED; } nsCOMPtr<nsIDocument> ourParentDocument = ourChildDocument->GetParentDocument(); nsCOMPtr<nsIDocument> otherParentDocument = otherChildDocument->GetParentDocument(); // Make sure to swap docshells between the two frames. nsIDocument* ourDoc = ourContent->GetCurrentDoc(); nsIDocument* otherDoc = otherContent->GetCurrentDoc(); if (!ourDoc || !otherDoc) { // Again, how odd, given that we had docshells return NS_ERROR_NOT_IMPLEMENTED; } NS_ASSERTION(ourDoc == ourParentDocument, "Unexpected parent document"); NS_ASSERTION(otherDoc == otherParentDocument, "Unexpected parent document"); nsIPresShell* ourShell = ourDoc->GetShell(); nsIPresShell* otherShell = otherDoc->GetShell(); if (!ourShell || !otherShell) { return NS_ERROR_NOT_IMPLEMENTED; } if (ourDocshell->GetIsBrowserElement() != otherDocshell->GetIsBrowserElement() || ourDocshell->GetIsApp() != otherDocshell->GetIsApp()) { return NS_ERROR_NOT_IMPLEMENTED; } if (mInSwap || aOther->mInSwap) { return NS_ERROR_NOT_IMPLEMENTED; } mInSwap = aOther->mInSwap = true; // Fire pageshow events on still-loading pages, and then fire pagehide // events. Note that we do NOT fire these in the normal way, but just fire // them on the chrome event handlers. FirePageShowEvent(ourTreeItem, ourChromeEventHandler, false); FirePageShowEvent(otherTreeItem, otherChromeEventHandler, false); FirePageHideEvent(ourTreeItem, ourChromeEventHandler); FirePageHideEvent(otherTreeItem, otherChromeEventHandler); nsIFrame* ourFrame = ourContent->GetPrimaryFrame(); nsIFrame* otherFrame = otherContent->GetPrimaryFrame(); if (!ourFrame || !otherFrame) { mInSwap = aOther->mInSwap = false; FirePageShowEvent(ourTreeItem, ourChromeEventHandler, true); FirePageShowEvent(otherTreeItem, otherChromeEventHandler, true); return NS_ERROR_NOT_IMPLEMENTED; } nsSubDocumentFrame* ourFrameFrame = do_QueryFrame(ourFrame); if (!ourFrameFrame) { mInSwap = aOther->mInSwap = false; FirePageShowEvent(ourTreeItem, ourChromeEventHandler, true); FirePageShowEvent(otherTreeItem, otherChromeEventHandler, true); return NS_ERROR_NOT_IMPLEMENTED; } // OK. First begin to swap the docshells in the two nsIFrames rv = ourFrameFrame->BeginSwapDocShells(otherFrame); if (NS_FAILED(rv)) { mInSwap = aOther->mInSwap = false; FirePageShowEvent(ourTreeItem, ourChromeEventHandler, true); FirePageShowEvent(otherTreeItem, otherChromeEventHandler, true); return rv; } // Now move the docshells to the right docshell trees. Note that this // resets their treeowners to null. ourParentItem->RemoveChild(ourTreeItem); otherParentItem->RemoveChild(otherTreeItem); if (ourType == nsIDocShellTreeItem::typeContent) { ourOwner->ContentShellRemoved(ourTreeItem); otherOwner->ContentShellRemoved(otherTreeItem); } ourParentItem->AddChild(otherTreeItem); otherParentItem->AddChild(ourTreeItem); // Restore the correct chrome event handlers. ourDocshell->SetChromeEventHandler(otherChromeEventHandler); otherDocshell->SetChromeEventHandler(ourChromeEventHandler); // Restore the correct treeowners // (and also chrome event handlers for content frames only). SetTreeOwnerAndChromeEventHandlerOnDocshellTree(ourTreeItem, otherOwner, ourType == nsIDocShellTreeItem::typeContent ? otherChromeEventHandler : nullptr); SetTreeOwnerAndChromeEventHandlerOnDocshellTree(otherTreeItem, ourOwner, ourType == nsIDocShellTreeItem::typeContent ? ourChromeEventHandler : nullptr); // Switch the owner content before we start calling AddTreeItemToTreeOwner. // Note that we rely on this to deal with setting mObservingOwnerContent to // false and calling RemoveMutationObserver as needed. SetOwnerContent(otherContent); aOther->SetOwnerContent(ourContent); AddTreeItemToTreeOwner(ourTreeItem, otherOwner, otherParentType, nullptr); aOther->AddTreeItemToTreeOwner(otherTreeItem, ourOwner, ourParentType, nullptr); // SetSubDocumentFor nulls out parent documents on the old child doc if a // new non-null document is passed in, so just go ahead and remove both // kids before reinserting in the parent subdoc maps, to avoid // complications. ourParentDocument->SetSubDocumentFor(ourContent, nullptr); otherParentDocument->SetSubDocumentFor(otherContent, nullptr); ourParentDocument->SetSubDocumentFor(ourContent, otherChildDocument); otherParentDocument->SetSubDocumentFor(otherContent, ourChildDocument); ourWindow->SetFrameElementInternal(otherFrameElement); otherWindow->SetFrameElementInternal(ourFrameElement); nsRefPtr<nsFrameMessageManager> ourMessageManager = mMessageManager; nsRefPtr<nsFrameMessageManager> otherMessageManager = aOther->mMessageManager; // Swap pointers in child message managers. if (mChildMessageManager) { nsInProcessTabChildGlobal* tabChild = static_cast<nsInProcessTabChildGlobal*>(mChildMessageManager.get()); tabChild->SetOwner(otherContent); tabChild->SetChromeMessageManager(otherMessageManager); } if (aOther->mChildMessageManager) { nsInProcessTabChildGlobal* otherTabChild = static_cast<nsInProcessTabChildGlobal*>(aOther->mChildMessageManager.get()); otherTabChild->SetOwner(ourContent); otherTabChild->SetChromeMessageManager(ourMessageManager); } // Swap and setup things in parent message managers. nsFrameMessageManager* ourParentManager = mMessageManager ? mMessageManager->GetParentManager() : nullptr; nsFrameMessageManager* otherParentManager = aOther->mMessageManager ? aOther->mMessageManager->GetParentManager() : nullptr; JSContext* thisCx = mMessageManager ? mMessageManager->GetJSContext() : nullptr; JSContext* otherCx = aOther->mMessageManager ? aOther->mMessageManager->GetJSContext() : nullptr; if (mMessageManager) { mMessageManager->RemoveFromParent(); mMessageManager->SetJSContext(otherCx); mMessageManager->SetParentManager(otherParentManager); mMessageManager->SetCallback(aOther, false); } if (aOther->mMessageManager) { aOther->mMessageManager->RemoveFromParent(); aOther->mMessageManager->SetJSContext(thisCx); aOther->mMessageManager->SetParentManager(ourParentManager); aOther->mMessageManager->SetCallback(this, false); } mMessageManager.swap(aOther->mMessageManager); aFirstToSwap.swap(aSecondToSwap); // Drop any cached content viewers in the two session histories. nsCOMPtr<nsISHistoryInternal> ourInternalHistory = do_QueryInterface(ourHistory); nsCOMPtr<nsISHistoryInternal> otherInternalHistory = do_QueryInterface(otherHistory); if (ourInternalHistory) { ourInternalHistory->EvictAllContentViewers(); } if (otherInternalHistory) { otherInternalHistory->EvictAllContentViewers(); } NS_ASSERTION(ourFrame == ourContent->GetPrimaryFrame() && otherFrame == otherContent->GetPrimaryFrame(), "changed primary frame"); ourFrameFrame->EndSwapDocShells(otherFrame); // If the content being swapped came from windows on two screens with // incompatible backing resolution (e.g. dragging a tab between windows on // hi-dpi and low-dpi screens), it will have style data that is based on // the wrong appUnitsPerDevPixel value. So we tell the PresShells that their // backing scale factor may have changed. (Bug 822266) ourShell->BackingScaleFactorChanged(); otherShell->BackingScaleFactorChanged(); ourParentDocument->FlushPendingNotifications(Flush_Layout); otherParentDocument->FlushPendingNotifications(Flush_Layout); FirePageShowEvent(ourTreeItem, otherChromeEventHandler, true); FirePageShowEvent(otherTreeItem, ourChromeEventHandler, true); mInSwap = aOther->mInSwap = false; return NS_OK; } void nsFrameLoader::DestroyChild() { if (mRemoteBrowser) { mRemoteBrowser->SetOwnerElement(nullptr); mRemoteBrowser->Destroy(); mRemoteBrowser = nullptr; } } NS_IMETHODIMP nsFrameLoader::Destroy() { if (mDestroyCalled) { return NS_OK; } mDestroyCalled = true; if (mMessageManager) { mMessageManager->Disconnect(); } if (mChildMessageManager) { static_cast<nsInProcessTabChildGlobal*>(mChildMessageManager.get())->Disconnect(); } nsCOMPtr<nsIDocument> doc; bool dynamicSubframeRemoval = false; if (mOwnerContent) { doc = mOwnerContent->OwnerDoc(); dynamicSubframeRemoval = !mIsTopLevelContent && !doc->InUnlinkOrDeletion(); doc->SetSubDocumentFor(mOwnerContent, nullptr); SetOwnerContent(nullptr); } DestroyChild(); // Seems like this is a dynamic frame removal. if (dynamicSubframeRemoval) { nsCOMPtr<nsIDocShellHistory> dhistory = do_QueryInterface(mDocShell); if (dhistory) { dhistory->RemoveFromSessionHistory(); } } // Let the tree owner know we're gone. if (mIsTopLevelContent) { nsCOMPtr<nsIDocShellTreeItem> ourItem = do_QueryInterface(mDocShell); if (ourItem) { nsCOMPtr<nsIDocShellTreeItem> parentItem; ourItem->GetParent(getter_AddRefs(parentItem)); nsCOMPtr<nsIDocShellTreeOwner> owner = do_GetInterface(parentItem); if (owner) { owner->ContentShellRemoved(ourItem); } } } // Let our window know that we are gone nsCOMPtr<nsPIDOMWindow> win_private(do_GetInterface(mDocShell)); if (win_private) { win_private->SetFrameElementInternal(nullptr); } if ((mNeedsAsyncDestroy || !doc || NS_FAILED(doc->FinalizeFrameLoader(this))) && mDocShell) { nsCOMPtr<nsIRunnable> event = new nsAsyncDocShellDestroyer(mDocShell); NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY); NS_DispatchToCurrentThread(event); // Let go of our docshell now that the async destroyer holds on to // the docshell. mDocShell = nullptr; } // NOTE: 'this' may very well be gone by now. return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetDepthTooGreat(bool* aDepthTooGreat) { *aDepthTooGreat = mDepthTooGreat; return NS_OK; } void nsFrameLoader::SetOwnerContent(Element* aContent) { if (mObservingOwnerContent) { mObservingOwnerContent = false; mOwnerContent->RemoveMutationObserver(this); } mOwnerContent = aContent; if (RenderFrameParent* rfp = GetCurrentRemoteFrame()) { rfp->OwnerContentChanged(aContent); } ResetPermissionManagerStatus(); } bool nsFrameLoader::OwnerIsBrowserOrAppFrame() { nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent); return browserFrame ? browserFrame->GetReallyIsBrowserOrApp() : false; } bool nsFrameLoader::OwnerIsAppFrame() { nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent); return browserFrame ? browserFrame->GetReallyIsApp() : false; } bool nsFrameLoader::OwnerIsBrowserFrame() { return OwnerIsBrowserOrAppFrame() && !OwnerIsAppFrame(); } void nsFrameLoader::GetOwnerAppManifestURL(nsAString& aOut) { aOut.Truncate(); nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent); if (browserFrame) { browserFrame->GetAppManifestURL(aOut); } } already_AddRefed<mozIApplication> nsFrameLoader::GetOwnApp() { nsAutoString manifest; GetOwnerAppManifestURL(manifest); if (manifest.IsEmpty()) { return nullptr; } nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID); NS_ENSURE_TRUE(appsService, nullptr); nsCOMPtr<mozIDOMApplication> domApp; appsService->GetAppByManifestURL(manifest, getter_AddRefs(domApp)); nsCOMPtr<mozIApplication> app = do_QueryInterface(domApp); MOZ_ASSERT_IF(domApp, app); return app.forget(); } already_AddRefed<mozIApplication> nsFrameLoader::GetContainingApp() { // See if our owner content's principal has an associated app. uint32_t appId = mOwnerContent->NodePrincipal()->GetAppId(); MOZ_ASSERT(appId != nsIScriptSecurityManager::UNKNOWN_APP_ID); if (appId == nsIScriptSecurityManager::NO_APP_ID || appId == nsIScriptSecurityManager::UNKNOWN_APP_ID) { return nullptr; } nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID); NS_ENSURE_TRUE(appsService, nullptr); nsCOMPtr<mozIDOMApplication> domApp; appsService->GetAppByLocalId(appId, getter_AddRefs(domApp)); MOZ_ASSERT(domApp); nsCOMPtr<mozIApplication> app = do_QueryInterface(domApp); MOZ_ASSERT_IF(domApp, app); return app.forget(); } bool nsFrameLoader::ShouldUseRemoteProcess() { if (PR_GetEnv("MOZ_DISABLE_OOP_TABS") || Preferences::GetBool("dom.ipc.tabs.disabled", false)) { return false; } // If we're inside a content process, don't use a remote process for this // frame; it won't work properly until bug 761935 is fixed. if (XRE_GetProcessType() == GeckoProcessType_Content) { return false; } // If we're an <iframe mozbrowser> and we don't have a "remote" attribute, // fall back to the default. if (OwnerIsBrowserOrAppFrame() && !mOwnerContent->HasAttr(kNameSpaceID_None, nsGkAtoms::Remote)) { return Preferences::GetBool("dom.ipc.browser_frames.oop_by_default", false); } // Otherwise, we're remote if we have "remote=true" and we're either a // browser frame or a XUL element. return (OwnerIsBrowserOrAppFrame() || mOwnerContent->GetNameSpaceID() == kNameSpaceID_XUL) && mOwnerContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::Remote, nsGkAtoms::_true, eCaseMatters); } nsresult nsFrameLoader::MaybeCreateDocShell() { if (mDocShell) { return NS_OK; } if (mRemoteFrame) { return NS_OK; } NS_ENSURE_STATE(!mDestroyCalled); if (ShouldUseRemoteProcess()) { mRemoteFrame = true; return NS_OK; } // Get our parent docshell off the document of mOwnerContent // XXXbz this is such a total hack.... We really need to have a // better setup for doing this. nsIDocument* doc = mOwnerContent->OwnerDoc(); if (!(doc->IsStaticDocument() || mOwnerContent->IsInDoc())) { return NS_ERROR_UNEXPECTED; } if (doc->IsResourceDoc() || !doc->IsActive()) { // Don't allow subframe loads in resource documents, nor // in non-active documents. return NS_ERROR_NOT_AVAILABLE; } nsCOMPtr<nsISupports> container = doc->GetContainer(); nsCOMPtr<nsIWebNavigation> parentAsWebNav = do_QueryInterface(container); NS_ENSURE_STATE(parentAsWebNav); // Create the docshell... mDocShell = do_CreateInstance("@mozilla.org/docshell;1"); NS_ENSURE_TRUE(mDocShell, NS_ERROR_FAILURE); if (!mNetworkCreated) { nsCOMPtr<nsIDocShellHistory> history = do_QueryInterface(mDocShell); if (history) { history->SetCreatedDynamically(true); } } // Get the frame name and tell the docshell about it. nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(mDocShell)); NS_ENSURE_TRUE(docShellAsItem, NS_ERROR_FAILURE); nsAutoString frameName; int32_t namespaceID = mOwnerContent->GetNameSpaceID(); if (namespaceID == kNameSpaceID_XHTML && !mOwnerContent->IsInHTMLDocument()) { mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::id, frameName); } else { mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, frameName); // XXX if no NAME then use ID, after a transition period this will be // changed so that XUL only uses ID too (bug 254284). if (frameName.IsEmpty() && namespaceID == kNameSpaceID_XUL) { mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::id, frameName); } } if (!frameName.IsEmpty()) { docShellAsItem->SetName(frameName.get()); } // If our container is a web-shell, inform it that it has a new // child. If it's not a web-shell then some things will not operate // properly. nsCOMPtr<nsIDocShellTreeNode> parentAsNode(do_QueryInterface(parentAsWebNav)); if (parentAsNode) { // Note: This logic duplicates a lot of logic in // nsSubDocumentFrame::AttributeChanged. We should fix that. nsCOMPtr<nsIDocShellTreeItem> parentAsItem = do_QueryInterface(parentAsNode); int32_t parentType; parentAsItem->GetItemType(&parentType); // XXXbz why is this in content code, exactly? We should handle // this some other way..... Not sure how yet. nsCOMPtr<nsIDocShellTreeOwner> parentTreeOwner; parentAsItem->GetTreeOwner(getter_AddRefs(parentTreeOwner)); NS_ENSURE_STATE(parentTreeOwner); mIsTopLevelContent = AddTreeItemToTreeOwner(docShellAsItem, parentTreeOwner, parentType, parentAsNode); // Make sure all shells have links back to the content element // in the nearest enclosing chrome shell. nsCOMPtr<nsIDOMEventTarget> chromeEventHandler; if (parentType == nsIDocShellTreeItem::typeChrome) { // Our parent shell is a chrome shell. It is therefore our nearest // enclosing chrome shell. chromeEventHandler = do_QueryInterface(mOwnerContent); NS_ASSERTION(chromeEventHandler, "This mContent should implement this."); } else { nsCOMPtr<nsIDocShell> parentShell(do_QueryInterface(parentAsNode)); // Our parent shell is a content shell. Get the chrome event // handler from it and use that for our shell as well. parentShell->GetChromeEventHandler(getter_AddRefs(chromeEventHandler)); } mDocShell->SetChromeEventHandler(chromeEventHandler); } // This is nasty, this code (the do_GetInterface(mDocShell) below) // *must* come *after* the above call to // mDocShell->SetChromeEventHandler() for the global window to get // the right chrome event handler. // Tell the window about the frame that hosts it. nsCOMPtr<nsIDOMElement> frame_element(do_QueryInterface(mOwnerContent)); NS_ASSERTION(frame_element, "frame loader owner element not a DOM element!"); nsCOMPtr<nsPIDOMWindow> win_private(do_GetInterface(mDocShell)); nsCOMPtr<nsIBaseWindow> base_win(do_QueryInterface(mDocShell)); if (win_private) { win_private->SetFrameElementInternal(frame_element); } // This is kinda whacky, this call doesn't really create anything, // but it must be called to make sure things are properly // initialized. if (NS_FAILED(base_win->Create()) || !win_private) { // Do not call Destroy() here. See bug 472312. NS_WARNING("Something wrong when creating the docshell for a frameloader!"); return NS_ERROR_FAILURE; } EnsureMessageManager(); if (OwnerIsAppFrame()) { // You can't be both an app and a browser frame. MOZ_ASSERT(!OwnerIsBrowserFrame()); nsCOMPtr<mozIApplication> ownApp = GetOwnApp(); MOZ_ASSERT(ownApp); uint32_t ownAppId = nsIScriptSecurityManager::NO_APP_ID; if (ownApp) { NS_ENSURE_SUCCESS(ownApp->GetLocalId(&ownAppId), NS_ERROR_FAILURE); } mDocShell->SetIsApp(ownAppId); } if (OwnerIsBrowserFrame()) { // You can't be both a browser and an app frame. MOZ_ASSERT(!OwnerIsAppFrame()); nsCOMPtr<mozIApplication> containingApp = GetContainingApp(); uint32_t containingAppId = nsIScriptSecurityManager::NO_APP_ID; if (containingApp) { NS_ENSURE_SUCCESS(containingApp->GetLocalId(&containingAppId), NS_ERROR_FAILURE); } mDocShell->SetIsBrowserInsideApp(containingAppId); } if (OwnerIsBrowserOrAppFrame()) { nsCOMPtr<nsIObserverService> os = services::GetObserverService(); if (os) { os->NotifyObservers(NS_ISUPPORTS_CAST(nsIFrameLoader*, this), "in-process-browser-or-app-frame-shown", NULL); } if (mMessageManager) { mMessageManager->LoadFrameScript( NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js"), /* allowDelayedLoad = */ true); } } return NS_OK; } void nsFrameLoader::GetURL(nsString& aURI) { aURI.Truncate(); if (mOwnerContent->Tag() == nsGkAtoms::object) { mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::data, aURI); } else { mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::src, aURI); } } nsresult nsFrameLoader::CheckForRecursiveLoad(nsIURI* aURI) { nsresult rv; mDepthTooGreat = false; rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) { return rv; } NS_ASSERTION(!mRemoteFrame, "Shouldn't call CheckForRecursiveLoad on remote frames."); if (!mDocShell) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShellTreeItem> treeItem = do_QueryInterface(mDocShell); NS_ASSERTION(treeItem, "docshell must be a treeitem!"); // Check that we're still in the docshell tree. nsCOMPtr<nsIDocShellTreeOwner> treeOwner; treeItem->GetTreeOwner(getter_AddRefs(treeOwner)); NS_WARN_IF_FALSE(treeOwner, "Trying to load a new url to a docshell without owner!"); NS_ENSURE_STATE(treeOwner); int32_t ourType; rv = treeItem->GetItemType(&ourType); if (NS_SUCCEEDED(rv) && ourType != nsIDocShellTreeItem::typeContent) { // No need to do recursion-protection here XXXbz why not?? Do we really // trust people not to screw up with non-content docshells? return NS_OK; } // Bug 8065: Don't exceed some maximum depth in content frames // (MAX_DEPTH_CONTENT_FRAMES) nsCOMPtr<nsIDocShellTreeItem> parentAsItem; treeItem->GetSameTypeParent(getter_AddRefs(parentAsItem)); int32_t depth = 0; while (parentAsItem) { ++depth; if (depth >= MAX_DEPTH_CONTENT_FRAMES) { mDepthTooGreat = true; NS_WARNING("Too many nested content frames so giving up"); return NS_ERROR_UNEXPECTED; // Too deep, give up! (silently?) } nsCOMPtr<nsIDocShellTreeItem> temp; temp.swap(parentAsItem); temp->GetSameTypeParent(getter_AddRefs(parentAsItem)); } // Bug 136580: Check for recursive frame loading int32_t matchCount = 0; treeItem->GetSameTypeParent(getter_AddRefs(parentAsItem)); while (parentAsItem) { // Check the parent URI with the URI we're loading nsCOMPtr<nsIWebNavigation> parentAsNav(do_QueryInterface(parentAsItem)); if (parentAsNav) { // Does the URI match the one we're about to load? nsCOMPtr<nsIURI> parentURI; parentAsNav->GetCurrentURI(getter_AddRefs(parentURI)); if (parentURI) { // Bug 98158/193011: We need to ignore data after the # bool equal; rv = aURI->EqualsExceptRef(parentURI, &equal); NS_ENSURE_SUCCESS(rv, rv); if (equal) { matchCount++; if (matchCount >= MAX_SAME_URL_CONTENT_FRAMES) { NS_WARNING("Too many nested content frames have the same url (recursion?) so giving up"); return NS_ERROR_UNEXPECTED; } } } } nsCOMPtr<nsIDocShellTreeItem> temp; temp.swap(parentAsItem); temp->GetSameTypeParent(getter_AddRefs(parentAsItem)); } return NS_OK; } nsresult nsFrameLoader::GetWindowDimensions(nsRect& aRect) { // Need to get outer window position here nsIDocument* doc = mOwnerContent->GetDocument(); if (!doc) { return NS_ERROR_FAILURE; } if (doc->GetDisplayDocument()) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIWebNavigation> parentAsWebNav = do_GetInterface(doc->GetScriptGlobalObject()); if (!parentAsWebNav) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocShellTreeItem> parentAsItem(do_QueryInterface(parentAsWebNav)); nsCOMPtr<nsIDocShellTreeOwner> parentOwner; if (NS_FAILED(parentAsItem->GetTreeOwner(getter_AddRefs(parentOwner))) || !parentOwner) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIBaseWindow> treeOwnerAsWin(do_GetInterface(parentOwner)); treeOwnerAsWin->GetPosition(&aRect.x, &aRect.y); treeOwnerAsWin->GetSize(&aRect.width, &aRect.height); return NS_OK; } NS_IMETHODIMP nsFrameLoader::UpdatePositionAndSize(nsIFrame *aIFrame) { if (mRemoteFrame) { if (mRemoteBrowser) { nsIntSize size = GetSubDocumentSize(aIFrame); nsRect dimensions; NS_ENSURE_SUCCESS(GetWindowDimensions(dimensions), NS_ERROR_FAILURE); mRemoteBrowser->UpdateDimensions(dimensions, size); } return NS_OK; } return UpdateBaseWindowPositionAndSize(aIFrame); } nsresult nsFrameLoader::UpdateBaseWindowPositionAndSize(nsIFrame *aIFrame) { nsCOMPtr<nsIDocShell> docShell; GetDocShell(getter_AddRefs(docShell)); nsCOMPtr<nsIBaseWindow> baseWindow(do_QueryInterface(docShell)); // resize the sub document if (baseWindow) { int32_t x = 0; int32_t y = 0; nsWeakFrame weakFrame(aIFrame); baseWindow->GetPositionAndSize(&x, &y, nullptr, nullptr); if (!weakFrame.IsAlive()) { // GetPositionAndSize() killed us return NS_OK; } nsIntSize size = GetSubDocumentSize(aIFrame); baseWindow->SetPositionAndSize(x, y, size.width, size.height, false); } return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetRenderMode(uint32_t* aRenderMode) { *aRenderMode = mRenderMode; return NS_OK; } NS_IMETHODIMP nsFrameLoader::SetRenderMode(uint32_t aRenderMode) { if (aRenderMode == mRenderMode) { return NS_OK; } mRenderMode = aRenderMode; return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetEventMode(uint32_t* aEventMode) { *aEventMode = mEventMode; return NS_OK; } NS_IMETHODIMP nsFrameLoader::SetEventMode(uint32_t aEventMode) { mEventMode = aEventMode; return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetClipSubdocument(bool* aResult) { *aResult = mClipSubdocument; return NS_OK; } NS_IMETHODIMP nsFrameLoader::SetClipSubdocument(bool aClip) { mClipSubdocument = aClip; nsIFrame* frame = GetPrimaryFrameOfOwningContent(); if (frame) { frame->InvalidateFrame(); frame->PresContext()->PresShell()-> FrameNeedsReflow(frame, nsIPresShell::eResize, NS_FRAME_IS_DIRTY); nsSubDocumentFrame* subdocFrame = do_QueryFrame(frame); if (subdocFrame) { nsIFrame* subdocRootFrame = subdocFrame->GetSubdocumentRootFrame(); if (subdocRootFrame) { nsIFrame* subdocRootScrollFrame = subdocRootFrame->PresContext()->PresShell()-> GetRootScrollFrame(); if (subdocRootScrollFrame) { frame->PresContext()->PresShell()-> FrameNeedsReflow(frame, nsIPresShell::eResize, NS_FRAME_IS_DIRTY); } } } } return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetClampScrollPosition(bool* aResult) { *aResult = mClampScrollPosition; return NS_OK; } NS_IMETHODIMP nsFrameLoader::SetClampScrollPosition(bool aClamp) { mClampScrollPosition = aClamp; // When turning clamping on, make sure the current position is clamped. if (aClamp) { nsIFrame* frame = GetPrimaryFrameOfOwningContent(); if (frame) { nsSubDocumentFrame* subdocFrame = do_QueryFrame(frame); if (subdocFrame) { nsIFrame* subdocRootFrame = subdocFrame->GetSubdocumentRootFrame(); if (subdocRootFrame) { nsIScrollableFrame* subdocRootScrollFrame = subdocRootFrame->PresContext()->PresShell()-> GetRootScrollFrameAsScrollable(); if (subdocRootScrollFrame) { subdocRootScrollFrame->ScrollTo(subdocRootScrollFrame->GetScrollPosition(), nsIScrollableFrame::INSTANT); } } } } } return NS_OK; } nsIntSize nsFrameLoader::GetSubDocumentSize(const nsIFrame *aIFrame) { nsSize docSizeAppUnits; nsPresContext* presContext = aIFrame->PresContext(); nsCOMPtr<nsIDOMHTMLFrameElement> frameElem = do_QueryInterface(aIFrame->GetContent()); if (frameElem) { docSizeAppUnits = aIFrame->GetSize(); } else { docSizeAppUnits = aIFrame->GetContentRect().Size(); } return nsIntSize(presContext->AppUnitsToDevPixels(docSizeAppUnits.width), presContext->AppUnitsToDevPixels(docSizeAppUnits.height)); } bool nsFrameLoader::TryRemoteBrowser() { NS_ASSERTION(!mRemoteBrowser, "TryRemoteBrowser called with a remote browser already?"); nsIDocument* doc = mOwnerContent->GetDocument(); if (!doc) { return false; } if (doc->GetDisplayDocument()) { // Don't allow subframe loads in external reference documents return false; } nsCOMPtr<nsIWebNavigation> parentAsWebNav = do_GetInterface(doc->GetScriptGlobalObject()); if (!parentAsWebNav) { return false; } nsCOMPtr<nsIDocShellTreeItem> parentAsItem(do_QueryInterface(parentAsWebNav)); // <iframe mozbrowser> gets to skip these checks. if (!OwnerIsBrowserOrAppFrame()) { int32_t parentType; parentAsItem->GetItemType(&parentType); if (parentType != nsIDocShellTreeItem::typeChrome) { return false; } if (!mOwnerContent->IsXUL()) { return false; } nsAutoString value; mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::type, value); if (!value.LowerCaseEqualsLiteral("content") && !StringBeginsWith(value, NS_LITERAL_STRING("content-"), nsCaseInsensitiveStringComparator())) { return false; } } uint32_t chromeFlags = 0; nsCOMPtr<nsIDocShellTreeOwner> parentOwner; if (NS_FAILED(parentAsItem->GetTreeOwner(getter_AddRefs(parentOwner))) || !parentOwner) { return false; } nsCOMPtr<nsIXULWindow> window(do_GetInterface(parentOwner)); if (!window) { return false; } if (NS_FAILED(window->GetChromeFlags(&chromeFlags))) { return false; } MutableTabContext context; nsCOMPtr<mozIApplication> ownApp = GetOwnApp(); nsCOMPtr<mozIApplication> containingApp = GetContainingApp(); ScrollingBehavior scrollingBehavior = DEFAULT_SCROLLING; if (mOwnerContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::mozasyncpanzoom, nsGkAtoms::_true, eCaseMatters)) { scrollingBehavior = ASYNC_PAN_ZOOM; } if (ownApp) { context.SetTabContextForAppFrame(ownApp, containingApp, scrollingBehavior); } else if (OwnerIsBrowserFrame()) { // The |else| above is unnecessary; OwnerIsBrowserFrame() implies !ownApp. context.SetTabContextForBrowserFrame(containingApp, scrollingBehavior); } mRemoteBrowser = ContentParent::CreateBrowserOrApp(context); if (mRemoteBrowser) { nsCOMPtr<nsIDOMElement> element = do_QueryInterface(mOwnerContent); mRemoteBrowser->SetOwnerElement(element); // If we're an app, send the frame element's mozapptype down to the child // process. This ends up in TabChild::GetAppType(). if (ownApp) { nsAutoString appType; mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::mozapptype, appType); mRemoteBrowser->SendSetAppType(appType); } nsCOMPtr<nsIDocShellTreeItem> rootItem; parentAsItem->GetRootTreeItem(getter_AddRefs(rootItem)); nsCOMPtr<nsIDOMWindow> rootWin = do_GetInterface(rootItem); nsCOMPtr<nsIDOMChromeWindow> rootChromeWin = do_QueryInterface(rootWin); NS_ABORT_IF_FALSE(rootChromeWin, "How did we not get a chrome window here?"); nsCOMPtr<nsIBrowserDOMWindow> browserDOMWin; rootChromeWin->GetBrowserDOMWindow(getter_AddRefs(browserDOMWin)); mRemoteBrowser->SetBrowserDOMWindow(browserDOMWin); mChildHost = static_cast<ContentParent*>(mRemoteBrowser->Manager()); } return true; } mozilla::dom::PBrowserParent* nsFrameLoader::GetRemoteBrowser() { return mRemoteBrowser; } NS_IMETHODIMP nsFrameLoader::ActivateRemoteFrame() { if (mRemoteBrowser) { mRemoteBrowser->Activate(); return NS_OK; } return NS_ERROR_UNEXPECTED; } NS_IMETHODIMP nsFrameLoader::DeactivateRemoteFrame() { if (mRemoteBrowser) { mRemoteBrowser->Deactivate(); return NS_OK; } return NS_ERROR_UNEXPECTED; } NS_IMETHODIMP nsFrameLoader::SendCrossProcessMouseEvent(const nsAString& aType, float aX, float aY, int32_t aButton, int32_t aClickCount, int32_t aModifiers, bool aIgnoreRootScrollFrame) { if (mRemoteBrowser) { mRemoteBrowser->SendMouseEvent(aType, aX, aY, aButton, aClickCount, aModifiers, aIgnoreRootScrollFrame); return NS_OK; } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsFrameLoader::ActivateFrameEvent(const nsAString& aType, bool aCapture) { if (mRemoteBrowser) { return mRemoteBrowser->SendActivateFrameEvent(nsString(aType), aCapture) ? NS_OK : NS_ERROR_NOT_AVAILABLE; } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsFrameLoader::SendCrossProcessKeyEvent(const nsAString& aType, int32_t aKeyCode, int32_t aCharCode, int32_t aModifiers, bool aPreventDefault) { if (mRemoteBrowser) { mRemoteBrowser->SendKeyEvent(aType, aKeyCode, aCharCode, aModifiers, aPreventDefault); return NS_OK; } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsFrameLoader::GetDelayRemoteDialogs(bool* aRetVal) { *aRetVal = mDelayRemoteDialogs; return NS_OK; } NS_IMETHODIMP nsFrameLoader::SetDelayRemoteDialogs(bool aDelay) { if (mRemoteBrowser && mDelayRemoteDialogs && !aDelay) { nsRefPtr<nsIRunnable> ev = NS_NewRunnableMethod(mRemoteBrowser, &mozilla::dom::TabParent::HandleDelayedDialogs); NS_DispatchToCurrentThread(ev); } mDelayRemoteDialogs = aDelay; return NS_OK; } nsresult nsFrameLoader::CreateStaticClone(nsIFrameLoader* aDest) { nsFrameLoader* dest = static_cast<nsFrameLoader*>(aDest); dest->MaybeCreateDocShell(); NS_ENSURE_STATE(dest->mDocShell); nsCOMPtr<nsIDOMDocument> dummy = do_GetInterface(dest->mDocShell); nsCOMPtr<nsIContentViewer> viewer; dest->mDocShell->GetContentViewer(getter_AddRefs(viewer)); NS_ENSURE_STATE(viewer); nsCOMPtr<nsIDocShell> origDocShell; GetDocShell(getter_AddRefs(origDocShell)); nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(origDocShell); nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc); NS_ENSURE_STATE(doc); nsCOMPtr<nsIDocument> clonedDoc = doc->CreateStaticClone(dest->mDocShell); nsCOMPtr<nsIDOMDocument> clonedDOMDoc = do_QueryInterface(clonedDoc); viewer->SetDOMDocument(clonedDOMDoc); return NS_OK; } bool nsFrameLoader::DoLoadFrameScript(const nsAString& aURL) { mozilla::dom::PBrowserParent* tabParent = GetRemoteBrowser(); if (tabParent) { return tabParent->SendLoadRemoteScript(nsString(aURL)); } nsRefPtr<nsInProcessTabChildGlobal> tabChild = static_cast<nsInProcessTabChildGlobal*>(GetTabChildGlobalAsEventTarget()); if (tabChild) { tabChild->LoadFrameScript(aURL); } return true; } class nsAsyncMessageToChild : public nsRunnable { public: nsAsyncMessageToChild(nsFrameLoader* aFrameLoader, const nsAString& aMessage, const StructuredCloneData& aData) : mFrameLoader(aFrameLoader), mMessage(aMessage) { if (aData.mDataLength && !mData.copy(aData.mData, aData.mDataLength)) { NS_RUNTIMEABORT("OOM"); } mClosure = aData.mClosure; } NS_IMETHOD Run() { nsInProcessTabChildGlobal* tabChild = static_cast<nsInProcessTabChildGlobal*>(mFrameLoader->mChildMessageManager.get()); if (tabChild && tabChild->GetInnerManager()) { nsFrameScriptCx cx(static_cast<nsIDOMEventTarget*>(tabChild), tabChild); StructuredCloneData data; data.mData = mData.data(); data.mDataLength = mData.nbytes(); data.mClosure = mClosure; nsRefPtr<nsFrameMessageManager> mm = tabChild->GetInnerManager(); mm->ReceiveMessage(static_cast<nsIDOMEventTarget*>(tabChild), mMessage, false, &data, nullptr, nullptr, nullptr); } return NS_OK; } nsRefPtr<nsFrameLoader> mFrameLoader; nsString mMessage; JSAutoStructuredCloneBuffer mData; StructuredCloneClosure mClosure; }; bool nsFrameLoader::DoSendAsyncMessage(const nsAString& aMessage, const StructuredCloneData& aData) { PBrowserParent* tabParent = GetRemoteBrowser(); if (tabParent) { ClonedMessageData data; SerializedStructuredCloneBuffer& buffer = data.data(); buffer.data = aData.mData; buffer.dataLength = aData.mDataLength; const nsTArray<nsCOMPtr<nsIDOMBlob> >& blobs = aData.mClosure.mBlobs; if (!blobs.IsEmpty()) { InfallibleTArray<PBlobParent*>& blobParents = data.blobsParent(); uint32_t length = blobs.Length(); blobParents.SetCapacity(length); ContentParent* cp = static_cast<ContentParent*>(tabParent->Manager()); for (uint32_t i = 0; i < length; ++i) { BlobParent* blobParent = cp->GetOrCreateActorForBlob(blobs[i]); if (!blobParent) { return false; } blobParents.AppendElement(blobParent); } } return tabParent->SendAsyncMessage(nsString(aMessage), data); } if (mChildMessageManager) { nsRefPtr<nsIRunnable> ev = new nsAsyncMessageToChild(this, aMessage, aData); NS_DispatchToCurrentThread(ev); return true; } // We don't have any targets to send our asynchronous message to. return false; } bool nsFrameLoader::CheckPermission(const nsAString& aPermission) { return AssertAppProcessPermission(GetRemoteBrowser(), NS_ConvertUTF16toUTF8(aPermission).get()); } NS_IMETHODIMP nsFrameLoader::GetMessageManager(nsIMessageSender** aManager) { EnsureMessageManager(); if (mMessageManager) { CallQueryInterface(mMessageManager, aManager); } return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetContentViewsIn(float aXPx, float aYPx, float aTopSize, float aRightSize, float aBottomSize, float aLeftSize, uint32_t* aLength, nsIContentView*** aResult) { nscoord x = nsPresContext::CSSPixelsToAppUnits(aXPx - aLeftSize); nscoord y = nsPresContext::CSSPixelsToAppUnits(aYPx - aTopSize); nscoord w = nsPresContext::CSSPixelsToAppUnits(aLeftSize + aRightSize) + 1; nscoord h = nsPresContext::CSSPixelsToAppUnits(aTopSize + aBottomSize) + 1; nsRect target(x, y, w, h); nsIFrame* frame = GetPrimaryFrameOfOwningContent(); nsTArray<ViewID> ids; nsLayoutUtils::GetRemoteContentIds(frame, target, ids, true); if (ids.Length() == 0 || !GetCurrentRemoteFrame()) { *aResult = nullptr; *aLength = 0; return NS_OK; } nsIContentView** result = reinterpret_cast<nsIContentView**>( NS_Alloc(ids.Length() * sizeof(nsIContentView*))); for (uint32_t i = 0; i < ids.Length(); i++) { nsIContentView* view = GetCurrentRemoteFrame()->GetContentView(ids[i]); NS_ABORT_IF_FALSE(view, "Retrieved ID from RenderFrameParent, it should be valid!"); nsRefPtr<nsIContentView>(view).forget(&result[i]); } *aResult = result; *aLength = ids.Length(); return NS_OK; } NS_IMETHODIMP nsFrameLoader::GetRootContentView(nsIContentView** aContentView) { RenderFrameParent* rfp = GetCurrentRemoteFrame(); if (!rfp) { *aContentView = nullptr; return NS_OK; } nsContentView* view = rfp->GetContentView(); NS_ABORT_IF_FALSE(view, "Should always be able to create root scrollable!"); nsRefPtr<nsIContentView>(view).forget(aContentView); return NS_OK; } nsresult nsFrameLoader::EnsureMessageManager() { NS_ENSURE_STATE(mOwnerContent); nsresult rv = MaybeCreateDocShell(); if (NS_FAILED(rv)) { return rv; } if (!mIsTopLevelContent && !OwnerIsBrowserOrAppFrame() && !mRemoteFrame) { return NS_OK; } if (mMessageManager) { if (ShouldUseRemoteProcess()) { mMessageManager->SetCallback(mRemoteBrowserShown ? this : nullptr); } return NS_OK; } nsIScriptContext* sctx = mOwnerContent->GetContextForEventHandlers(&rv); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_STATE(sctx); JSContext* cx = sctx->GetNativeContext(); NS_ENSURE_STATE(cx); nsCOMPtr<nsIDOMChromeWindow> chromeWindow = do_QueryInterface(GetOwnerDoc()->GetWindow()); nsCOMPtr<nsIMessageBroadcaster> parentManager; if (chromeWindow) { chromeWindow->GetMessageManager(getter_AddRefs(parentManager)); } if (ShouldUseRemoteProcess()) { mMessageManager = new nsFrameMessageManager(mRemoteBrowserShown ? this : nullptr, static_cast<nsFrameMessageManager*>(parentManager.get()), cx, MM_CHROME); } else { mMessageManager = new nsFrameMessageManager(nullptr, static_cast<nsFrameMessageManager*>(parentManager.get()), cx, MM_CHROME); mChildMessageManager = new nsInProcessTabChildGlobal(mDocShell, mOwnerContent, mMessageManager); // Force pending frame scripts to be loaded. mMessageManager->SetCallback(this); } return NS_OK; } nsIDOMEventTarget* nsFrameLoader::GetTabChildGlobalAsEventTarget() { return static_cast<nsInProcessTabChildGlobal*>(mChildMessageManager.get()); } NS_IMETHODIMP nsFrameLoader::GetOwnerElement(nsIDOMElement **aElement) { nsCOMPtr<nsIDOMElement> ownerElement = do_QueryInterface(mOwnerContent); ownerElement.forget(aElement); return NS_OK; } void nsFrameLoader::SetRemoteBrowser(nsITabParent* aTabParent) { MOZ_ASSERT(!mRemoteBrowser); MOZ_ASSERT(!mCurrentRemoteFrame); mRemoteFrame = true; mRemoteBrowser = static_cast<TabParent*>(aTabParent); ShowRemoteFrame(nsIntSize(0, 0)); } void nsFrameLoader::SetDetachedSubdocView(nsView* aDetachedViews, nsIDocument* aContainerDoc) { mDetachedSubdocViews = aDetachedViews; mContainerDocWhileDetached = aContainerDoc; } nsView* nsFrameLoader::GetDetachedSubdocView(nsIDocument** aContainerDoc) const { NS_IF_ADDREF(*aContainerDoc = mContainerDocWhileDetached); return mDetachedSubdocViews; } /* virtual */ void nsFrameLoader::AttributeChanged(nsIDocument* aDocument, mozilla::dom::Element* aElement, int32_t aNameSpaceID, nsIAtom* aAttribute, int32_t aModType) { MOZ_ASSERT(mObservingOwnerContent); // TODO: Implement ContentShellAdded for remote browsers (bug 658304) MOZ_ASSERT(!mRemoteBrowser); if (aNameSpaceID != kNameSpaceID_None || aAttribute != TypeAttrName()) { return; } if (aElement != mOwnerContent) { return; } // Note: This logic duplicates a lot of logic in // MaybeCreateDocshell. We should fix that. // Notify our enclosing chrome that our type has changed. We only do this // if our parent is chrome, since in all other cases we're random content // subframes and the treeowner shouldn't worry about us. nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(mDocShell)); if (!docShellAsItem) { return; } nsCOMPtr<nsIDocShellTreeItem> parentItem; docShellAsItem->GetParent(getter_AddRefs(parentItem)); if (!parentItem) { return; } int32_t parentType; parentItem->GetItemType(&parentType); if (parentType != nsIDocShellTreeItem::typeChrome) { return; } nsCOMPtr<nsIDocShellTreeOwner> parentTreeOwner; parentItem->GetTreeOwner(getter_AddRefs(parentTreeOwner)); if (!parentTreeOwner) { return; } nsAutoString value; aElement->GetAttr(kNameSpaceID_None, TypeAttrName(), value); bool is_primary = value.LowerCaseEqualsLiteral("content-primary"); #ifdef MOZ_XUL // when a content panel is no longer primary, hide any open popups it may have if (!is_primary) { nsXULPopupManager* pm = nsXULPopupManager::GetInstance(); if (pm) pm->HidePopupsInDocShell(docShellAsItem); } #endif parentTreeOwner->ContentShellRemoved(docShellAsItem); if (value.LowerCaseEqualsLiteral("content") || StringBeginsWith(value, NS_LITERAL_STRING("content-"), nsCaseInsensitiveStringComparator())) { bool is_targetable = is_primary || value.LowerCaseEqualsLiteral("content-targetable"); parentTreeOwner->ContentShellAdded(docShellAsItem, is_primary, is_targetable, value); } } void nsFrameLoader::ResetPermissionManagerStatus() { // Finding the new app Id: // . first we check if the owner is an app frame // . second, we check if the owner is a browser frame // in both cases we populate the appId variable. uint32_t appId = nsIScriptSecurityManager::NO_APP_ID; if (OwnerIsAppFrame()) { // You can't be both an app and a browser frame. MOZ_ASSERT(!OwnerIsBrowserFrame()); nsCOMPtr<mozIApplication> ownApp = GetOwnApp(); MOZ_ASSERT(ownApp); uint32_t ownAppId = nsIScriptSecurityManager::NO_APP_ID; if (ownApp && NS_SUCCEEDED(ownApp->GetLocalId(&ownAppId))) { appId = ownAppId; } } if (OwnerIsBrowserFrame()) { // You can't be both a browser and an app frame. MOZ_ASSERT(!OwnerIsAppFrame()); nsCOMPtr<mozIApplication> containingApp = GetContainingApp(); uint32_t containingAppId = nsIScriptSecurityManager::NO_APP_ID; if (containingApp && NS_SUCCEEDED(containingApp->GetLocalId(&containingAppId))) { appId = containingAppId; } } // Nothing changed. if (appId == mAppIdSentToPermissionManager) { return; } nsCOMPtr<nsIPermissionManager> permMgr = do_GetService(NS_PERMISSIONMANAGER_CONTRACTID); if (!permMgr) { NS_ERROR("No PermissionManager available!"); return; } // If previously we registered an appId, we have to unregister it. if (mAppIdSentToPermissionManager != nsIScriptSecurityManager::NO_APP_ID) { permMgr->ReleaseAppId(mAppIdSentToPermissionManager); mAppIdSentToPermissionManager = nsIScriptSecurityManager::NO_APP_ID; } // Register the new AppId. if (appId != nsIScriptSecurityManager::NO_APP_ID) { mAppIdSentToPermissionManager = appId; permMgr->AddrefAppId(mAppIdSentToPermissionManager); } }
30.972445
117
0.711087
CGCL-codes
90cf0d42a44b877bb39975b9c10bdba938e060e6
8,399
cpp
C++
src/plugins/gps_importer/qgsgpsdevicedialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/gps_importer/qgsgpsdevicedialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/gps_importer/qgsgpsdevicedialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** * Copyright (C) 2004 by Lars Luthman * larsl@users.sourceforge.net * * * This is a plugin generated from the QGIS plugin template * * * * 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. * ***************************************************************************/ #include "qgsgpsdevicedialog.h" #include "qgsguiutils.h" #include "qgssettings.h" #include <QMessageBox> QgsGpsDeviceDialog::QgsGpsDeviceDialog( std::map < QString, QgsGpsDevice * > &devices ) : QDialog( nullptr, QgsGuiUtils::ModalDialogFlags ) , mDevices( devices ) { setupUi( this ); connect( pbnNewDevice, &QPushButton::clicked, this, &QgsGpsDeviceDialog::pbnNewDevice_clicked ); connect( pbnDeleteDevice, &QPushButton::clicked, this, &QgsGpsDeviceDialog::pbnDeleteDevice_clicked ); connect( pbnUpdateDevice, &QPushButton::clicked, this, &QgsGpsDeviceDialog::pbnUpdateDevice_clicked ); setAttribute( Qt::WA_DeleteOnClose ); // Manually set the relative size of the two main parts of the // device dialog box. QObject::connect( lbDeviceList, &QListWidget::currentItemChanged, this, &QgsGpsDeviceDialog::slotSelectionChanged ); slotUpdateDeviceList(); } void QgsGpsDeviceDialog::pbnNewDevice_clicked() { std::map<QString, QgsGpsDevice *>::const_iterator iter = mDevices.begin(); QString deviceName = tr( "New device %1" ); int i = 1; for ( ; iter != mDevices.end(); ++i ) iter = mDevices.find( deviceName.arg( i ) ); deviceName = deviceName.arg( i - 1 ); mDevices[deviceName] = new QgsGpsDevice; writeDeviceSettings(); slotUpdateDeviceList( deviceName ); emit devicesChanged(); } void QgsGpsDeviceDialog::pbnDeleteDevice_clicked() { if ( QMessageBox::warning( this, tr( "Delete Device" ), tr( "Are you sure that you want to delete this device?" ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Ok ) { std::map<QString, QgsGpsDevice *>::iterator iter = mDevices.find( lbDeviceList->currentItem()->text() ); if ( iter != mDevices.end() ) { delete iter->second; mDevices.erase( iter ); writeDeviceSettings(); slotUpdateDeviceList(); emit devicesChanged(); } } } void QgsGpsDeviceDialog::pbnUpdateDevice_clicked() { if ( lbDeviceList->count() > 0 ) { std::map<QString, QgsGpsDevice *>::iterator iter = mDevices.find( lbDeviceList->currentItem()->text() ); if ( iter != mDevices.end() ) { delete iter->second; mDevices.erase( iter ); mDevices[leDeviceName->text()] = new QgsGpsDevice( leWptDown->text(), leWptUp->text(), leRteDown->text(), leRteUp->text(), leTrkDown->text(), leTrkUp->text() ); writeDeviceSettings(); slotUpdateDeviceList( leDeviceName->text() ); emit devicesChanged(); } } } void QgsGpsDeviceDialog::slotUpdateDeviceList( const QString &selection ) { QString selected; if ( selection.isEmpty() ) { QListWidgetItem *item = lbDeviceList->currentItem(); selected = ( item ? item->text() : QString() ); } else { selected = selection; } // We're going to be changing the selected item, so disable our // notificaton of that. QObject::disconnect( lbDeviceList, &QListWidget::currentItemChanged, this, &QgsGpsDeviceDialog::slotSelectionChanged ); lbDeviceList->clear(); std::map<QString, QgsGpsDevice *>::const_iterator iter; for ( iter = mDevices.begin(); iter != mDevices.end(); ++iter ) { QListWidgetItem *item = new QListWidgetItem( iter->first, lbDeviceList ); if ( iter->first == selected ) { lbDeviceList->setCurrentItem( item ); } } if ( !lbDeviceList->currentItem() && lbDeviceList->count() > 0 ) lbDeviceList->setCurrentRow( 0 ); // Update the display and reconnect the selection changed signal slotSelectionChanged( lbDeviceList->currentItem() ); QObject::connect( lbDeviceList, &QListWidget::currentItemChanged, this, &QgsGpsDeviceDialog::slotSelectionChanged ); } void QgsGpsDeviceDialog::slotSelectionChanged( QListWidgetItem *current ) { if ( lbDeviceList->count() > 0 ) { QString devName = current->text(); leDeviceName->setText( devName ); QgsGpsDevice *device = mDevices[devName]; leWptDown->setText( device-> importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leWptUp->setText( device-> exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leRteDown->setText( device-> importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leRteUp->setText( device-> exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leTrkDown->setText( device-> importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leTrkUp->setText( device-> exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); } } void QgsGpsDeviceDialog::writeDeviceSettings() { QStringList deviceNames; QgsSettings settings; QString devPath = QStringLiteral( "/Plugin-GPS/devices/%1" ); settings.remove( QStringLiteral( "/Plugin-GPS/devices" ) ); std::map<QString, QgsGpsDevice *>::const_iterator iter; for ( iter = mDevices.begin(); iter != mDevices.end(); ++iter ) { deviceNames.append( iter->first ); QString wptDownload = iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString wptUpload = iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString rteDownload = iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString rteUpload = iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString trkDownload = iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString trkUpload = iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); settings.setValue( devPath.arg( iter->first ) + "/wptdownload", wptDownload ); settings.setValue( devPath.arg( iter->first ) + "/wptupload", wptUpload ); settings.setValue( devPath.arg( iter->first ) + "/rtedownload", rteDownload ); settings.setValue( devPath.arg( iter->first ) + "/rteupload", rteUpload ); settings.setValue( devPath.arg( iter->first ) + "/trkdownload", trkDownload ); settings.setValue( devPath.arg( iter->first ) + "/trkupload", trkUpload ); } settings.setValue( QStringLiteral( "/Plugin-GPS/devicelist" ), deviceNames ); } void QgsGpsDeviceDialog::on_pbnClose_clicked() { close(); }
42.419192
175
0.614716
dyna-mis
90d0e254fc7e7a06f064b22e46d16f60071924a9
21,526
cpp
C++
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
crskycode/msLTBImporter
be8a04c5365746c46a1d7804909e04a741d86b44
[ "MIT" ]
3
2021-03-02T15:55:01.000Z
2021-10-21T07:11:17.000Z
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
crskycode/msLTBImporter
be8a04c5365746c46a1d7804909e04a741d86b44
[ "MIT" ]
1
2021-09-27T02:38:49.000Z
2021-11-06T16:09:21.000Z
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
crskycode/msLTBImporter
be8a04c5365746c46a1d7804909e04a741d86b44
[ "MIT" ]
1
2021-04-26T13:22:51.000Z
2021-04-26T13:22:51.000Z
// d3dmeshrendobj_skel.cpp //#include "precompile.h" #include "d3dmeshrendobj_skel.h" //#include "renderstruct.h" #include "ltb.h" //#include "d3d_device.h" //#include "d3d_texture.h" //#include "d3d_renderstatemgr.h" //#include "d3d_draw.h" //#include "ltvertexshadermgr.h" //#include "ltpixelshadermgr.h" //#include "de_objects.h" //#include "ltshaderdevicestateimp.h" //#include "rendererconsolevars.h" //#include "LTEffectImpl.h" //#include "lteffectshadermgr.h" #include <set> #include <vector> //IClientShell game client shell object. //#include "iclientshell.h" //static IClientShell *i_client_shell; //define_holder(IClientShell, i_client_shell); CD3DSkelMesh::CD3DSkelMesh() { Reset(); } CD3DSkelMesh::~CD3DSkelMesh() { FreeAll(); } // ------------------------------------------------------------------------ // CalcUsedNodes() // specifically find the nodes that are used by the mesh AND are the most // distal nodes in the set. We don't need interior nodes since the xform evaulation // paths start at the leaves. // NOTE : t.f fix // This algorithm is actually in the packer, its here for models that are // version 21 or less. This should be removed once all models are version 22. // ------------------------------------------------------------------------ void CD3DSkelMesh::CalcUsedNodes( Model *pModel ) { std::set<uint32> node_set ; std::vector<uint32> node_list ; for( uint32 iBoneSet = 0 ; iBoneSet < m_iBoneSetCount ; iBoneSet++ ) { for( uint32 iBoneCnt = 0 ; iBoneCnt < 4 ; iBoneCnt++ ) { node_set.insert( (uint32)m_pBoneSetArray[iBoneSet].BoneSetArray[iBoneCnt]); } } std::set<uint32>::iterator set_it = node_set.begin(); // create set of terminal nodes for finding paths. for( ; set_it != node_set.end() ; set_it++ ) { uint32 iNode = *set_it ; if( iNode == 255 ) continue ; ModelNode *pModelNode = pModel->GetNode(iNode); // check if children are in the set. // if none of the children are in the set, add the node to the final list. uint32 nChildren = pModelNode->m_Children.GetSize(); uint32 iChild ; bool IsTerminalNode = true ; for( iChild = 0 ; iChild < nChildren ; iChild++ ) { // if we find a child that is in the set, quit the search. if( node_set.find( pModelNode->m_Children[iChild]->m_NodeIndex ) != node_set.end() ) { IsTerminalNode = false ; continue ; } } // if all the children didn't have a parent in the mesh's bone list, add this node // as a terminal node. if(IsTerminalNode) { node_list.push_back(*set_it); } } // transfer the new information from here to the renderobject. CreateUsedNodeList(node_list.size()); for( uint32 iNodeCnt =0 ; iNodeCnt < node_list.size() ; iNodeCnt++ ) { m_pUsedNodeList[iNodeCnt] = node_list[iNodeCnt]; } } void CD3DSkelMesh::Reset() { // m_VBController.Reset(); m_iMaxBonesPerVert = 0; m_iMaxBonesPerTri = 0; m_iVertCount = 0; m_iPolyCount = 0; m_eRenderMethod = eD3DRenderDirect; m_iBoneSetCount = 0; m_pBoneSetArray = NULL; m_VertType = eNO_WORLD_BLENDS; // m_bSWVertProcessing = ((g_Device.GetDeviceCaps()->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0) ? true : false; m_bSWVSBuffers = false; // Use software processing for shaders ? // if ( g_Device.GetDeviceCaps()->VertexShaderVersion < D3DVS_VERSION(1,1) ) // m_bSWVSBuffers = true; // in case software has been forced // if ( g_CV_ForceSWVertProcess ) // m_bSWVertProcessing = true; m_pIndexData = NULL; m_bNonFixPipeData = false; m_bReIndexedBones = false; m_pReIndexedBoneList= NULL; for (uint32 i = 0; i < 4; ++i) m_pVertData[i] = NULL; } void CD3DSkelMesh::FreeAll() { // m_VBController.FreeAll(); if (m_pBoneSetArray) { delete[] m_pBoneSetArray; m_pBoneSetArray = NULL; } if (m_pIndexData) { delete[] m_pIndexData; m_pIndexData = NULL; } if (m_pReIndexedBoneList) { delete[] m_pReIndexedBoneList; m_pReIndexedBoneList = NULL; } for (uint32 i = 0; i < 4; ++i) { if (m_pVertData[i]) { delete[] m_pVertData[i]; m_pVertData[i] = NULL; } } Reset(); } bool CD3DSkelMesh::Load(ILTStream& File, LTB_Header& LTBHeader) { if (LTBHeader.m_iFileType != LTB_D3D_MODEL_FILE) { // OutputDebugString("Error: Wrong file type in CD3DSkelMesh::Load\n"); return false; } if (LTBHeader.m_iVersion != CD3D_LTB_LOAD_VERSION) { // OutputDebugString("Error: Wrong file version in CD3DSkelMesh::Load\n"); return false; } // Read in the basics... uint32 iObjSize; File.Read(&iObjSize,sizeof(iObjSize)); File.Read(&m_iVertCount,sizeof(m_iVertCount)); File.Read(&m_iPolyCount,sizeof(m_iPolyCount)); File.Read(&m_iMaxBonesPerTri,sizeof(m_iMaxBonesPerTri)); File.Read(&m_iMaxBonesPerVert,sizeof(m_iMaxBonesPerVert)); File.Read(&m_bReIndexedBones,sizeof(m_bReIndexedBones)); File.Read(&m_VertStreamFlags[0],sizeof(uint32)*4); // Are we using Matrix Palettes... bool bUseMatrixPalettes; File.Read(&bUseMatrixPalettes,sizeof(bUseMatrixPalettes)); if (bUseMatrixPalettes) { m_eRenderMethod = eD3DRenderMatrixPalettes; return Load_MP(File); } else { m_eRenderMethod = eD3DRenderDirect; return Load_RD(File); } } bool CD3DSkelMesh::Load_RD(ILTStream& File) { // What type of Vert do we need? switch (m_iMaxBonesPerTri) { case 1 : m_VertType = eNO_WORLD_BLENDS; break; case 2 : m_VertType = eNONINDEXED_B1; break; case 3 : m_VertType = eNONINDEXED_B2; break; case 4 : m_VertType = eNONINDEXED_B3; break; default : assert(0); return false; } // Read in our Verts... for (uint32 i=0;i<4;++i) { if (!m_VertStreamFlags[i]) continue; uint32 iVertexSize = 0; // Figure out the vertex size... uint32 iVertFlags = 0; uint32 iUVSets = 0; GetVertexFlags_and_Size(m_VertType,m_VertStreamFlags[i],iVertFlags,iVertexSize,iUVSets,m_bNonFixPipeData); uint32 iSize = iVertexSize * m_iVertCount; // Alloc the VertData... LT_MEM_TRACK_ALLOC(m_pVertData[i] = new uint8[iSize],LT_MEM_TYPE_RENDERER); File.Read(m_pVertData[i],iSize); } // Read in pIndexList... LT_MEM_TRACK_ALLOC(m_pIndexData = new uint8[sizeof(uint16) * m_iPolyCount * 3],LT_MEM_TYPE_RENDERER); File.Read(m_pIndexData,sizeof(uint16) * m_iPolyCount * 3); // Allocate and read in the BoneSets... File.Read(&m_iBoneSetCount,sizeof(m_iBoneSetCount)); LT_MEM_TRACK_ALLOC(m_pBoneSetArray = new BoneSetListItem[m_iBoneSetCount],LT_MEM_TYPE_RENDERER); if (!m_pBoneSetArray) return false; File.Read(m_pBoneSetArray,sizeof(BoneSetListItem)*m_iBoneSetCount); // Create the VBs and stuff... ReCreateObject(); return true; } bool CD3DSkelMesh::Load_MP(ILTStream& File) { // Read in out Min/Max Bones (effecting this guy)... File.Read(&m_iMinBone,sizeof(m_iMinBone)); File.Read(&m_iMaxBone,sizeof(m_iMaxBone)); // What type of Vert do we need? switch (m_iMaxBonesPerVert) { case 2 : m_VertType = eINDEXED_B1; break; case 3 : m_VertType = eINDEXED_B2; break; case 4 : m_VertType = eINDEXED_B3; break; default : assert(0); return false; } // If we are using re-indexed bones, read them in... if (m_bReIndexedBones) { uint32 iBoneCount = 0; File.Read(&iBoneCount,sizeof(iBoneCount)); assert(iBoneCount < 10000 && "Crazy bone count, checked your packed model format."); LT_MEM_TRACK_ALLOC(m_pReIndexedBoneList = new uint32[iBoneCount],LT_MEM_TYPE_RENDERER); File.Read(m_pReIndexedBoneList,sizeof(uint32)*iBoneCount); } // Read in our Verts... for (uint32 i=0;i<4;++i) { if (!m_VertStreamFlags[i]) continue; uint32 iVertexSize = 0; // Figure out the vertex size... uint32 iVertFlags = 0; uint32 iUVSets = 0; GetVertexFlags_and_Size(m_VertType,m_VertStreamFlags[i],iVertFlags,iVertexSize,iUVSets,m_bNonFixPipeData); uint32 iSize = iVertexSize * m_iVertCount; // Alloc the VertData... LT_MEM_TRACK_ALLOC(m_pVertData[i] = new uint8[iSize],LT_MEM_TYPE_RENDERER); File.Read(m_pVertData[i],iSize); } // Read in pIndexList... LT_MEM_TRACK_ALLOC(m_pIndexData = new uint8[sizeof(uint16) * m_iPolyCount * 3],LT_MEM_TYPE_RENDERER); File.Read(m_pIndexData,sizeof(uint16) * m_iPolyCount * 3); // Create the VBs and stuff... ReCreateObject(); return true; } // Create the VBs and stuff from our sys mem copies... //void CD3DSkelMesh::ReCreateObject() //{ // // Create our VB... // for (uint32 i=0;i<4;++i) // { // if (!m_VertStreamFlags[i]) // continue; // // if (!m_VBController.CreateStream(i, m_iVertCount, m_VertStreamFlags[i], m_VertType, false, true, m_bSWVertProcessing)) // { // FreeAll(); // return; // } // } // // if (!m_VBController.CreateIndexBuffer(m_iPolyCount*3,false,true,m_bSWVertProcessing)) // { // FreeAll(); // return; // } // // // Read in our Verts... // for (i=0;i<4;++i) // { // if (!m_VertStreamFlags[i]) // continue; // // m_VBController.Lock((VertexBufferController::VB_TYPE)(VertexBufferController::eVERTSTREAM0 + i),false); // // uint8* pVertData = (uint8*)m_VBController.getVertexData(i); // uint32 iSize = m_VBController.getVertexSize(i) * m_iVertCount; // memcpy(pVertData,m_pVertData[i],iSize); // // m_VBController.UnLock((VertexBufferController::VB_TYPE)(VertexBufferController::eVERTSTREAM0 + i)); // } // // // Read in pIndexList... // m_VBController.Lock(VertexBufferController::eINDEX,false); // memcpy(m_VBController.getIndexData(),m_pIndexData,sizeof(uint16) * m_iPolyCount * 3); // m_VBController.UnLock(VertexBufferController::eINDEX); //} // We're loosing focus, free the stuff... //void CD3DSkelMesh::FreeDeviceObjects() //{ // m_VBController.FreeAll(); // Free our VB... //} //inline int32 CD3DSkelMesh::SetTransformsToBoneSet(BoneSetListItem* pBoneSet,D3DMATRIX* pTransforms, int32 nNumMatrices) //{ // for (int32 iCurrBone=0; iCurrBone < 4; ++iCurrBone) // { // if (pBoneSet->BoneSetArray[iCurrBone] == 0xFF) // { // /* // D3DXMATRIX mMat; // //D3DXMatrixIdentity(&mMat); // ZeroMemory(&mMat, sizeof(D3DXMATRIX)); // g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(iCurrBone),&mMat); // continue; // */ // // break; // } // // g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(iCurrBone),&pTransforms[pBoneSet->BoneSetArray[iCurrBone]]); // } // // // // if(nNumMatrices != iCurrBone) // { // if( g_CV_Use0WeightsForDisable ) // { // // ATI requires 0 weights instead of disable // switch (iCurrBone) // { // case 1: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_0WEIGHTS); // break; // case 2: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS); // break; // case 3: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS); // break; // case 4: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS); // break; // default: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE); // ASSERT(0); // break; // } // } // else // { // // but NVIDIA uses disable instead of 0 weights (only on 440MX) // switch (iCurrBone) // { // case 2: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS); // break; // case 3: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS); // break; // case 4: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS); // break; // default: // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE); // break; // } // } // } // // return (iCurrBone-1); //} //inline uint32 CD3DSkelMesh::SetMatrixPalette(uint32 MinBone,uint32 MaxBone,D3DMATRIX* pTransforms) //{ // for (uint32 i=MinBone;i<=MaxBone;++i) // { // if (m_bReIndexedBones) // { // g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(i),&pTransforms[m_pReIndexedBoneList[i]]); // } // else // { // g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(i),&pTransforms[i]); // } // } // // switch (m_iMaxBonesPerVert) // { // case 2 : // { // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS); // break; // } // case 3 : // { // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS); // break; // } // case 4 : // { // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS); // break; // } // default: // { // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE); // } // } // // return (MaxBone-MinBone); //} // THIS Function should be removed when we go to the full render object implementation - it's // temporary on the path to full render objects. The D3D pipe render model path call this guy to do // the transform and lighting stuff. //void CD3DSkelMesh::Render(ModelInstance *pInstance, D3DMATRIX* pD3DTransforms, CD3DRenderStyle* pRenderStyle, uint32 iRenderPass) //{ // switch (m_eRenderMethod) // { // case eD3DRenderDirect : // { // We need to do the bone walk, but we can render direct (they've been pre-processed into triangle group/bone group order)... // uint32 iCurrentPolyIndex = 0; // int32 nNumActiveBones = -1; // for( int32 iBoneSet = 0; (iBoneSet < (int32)m_iBoneSetCount) ; ++iBoneSet ) // { // BoneSetListItem* pBoneSet = &m_pBoneSetArray[iBoneSet]; // nNumActiveBones = SetTransformsToBoneSet(pBoneSet,pD3DTransforms, nNumActiveBones); // // // Set the vertex shader constants. // if (m_pVertexShader != NULL) // { // // Let the client set some constants. // if (NULL != i_client_shell) // { // i_client_shell->OnVertexShaderSetConstants(m_pVertexShader, iRenderPass, pRenderStyle, pInstance, // LTShaderDeviceStateImp::GetSingleton()); // } // // // Send the constants to the video card. // LTVertexShaderMgr::GetSingleton().SetVertexShaderConstants(m_pVertexShader); // } // // // Set the pixel shader constants. // if (m_pPixelShader != NULL) // { // // Let the client set some constants. // if (NULL != i_client_shell) // { // i_client_shell->OnPixelShaderSetConstants(m_pPixelShader, iRenderPass, pRenderStyle, pInstance, // LTShaderDeviceStateImp::GetSingleton()); // } // // // Send the constants to the video card. // LTPixelShaderMgr::GetSingleton().SetPixelShaderConstants(m_pPixelShader); // } // // RSD3DOptions rsD3DOptions; // pRenderStyle->GetDirect3D_Options(&rsD3DOptions); // if(rsD3DOptions.bUseEffectShader) // { // LTEffectImpl* _pEffect = (LTEffectImpl*)LTEffectShaderMgr::GetSingleton().GetEffectShader(rsD3DOptions.EffectShaderID); // ID3DXEffect* pEffect = _pEffect->GetEffect(); // // if(pEffect) // { // i_client_shell->OnEffectShaderSetParams((LTEffectShader*)_pEffect, pRenderStyle, pInstance, LTShaderDeviceStateImp::GetSingleton()); // pEffect->SetInt("BoneCount", nNumActiveBones); // pEffect->CommitChanges(); // } // // } // // m_VBController.Render( pBoneSet->iFirstVertIndex, // iCurrentPolyIndex, // pBoneSet->iVertCount, // (pBoneSet->iIndexIntoIndexBuff - iCurrentPolyIndex)/3); // // // // iCurrentPolyIndex = pBoneSet->iIndexIntoIndexBuff; // // IncFrameStat(eFS_ModelRender_NumSkeletalRenderObjects, 1); // } // // break; // } // case eD3DRenderMatrixPalettes : // { // uint32 nNumActiveBones = SetMatrixPalette(m_iMinBone,m_iMaxBone,pD3DTransforms); // // // Set the vertex shader constants. // if (m_pVertexShader != NULL) // { // // Let the client set some constants. // if (NULL != i_client_shell) // { // i_client_shell->OnVertexShaderSetConstants(m_pVertexShader, iRenderPass, pRenderStyle, pInstance, // LTShaderDeviceStateImp::GetSingleton()); // } // // // Send the constants to the video card. // LTVertexShaderMgr::GetSingleton().SetVertexShaderConstants(m_pVertexShader); // } // // // Set the pixel shader constants. // if (m_pPixelShader != NULL) // { // // Let the client set some constants. // if (NULL != i_client_shell) // { // i_client_shell->OnPixelShaderSetConstants(m_pPixelShader, iRenderPass, pRenderStyle, pInstance, // LTShaderDeviceStateImp::GetSingleton()); // } // // // Send the constants to the video card. // LTPixelShaderMgr::GetSingleton().SetPixelShaderConstants(m_pPixelShader); // } // // RSD3DOptions rsD3DOptions; // pRenderStyle->GetDirect3D_Options(&rsD3DOptions); // if(rsD3DOptions.bUseEffectShader) // { // LTEffectImpl* _pEffect = (LTEffectImpl*)LTEffectShaderMgr::GetSingleton().GetEffectShader(rsD3DOptions.EffectShaderID); // ID3DXEffect* pEffect = _pEffect->GetEffect(); // // if(pEffect) // { // i_client_shell->OnEffectShaderSetParams((LTEffectShader*)_pEffect, pRenderStyle, pInstance, LTShaderDeviceStateImp::GetSingleton()); // pEffect->SetInt("BoneCount", nNumActiveBones); // pEffect->CommitChanges(); // } // // } // // m_VBController.Render(0,0,m_iVertCount,m_iPolyCount); // // break; // } // } //} //void CD3DSkelMesh::BeginRender(D3DMATRIX* pD3DTransforms, CD3DRenderStyle* pRenderStyle, uint32 iRenderPass) //{ // //// [dlj] remove this because DX9 doesn't have this bug // // // DX8 has bug with table fog with blended meshes... //// PD3DDEVICE->GetRenderState(D3DRS_FOGTABLEMODE, &m_nPrevFogTableMode); //// PD3DDEVICE->SetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_NONE); //// PD3DDEVICE->GetRenderState(D3DRS_FOGVERTEXMODE, &m_nPrevFogVertexMode); //// PD3DDEVICE->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR); // // // Do we need to do software vert processing... // bool bSoftwareProcessing = m_bSWVertProcessing; // // // Check if we need to do software processing... // switch (m_eRenderMethod) // { // case eD3DRenderDirect : // if (m_iMaxBonesPerTri > g_Device.GetDeviceCaps()->MaxVertexBlendMatrices) // { // bSoftwareProcessing = true; // } // break; // case eD3DRenderMatrixPalettes : // // Note: I am multiplying by two because the spec sais, if you're doing normals as well, it's half of the cap sais... // if ((m_iMaxBone-m_iMinBone)*2+1 > g_Device.GetDeviceCaps()->MaxVertexBlendMatrixIndex) // { // bSoftwareProcessing = true; // } // break; // } // // // If not already software vertex processing then set // if (!m_bSWVertProcessing && bSoftwareProcessing) // { // m_bSWVertProcessing = true; // FreeDeviceObjects(); // ReCreateObject(); // } // // // // If this pass has a vertex shader, use it. // RSD3DRenderPass *pPass = pRenderStyle->GetRenderPass_D3DOptions(iRenderPass); // if (NULL != pPass && // pPass->bUseVertexShader && // pPass->VertexShaderID != LTVertexShader::VERTEXSHADER_INVALID) // { // if ( m_bSWVSBuffers && !m_bSWVertProcessing ) // { // m_bSWVertProcessing = true; // FreeDeviceObjects(); // ReCreateObject(); // } // // // Store the pointer to the actual shader during rendering. // m_pVertexShader = LTVertexShaderMgr::GetSingleton().GetVertexShader(pPass->VertexShaderID); // if (m_pVertexShader != NULL) // { // // Install the shader. // if (!LTVertexShaderMgr::GetSingleton().InstallVertexShader(m_pVertexShader)) // { // m_pVertexShader = NULL; // return; // } // } // } // else if (!m_VBController.getVertexFormat(0) || m_bNonFixPipeData) // { // // RSD3DOptions rsD3DOptions; // pRenderStyle->GetDirect3D_Options(&rsD3DOptions); // if(!rsD3DOptions.bUseEffectShader) // { // return; // This is a non fixed function pipe VB - bail out... // } // // //return; // This is a non fixed function pipe VB - bail out... // } // else if (FAILED(g_RenderStateMgr.SetVertexShader(m_VBController.getVertexFormat(0)))) // { // return; // } // // // If this pass has a pixel shader, use it. // if (NULL != pPass && // pPass->bUsePixelShader && // pPass->PixelShaderID != LTPixelShader::PIXELSHADER_INVALID) // { // // Store the pointer to the actual shader during rendering. // m_pPixelShader = LTPixelShaderMgr::GetSingleton().GetPixelShader(pPass->PixelShaderID); // if (m_pPixelShader != NULL) // { // // Install the shader. // if (!LTPixelShaderMgr::GetSingleton().InstallPixelShader(m_pPixelShader)) // { // m_pPixelShader = NULL; // return; // } // } // } // // // // We need software processing // if(m_bSWVertProcessing) // { // PD3DDEVICE->SetSoftwareVertexProcessing(TRUE); // } // // // m_VBController.SetStreamSources(); // // if(m_eRenderMethod == eD3DRenderMatrixPalettes) // { // PD3DDEVICE->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE); // } //} //void CD3DSkelMesh::EndRender() //{ // if(m_eRenderMethod == eD3DRenderMatrixPalettes) // { // PD3DDEVICE->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE); // } // // if ( m_bSWVertProcessing ) // { // // If we are running with hardware then turn back on hardware processing // if ( (g_Device.GetDeviceCaps()->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) ) // { // // PD3DDEVICE->SetSoftwareVertexProcessing(FALSE); // } // } // // PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE); // //// [dlj] remove this because DX9 doesn't have this bug //// PD3DDEVICE->SetRenderState(D3DRS_FOGTABLEMODE, m_nPrevFogTableMode); //// PD3DDEVICE->SetRenderState(D3DRS_FOGVERTEXMODE, m_nPrevFogVertexMode); // // PD3DDEVICE->SetStreamSource(0, 0, 0, 0); // PD3DDEVICE->SetIndices(0); // // // Uninstall the vertex shader. // if (NULL != m_pVertexShader) // { // LTVertexShaderMgr::GetSingleton().UninstallVertexShader(); // m_pVertexShader = NULL; // } // // // Uninstall the pixel shader. // if (NULL != m_pPixelShader) // { // LTPixelShaderMgr::GetSingleton().UninstallPixelShader(); // m_pPixelShader = NULL; // } // // //}
28.855228
140
0.684242
crskycode
90d15e73d1e0a054bc627e6d4f321c3c255f2c21
5,224
hpp
C++
master/core/third/libtorrent/include/libtorrent/socket.hpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/libtorrent/include/libtorrent/socket.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/libtorrent/include/libtorrent/socket.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push, 1) #endif // if building as Objective C++, asio's template // parameters Protocol has to be renamed to avoid // colliding with keywords #ifdef __OBJC__ #define Protocol Protocol_ #endif #include <asio/ip/tcp.hpp> #include <asio/ip/udp.hpp> #include <asio/io_service.hpp> #include <asio/deadline_timer.hpp> #include <asio/write.hpp> #include <asio/strand.hpp> #include <asio/time_traits.hpp> #include <asio/basic_deadline_timer.hpp> #ifdef __OBJC__ #undef Protocol #endif #include "libtorrent/io.hpp" #include "libtorrent/time.hpp" #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { /* namespace asio = boost::asio; using boost::asio::ipv4::tcp; using boost::asio::ipv4::address; using boost::asio::stream_socket; using boost::asio::datagram_socket; using boost::asio::socket_acceptor; using boost::asio::io_service; using boost::asio::ipv4::host_resolver; using boost::asio::async_write; using boost::asio::ipv4::host; using boost::asio::deadline_timer; */ // namespace asio = ::asio; using asio::ip::tcp; using asio::ip::udp; typedef asio::ip::tcp::socket stream_socket; typedef asio::ip::address address; typedef asio::ip::address_v4 address_v4; typedef asio::ip::address_v6 address_v6; typedef asio::ip::udp::socket datagram_socket; typedef asio::ip::tcp::acceptor socket_acceptor; typedef asio::io_service io_service; using asio::async_write; using asio::error_code; typedef asio::basic_deadline_timer<libtorrent::ptime> deadline_timer; inline std::ostream& print_endpoint(std::ostream& os, tcp::endpoint const& ep) { address const& addr = ep.address(); asio::error_code ec; std::string a = addr.to_string(ec); if (ec) return os; if (addr.is_v6()) os << "[" << a << "]:"; else os << a << ":"; os << ep.port(); return os; } namespace detail { template<class OutIt> void write_address(address const& a, OutIt& out) { if (a.is_v4()) { write_uint32(a.to_v4().to_ulong(), out); } else if (a.is_v6()) { asio::ip::address_v6::bytes_type bytes = a.to_v6().to_bytes(); std::copy(bytes.begin(), bytes.end(), out); } } template<class InIt> address read_v4_address(InIt& in) { unsigned long ip = read_uint32(in); return asio::ip::address_v4(ip); } template<class InIt> address read_v6_address(InIt& in) { typedef asio::ip::address_v6::bytes_type bytes_t; bytes_t bytes; for (bytes_t::iterator i = bytes.begin() , end(bytes.end()); i != end; ++i) *i = read_uint8(in); return asio::ip::address_v6(bytes); } template<class Endpoint, class OutIt> void write_endpoint(Endpoint const& e, OutIt& out) { write_address(e.address(), out); write_uint16(e.port(), out); } template<class Endpoint, class InIt> Endpoint read_v4_endpoint(InIt& in) { address addr = read_v4_address(in); int port = read_uint16(in); return Endpoint(addr, port); } template<class Endpoint, class InIt> Endpoint read_v6_endpoint(InIt& in) { address addr = read_v6_address(in); int port = read_uint16(in); return Endpoint(addr, port); } } struct v6only { v6only(bool enable): m_value(enable) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IPV6; } template<class Protocol> int name(Protocol const&) const { return IPV6_V6ONLY; } template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; } #endif // TORRENT_SOCKET_HPP_INCLUDED
26.927835
79
0.723966
importlib
90d288af6571d1f98c014630d861f60ffb33678a
11,628
cc
C++
pyxel/core/src/pyxelcore.cc
nnn1590/pyxel
fa1c5748f1e76d137fe157619584eadfbe0d45e7
[ "MIT" ]
null
null
null
pyxel/core/src/pyxelcore.cc
nnn1590/pyxel
fa1c5748f1e76d137fe157619584eadfbe0d45e7
[ "MIT" ]
null
null
null
pyxel/core/src/pyxelcore.cc
nnn1590/pyxel
fa1c5748f1e76d137fe157619584eadfbe0d45e7
[ "MIT" ]
null
null
null
#include "pyxelcore.h" #include "pyxelcore/audio.h" #include "pyxelcore/graphics.h" #include "pyxelcore/image.h" #include "pyxelcore/input.h" #include "pyxelcore/music.h" #include "pyxelcore/resource.h" #include "pyxelcore/sound.h" #include "pyxelcore/system.h" #include "pyxelcore/tilemap.h" #define IMAGE reinterpret_cast<pyxelcore::Image*>(self) #define TILEMAP reinterpret_cast<pyxelcore::Tilemap*>(self) #define SOUND reinterpret_cast<pyxelcore::Sound*>(self) #define MUSIC reinterpret_cast<pyxelcore::Music*>(self) static pyxelcore::System* s_system = NULL; static pyxelcore::Resource* s_resource = NULL; static pyxelcore::Input* s_input = NULL; static pyxelcore::Graphics* s_graphics = NULL; static pyxelcore::Audio* s_audio = NULL; // // Constants // int32_t _get_constant_number(const char* name) { return pyxelcore::GetConstantNumber(name); } void _get_constant_string(char* str, int32_t str_length, const char* name) { strncpy(str, pyxelcore::GetConstantString(name).c_str(), str_length); } // // System // int32_t width_getter() { return s_system->Width(); } int32_t height_getter() { return s_system->Height(); } int32_t frame_count_getter() { return s_system->FrameCount(); } void init(int32_t width, int32_t height, const char* caption, int32_t scale, const int32_t* palette, int32_t fps, int32_t border_width, int32_t border_color) { std::array<int32_t, pyxelcore::COLOR_COUNT> palette_color; for (int32_t i = 0; i < pyxelcore::COLOR_COUNT; i++) { palette_color[i] = palette[i]; } s_system = new pyxelcore::System(width, height, std::string(caption), scale, palette_color, fps, border_width, border_color); s_resource = s_system->Resource(); s_input = s_system->Input(); s_graphics = s_system->Graphics(); s_audio = s_system->Audio(); } void run(void (*update)(), void (*draw)()) { s_system->Run(update, draw); } void quit() { s_system->Quit(); } void flip() { s_system->FlipScreen(); } void show() { s_system->ShowScreen(); } void _drop_file_getter(char* str, int32_t str_length) { strncpy(str, s_system->DropFile().c_str(), str_length); } void _caption(const char* caption) { s_system->SetCaption(caption); } // // Resource // void save(const char* filename) { s_resource->SaveAsset(filename); } void load(const char* filename) { s_resource->LoadAsset(filename); } // // Input // int32_t mouse_x_getter() { return s_input->MouseX(); } int32_t mouse_y_getter() { return s_input->MouseY(); } int32_t btn(int32_t key) { return s_input->IsButtonOn(key); } int32_t btnp(int32_t key, int32_t hold, int32_t period) { return s_input->IsButtonPressed(key, hold, period); } int32_t btnr(int32_t key) { return s_input->IsButtonReleased(key); } void mouse(int32_t visible) { return s_input->SetMouseVisible(visible); } // // Graphics // void* image(int32_t img, int32_t system) { return s_graphics->GetImageBank(img, system); } void* tilemap(int32_t tm) { return s_graphics->GetTilemapBank(tm); } void clip0() { s_graphics->ResetClipArea(); } void clip(int32_t x, int32_t y, int32_t w, int32_t h) { s_graphics->SetClipArea(x, y, w, h); } void pal0() { s_graphics->ResetPalette(); } void pal(int32_t col1, int32_t col2) { s_graphics->SetPalette(col1, col2); } void cls(int32_t col) { s_graphics->ClearScreen(col); } void pix(int32_t x, int32_t y, int32_t col) { s_graphics->DrawPoint(x, y, col); } void line(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t col) { s_graphics->DrawLine(x1, y1, x2, y2, col); } void rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t col) { s_graphics->DrawRectangle(x, y, w, h, col); } void rectb(int32_t x, int32_t y, int32_t w, int32_t h, int32_t col) { s_graphics->DrawRectangleBorder(x, y, w, h, col); } void circ(int32_t x, int32_t y, int32_t r, int32_t col) { s_graphics->DrawCircle(x, y, r, col); } void circb(int32_t x, int32_t y, int32_t r, int32_t col) { s_graphics->DrawCircleBorder(x, y, r, col); } void blt(int32_t x, int32_t y, int32_t img, int32_t u, int32_t v, int32_t w, int32_t h, int32_t colkey) { s_graphics->DrawImage(x, y, img, u, v, w, h, colkey); } void bltm(int32_t x, int32_t y, int32_t tm, int32_t u, int32_t v, int32_t w, int32_t h, int32_t colkey) { s_graphics->DrawTilemap(x, y, tm, u, v, w, h, colkey); } void text(int32_t x, int32_t y, const char* s, int32_t col) { s_graphics->DrawText(x, y, s, col); } // // Audio // void* sound(int32_t snd, int32_t system) { return s_audio->GetSoundBank(snd, system); } void* music(int32_t msc) { return s_audio->GetMusicBank(msc); } int32_t play_pos(int32_t ch) { return s_audio->GetPlayPos(ch); } void play1(int32_t ch, int32_t snd, int32_t loop) { s_audio->PlaySound(ch, snd, loop); } void play(int32_t ch, int32_t* snd, int32_t snd_length, int32_t loop) { pyxelcore::SoundIndexList sound_index_list; for (int32_t i = 0; i < snd_length; i++) { sound_index_list.push_back(snd[i]); } s_audio->PlaySound(ch, sound_index_list, loop); } void playm(int32_t msc, int32_t loop) { s_audio->PlayMusic(msc, loop); } void stop(int32_t ch) { s_audio->StopPlaying(ch); } // // Image class // int32_t image_width_getter(void* self) { return IMAGE->Width(); } int32_t image_height_getter(void* self) { return IMAGE->Height(); } int32_t** image_data_getter(void* self) { return IMAGE->Data(); } int32_t image_get(void* self, int32_t x, int32_t y) { return IMAGE->GetValue(x, y); } void image_set1(void* self, int32_t x, int32_t y, int32_t data) { IMAGE->SetValue(x, y, data); } void image_set(void* self, int32_t x, int32_t y, const char** data, int32_t data_length) { pyxelcore::ImageString image_string; for (int32_t i = 0; i < data_length; i++) { image_string.push_back(data[i]); } IMAGE->SetData(x, y, image_string); } void image_load(void* self, int32_t x, int32_t y, const char* filename) { IMAGE->LoadImage(x, y, filename, s_system->PaletteColor()); } void image_copy(void* self, int32_t x, int32_t y, int32_t img, int32_t u, int32_t v, int32_t w, int32_t h) { IMAGE->CopyImage(x, y, s_graphics->GetImageBank(img, true), u, v, w, h); } // // Tilemap class // int32_t tilemap_width_getter(void* self) { return TILEMAP->Width(); } int32_t tilemap_height_getter(void* self) { return TILEMAP->Height(); } int32_t** tilemap_data_getter(void* self) { return TILEMAP->Data(); } int32_t tilemap_refimg_getter(void* self) { return TILEMAP->ImageIndex(); } void tilemap_refimg_setter(void* self, int32_t refimg) { TILEMAP->ImageIndex(refimg); } int32_t tilemap_get(void* self, int32_t x, int32_t y) { return TILEMAP->GetValue(x, y); } void tilemap_set1(void* self, int32_t x, int32_t y, int32_t data) { TILEMAP->SetValue(x, y, data); } void tilemap_set(void* self, int32_t x, int32_t y, const char** data, int32_t data_length) { pyxelcore::TilemapString tilemap_string; for (int32_t i = 0; i < data_length; i++) { tilemap_string.push_back(data[i]); } TILEMAP->SetData(x, y, tilemap_string); } void tilemap_copy(void* self, int32_t x, int32_t y, int32_t tm, int32_t u, int32_t v, int32_t w, int32_t h) { return TILEMAP->CopyTilemap(x, y, s_graphics->GetTilemapBank(tm), u, v, w, h); } // // Sound class // int32_t* sound_note_getter(void* self) { return SOUND->Note().data(); } int32_t sound_note_length_getter(void* self) { return SOUND->Note().size(); } void sound_note_length_setter(void* self, int32_t length) { SOUND->Note().resize(length); } int32_t* sound_tone_getter(void* self) { return SOUND->Tone().data(); } int32_t sound_tone_length_getter(void* self) { return SOUND->Tone().size(); } void sound_tone_length_setter(void* self, int32_t length) { SOUND->Tone().resize(length); } int32_t* sound_volume_getter(void* self) { return SOUND->Volume().data(); } int32_t sound_volume_length_getter(void* self) { return SOUND->Volume().size(); } void sound_volume_length_setter(void* self, int32_t length) { SOUND->Volume().resize(length); } int32_t* sound_effect_getter(void* self) { return SOUND->Effect().data(); } int32_t sound_effect_length_getter(void* self) { return SOUND->Effect().size(); } void sound_effect_length_setter(void* self, int32_t length) { SOUND->Effect().resize(length); } int32_t sound_speed_getter(void* self) { return SOUND->Speed(); } void sound_speed_setter(void* self, int32_t speed) { SOUND->Speed(speed); } void sound_set(void* self, const char* note, const char* tone, const char* volume, const char* effect, int32_t speed) { SOUND->Set(note, tone, volume, effect, speed); } void sound_set_note(void* self, const char* note) { SOUND->SetNote(note); } void sound_set_tone(void* self, const char* tone) { SOUND->SetTone(tone); } void sound_set_volume(void* self, const char* volume) { SOUND->SetVolume(volume); } void sound_set_effect(void* self, const char* effect) { SOUND->SetEffect(effect); } // // Music class // int32_t* music_ch0_getter(void* self) { return MUSIC->Channel0().data(); } int32_t music_ch0_length_getter(void* self) { return MUSIC->Channel0().size(); } void music_ch0_length_setter(void* self, int32_t length) { MUSIC->Channel0().resize(length); } int32_t* music_ch1_getter(void* self) { return MUSIC->Channel1().data(); } int32_t music_ch1_length_getter(void* self) { return MUSIC->Channel1().size(); } void music_ch1_length_setter(void* self, int32_t length) { MUSIC->Channel1().resize(length); } int32_t* music_ch2_getter(void* self) { return MUSIC->Channel2().data(); } int32_t music_ch2_length_getter(void* self) { return MUSIC->Channel2().size(); } void music_ch2_length_setter(void* self, int32_t length) { MUSIC->Channel2().resize(length); } int32_t* music_ch3_getter(void* self) { return MUSIC->Channel3().data(); } int32_t music_ch3_length_getter(void* self) { return MUSIC->Channel3().size(); } void music_ch3_length_setter(void* self, int32_t length) { MUSIC->Channel3().resize(length); } void music_set(void* self, const int32_t* ch0, int32_t ch0_length, const int32_t* ch1, int32_t ch1_length, const int32_t* ch2, int32_t ch2_length, const int32_t* ch3, int32_t ch3_length) { pyxelcore::SoundIndexList sound_index_list0; for (int32_t i = 0; i < ch0_length; i++) { sound_index_list0.push_back(ch0[i]); } pyxelcore::SoundIndexList sound_index_list1; for (int32_t i = 0; i < ch1_length; i++) { sound_index_list1.push_back(ch1[i]); } pyxelcore::SoundIndexList sound_index_list2; for (int32_t i = 0; i < ch2_length; i++) { sound_index_list2.push_back(ch2[i]); } pyxelcore::SoundIndexList sound_index_list3; for (int32_t i = 0; i < ch3_length; i++) { sound_index_list3.push_back(ch3[i]); } MUSIC->Set(sound_index_list0, sound_index_list1, sound_index_list2, sound_index_list3); }
22.19084
80
0.659013
nnn1590
90d37359d2d67674cff2dfbcec9d4f03602ef5e4
4,278
cpp
C++
SDKs/CryCode/3.8.1/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
#include "stdafx.h" #include "EntityAttributesProxy.h" #include "Serialization/IArchive.h" #include "Serialization/IArchiveHost.h" namespace { struct SEntityAttributesSerializer { SEntityAttributesSerializer(TEntityAttributeArray& _attributes) : attributes(_attributes) {} void Serialize(Serialization::IArchive& archive) { for(size_t iAttribute = 0, attributeCount = attributes.size(); iAttribute < attributeCount; ++ iAttribute) { IEntityAttribute* pAttribute = attributes[iAttribute].get(); if(pAttribute != NULL) { archive(*pAttribute, pAttribute->GetName(), pAttribute->GetLabel()); } } } TEntityAttributeArray& attributes; }; } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::ProcessEvent(SEntityEvent& event) {} ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Initialize(SComponentInitializer const& inititializer) {} ////////////////////////////////////////////////////////////////////////// EEntityProxy CEntityAttributesProxy::GetType() { return ENTITY_PROXY_ATTRIBUTES; } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Release() { delete this; } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Done() {} ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Update(SEntityUpdateContext& context) {} ////////////////////////////////////////////////////////////////////////// bool CEntityAttributesProxy::Init(IEntity* pEntity, SEntitySpawnParams& params) { if(m_attributes.empty() == true) { EntityAttributeUtils::CloneAttributes(params.pClass->GetEntityAttributes(), m_attributes); } return true; } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Reload(IEntity* pEntity, SEntitySpawnParams& params) {} ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::SerializeXML(XmlNodeRef &entityNodeXML, bool loading) { if(loading == true) { if(XmlNodeRef attributesNodeXML = entityNodeXML->findChild("Attributes")) { SEntityAttributesSerializer serializer(m_attributes); Serialization::LoadXmlNode(serializer, attributesNodeXML); } } else { if(!m_attributes.empty()) { SEntityAttributesSerializer serializer(m_attributes); if(XmlNodeRef attributesNodeXML = Serialization::SaveXmlNode(serializer, "Attributes")) { entityNodeXML->addChild(attributesNodeXML); } } } } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::Serialize(TSerialize serialize) {} ////////////////////////////////////////////////////////////////////////// bool CEntityAttributesProxy::NeedSerialize() { return false; } ////////////////////////////////////////////////////////////////////////// bool CEntityAttributesProxy::GetSignature(TSerialize signature) { return true; } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::GetMemoryUsage(ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); } ////////////////////////////////////////////////////////////////////////// void CEntityAttributesProxy::SetAttributes(const TEntityAttributeArray& attributes) { const size_t attributeCount = attributes.size(); m_attributes.resize(attributeCount); for(size_t iAttribute = 0; iAttribute < attributeCount; ++ iAttribute) { IEntityAttribute* pSrc = attributes[iAttribute].get(); IEntityAttribute* pDst = m_attributes[iAttribute].get(); if((pDst != NULL) && (strcmp(pSrc->GetName(), pDst->GetName()) == 0)) { Serialization::CloneBinary(*pDst, *pSrc); } else if(pSrc != NULL) { m_attributes[iAttribute] = pSrc->Clone(); } } } ////////////////////////////////////////////////////////////////////////// TEntityAttributeArray& CEntityAttributesProxy::GetAttributes() { return m_attributes; } ////////////////////////////////////////////////////////////////////////// const TEntityAttributeArray& CEntityAttributesProxy::GetAttributes() const { return m_attributes; }
29.708333
109
0.544647
amrhead
90d49e3ae32010fb49ec8e2a8d41b7d434131e69
30,420
cp
C++
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright (c) 2007 Cyrus Daboo. 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. */ // Source for CSearchCriteriaLocal class #include "CSearchCriteriaLocal.h" #include "CDateControl.h" #include "CFilterItem.h" #include "CMulberryCommon.h" #include "CPreferences.h" #include "CRFC822.h" #include "CSearchCriteriaContainer.h" #include "CSearchStyle.h" #include "CTextFieldX.h" #include <LPopupButton.h> // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // Menu items enum { eCriteria_From = 1, eCriteria_To, eCriteria_CC, eCriteria_Bcc, eCriteria_Recipient, eCriteria_Correspondent, eCriteria_Sender, eCriteria_DateSent, eCriteria_DateReceived, eCriteria_Subject, eCriteria_Body, eCriteria_Header, eCriteria_Text, eCriteria_Size, eCriteria_Separator1, eCriteria_Recent, eCriteria_Seen, eCriteria_Answered, eCriteria_Flagged, eCriteria_Deleted, eCriteria_Draft, eCriteria_Separator2, eCriteria_Label1, eCriteria_Label2, eCriteria_Label3, eCriteria_Label4, eCriteria_Label5, eCriteria_Label6, eCriteria_Label7, eCriteria_Label8, eCriteria_Separator3, eCriteria_Group, eCriteria_Separator4, eCriteria_SearchSet, eCriteria_Separator5, eCriteria_All, eCriteria_Selected }; enum { eAddressMethod_Contains = 1, eAddressMethod_NotContains, eAddressMethod_IsMe, eAddressMethod_IsNotMe }; enum { eDateMethod_Before = 1, eDateMethod_On, eDateMethod_After, eDateMethod_Separator1, eDateMethod_Is, eDateMethod_IsNot, eDateMethod_IsWithin, eDateMethod_IsNotWithin }; enum { eDateRelMethod_SentToday = 1, eDateRelMethod_SentYesterday, eDateRelMethod_SentWeek, eDateRelMethod_Sent7Days, eDateRelMethod_SentMonth, eDateRelMethod_SentYear }; enum { eDateWithin_Days = 1, eDateWithin_Weeks, eDateWithin_Months, eDateWithin_Years }; enum { eTextMethod_Contains = 1, eTextMethod_NotContains }; enum { eSizeMethod_Larger = 1, eSizeMethod_Smaller }; enum { eFlagMethod_Set = 1, eFlagMethod_NotSet }; enum { eSize_Bytes = 1, eSize_KBytes, eSize_MBytes }; enum { eSearchSetMethod_Is = 1, eSearchSetMethod_IsNot }; enum { eMode_Or = 1, eMode_And }; // Default constructor CSearchCriteriaLocal::CSearchCriteriaLocal() { } // Constructor from stream CSearchCriteriaLocal::CSearchCriteriaLocal(LStream *inStream) : CSearchCriteria(inStream) { } // Default destructor CSearchCriteriaLocal::~CSearchCriteriaLocal() { } // O T H E R M E T H O D S ____________________________________________________________________________ // Get details of sub-panes void CSearchCriteriaLocal::FinishCreateSelf(void) { // Do inherited CSearchCriteria::FinishCreateSelf(); // Get controls mPopup1 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup1); mPopup2 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup2); mPopup3 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup3); mPopup4 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup4); mPopup5 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup5); mPopup6 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup6); mPopup7 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup7); mPopup8 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup8); mText1 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText1); mText2 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText2); mText3 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText3); mDate = (CDateControl*) FindPaneByID(paneid_SearchCriteriaDate); InitLabelNames(); // Link controls to this window UReanimator::LinkListenerToBroadcasters(this,this,RidL_CSearchCriteriaLocalBtns); } // Handle buttons void CSearchCriteriaLocal::ListenToMessage( MessageT inMessage, void *ioParam) { switch (inMessage) { case msg_SearchCriteriaPopup1: OnSetCriteria(*(long*) ioParam); break; case msg_SearchCriteriaPopup2: OnSetMethod(*(long*) ioParam); break; default: CSearchCriteria::ListenToMessage(inMessage, ioParam); break; } } void CSearchCriteriaLocal::SetRules(bool rules) { mRules = rules; // Remove select item from popup if not rules if (!mRules) { mPopup1->DeleteMenuItem(eCriteria_Selected); } } bool CSearchCriteriaLocal::DoActivate() { CTextFieldX* activate = NULL; if (mText2->IsVisible()) activate = mText2; else if (mText1->IsVisible()) activate = mText1; else if (mText3->IsVisible()) activate = mText3; if (activate) { activate->GetSuperCommander()->SetLatentSub(activate); LCommander::SwitchTarget(activate); activate->SelectAll(); return true; } else return false; } long CSearchCriteriaLocal::ShowOrAnd(bool show) { if (show) mPopup4->Show(); else mPopup4->Hide(); return 0; } bool CSearchCriteriaLocal::IsOr() const { return (mPopup4->GetValue() == eMode_Or); } void CSearchCriteriaLocal::SetOr(bool use_or) { mPopup4->SetValue(use_or ? eMode_Or : eMode_And); } void CSearchCriteriaLocal::OnSetCriteria(long item1) { // Set popup menu for method and show/hide text field as approriate bool method_refresh = false; switch(item1) { case eCriteria_From: case eCriteria_To: case eCriteria_CC: case eCriteria_Bcc: case eCriteria_Recipient: case eCriteria_Correspondent: case eCriteria_Sender: if (mPopup2->GetMenuID() != MENU_SearchAddressCriteria) { mPopup2->SetMenuID(MENU_SearchAddressCriteria); mPopup2->SetValue(1); } mPopup2->Show(); mPopup2->Refresh(); method_refresh = true; mPopup3->Hide(); mText1->Show(); mText2->Hide(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_DateSent: case eCriteria_DateReceived: if (mPopup2->GetMenuID() != MENU_SearchDateCriteria) { mPopup2->SetMenuID(MENU_SearchDateCriteria); mPopup2->SetValue(1); } mPopup2->Show(); mPopup2->Refresh(); method_refresh = true; mPopup3->Hide(); mText1->Hide(); mText2->Hide(); mText3->Hide(); mDate->Show(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_Subject: case eCriteria_Body: case eCriteria_Text: if (mPopup2->GetMenuID() != MENU_SearchTestCriteria) { mPopup2->SetMenuID(MENU_SearchTestCriteria); mPopup2->SetValue(1); } mPopup2->Show(); mPopup2->Refresh(); method_refresh = true; mPopup3->Hide(); mText1->Show(); mText2->Hide(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_Header: mText2->SetText(cdstring::null_str); mPopup2->Hide(); mPopup3->Hide(); mText1->Show(); mText2->Show(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_Size: if (mPopup2->GetMenuID() != MENU_SearchSizeCriteria) { mPopup2->SetMenuID(MENU_SearchSizeCriteria); mPopup2->SetValue(1); } mPopup2->Show(); mPopup2->Refresh(); method_refresh = true; mPopup3->Show(); mText1->Hide(); mText2->Hide(); mText3->Show(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_Recent: case eCriteria_Seen: case eCriteria_Answered: case eCriteria_Flagged: case eCriteria_Deleted: case eCriteria_Draft: case eCriteria_Label1: case eCriteria_Label2: case eCriteria_Label3: case eCriteria_Label4: case eCriteria_Label5: case eCriteria_Label6: case eCriteria_Label7: case eCriteria_Label8: if (mPopup2->GetMenuID() != MENU_SearchFlagCriteria) { mPopup2->SetMenuID(MENU_SearchFlagCriteria); mPopup2->SetValue(1); } mText1->SetText(cdstring::null_str); mPopup2->Show(); mPopup2->Refresh(); method_refresh = true; mPopup3->Hide(); mText1->Hide(); mText2->Hide(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; case eCriteria_SearchSet: mPopup2->Hide(); method_refresh = true; mPopup3->Hide(); mText1->Hide(); mText2->Hide(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); InitSearchSets(); mPopup7->Show(); mPopup8->Show(); break; case eCriteria_Group: case eCriteria_All: case eCriteria_Selected: mPopup2->Hide(); mPopup3->Hide(); mText1->Hide(); mText2->Hide(); mText3->Hide(); mDate->Hide(); mPopup5->Hide(); mPopup6->Hide(); mPopup7->Hide(); mPopup8->Hide(); break; } // Special for group display if (item1 == eCriteria_Group) MakeGroup(CFilterItem::eLocal); else RemoveGroup(); // Refresh method for new criteria if (method_refresh) OnSetMethod(mPopup2->GetValue()); } void CSearchCriteriaLocal::OnSetMethod(long item) { // Show/hide text field as appropriate switch(mPopup1->GetValue()) { case eCriteria_From: case eCriteria_To: case eCriteria_CC: case eCriteria_Bcc: case eCriteria_Recipient: case eCriteria_Correspondent: case eCriteria_Sender: switch(item) { case eAddressMethod_Contains: case eAddressMethod_NotContains: mText1->Show(); break; case eAddressMethod_IsMe: case eAddressMethod_IsNotMe: mText1->Hide(); mText1->SetText(cdstring::null_str); break; } break; case eCriteria_DateSent: case eCriteria_DateReceived: switch(item) { case eDateMethod_Before: case eDateMethod_On: case eDateMethod_After: mText3->Hide(); mDate->Show(); mPopup5->Hide(); mPopup6->Hide(); break; case eDateMethod_Is: case eDateMethod_IsNot: mText3->Hide(); mDate->Hide(); mPopup5->Show(); mPopup6->Hide(); break; case eDateMethod_IsWithin: case eDateMethod_IsNotWithin: mText3->Show(); mDate->Hide(); mPopup5->Hide(); mPopup6->Show(); break; } break; default: break; } } void CSearchCriteriaLocal::InitLabelNames() { // Change name of labels for(short i = eCriteria_Label1; i < eCriteria_Label1 + NMessage::eMaxLabels; i++) { ::SetMenuItemTextUTF8(mPopup1->GetMacMenuH(), i, CPreferences::sPrefs->mLabels.GetValue()[i - eCriteria_Label1]->name); } } void CSearchCriteriaLocal::InitSearchSets() { // Remove any existing items from main menu short num_menu = ::CountMenuItems(mPopup7->GetMacMenuH()); for(short i = 1; i <= num_menu; i++) ::DeleteMenuItem(mPopup7->GetMacMenuH(), 1); short index = 1; for(CSearchStyleList::const_iterator iter = CPreferences::sPrefs->mSearchStyles.GetValue().begin(); iter != CPreferences::sPrefs->mSearchStyles.GetValue().end(); iter++, index++) ::AppendItemToMenu(mPopup7->GetMacMenuH(), index, (*iter)->GetName()); // Force max/min update mPopup7->SetMenuMinMax(); mPopup7->SetValue(1); mPopup7->Draw(NULL); } CSearchItem* CSearchCriteriaLocal::GetSearchItem() const { switch(mPopup1->GetValue()) { case eCriteria_From: return ParseAddress(CSearchItem::eFrom); case eCriteria_To: return ParseAddress(CSearchItem::eTo); case eCriteria_CC: return ParseAddress(CSearchItem::eCC); case eCriteria_Bcc: return ParseAddress(CSearchItem::eBcc); case eCriteria_Recipient: return ParseAddress(CSearchItem::eRecipient); case eCriteria_Correspondent: return ParseAddress(CSearchItem::eCorrespondent); case eCriteria_Sender: return ParseAddress(CSearchItem::eSender); case eCriteria_DateSent: return ParseDate(true); case eCriteria_DateReceived: return ParseDate(false); case eCriteria_Subject: return ParseText(CSearchItem::eSubject); case eCriteria_Body: return ParseText(CSearchItem::eBody); case eCriteria_Text: return ParseText(CSearchItem::eText); case eCriteria_Header: { cdstring text1 = mText1->GetText(); cdstring text2 = mText2->GetText(); text2.trimspace(); // Strip trailing colon from header field if (text2.compare_end(":")) text2[text2.length() - 1] = 0; // Look for '!' at start of header field as negate item if (text2[0UL] == '!') return new CSearchItem(CSearchItem::eNot, new CSearchItem(CSearchItem::eHeader, text2.c_str() + 1, text1)); else return new CSearchItem(CSearchItem::eHeader, text2, text1); } case eCriteria_Size: return ParseSize(); case eCriteria_Recent: return ParseFlag(CSearchItem::eRecent, CSearchItem::eOld); case eCriteria_Seen: return ParseFlag(CSearchItem::eSeen, CSearchItem::eUnseen); case eCriteria_Answered: return ParseFlag(CSearchItem::eAnswered, CSearchItem::eUnanswered); case eCriteria_Flagged: return ParseFlag(CSearchItem::eFlagged, CSearchItem::eUnflagged); case eCriteria_Deleted: return ParseFlag(CSearchItem::eDeleted, CSearchItem::eUndeleted); case eCriteria_Draft: return ParseFlag(CSearchItem::eDraft, CSearchItem::eUndraft); case eCriteria_Label1: case eCriteria_Label2: case eCriteria_Label3: case eCriteria_Label4: case eCriteria_Label5: case eCriteria_Label6: case eCriteria_Label7: case eCriteria_Label8: return ParseLabel(CSearchItem::eLabel, mPopup1->GetValue() - eCriteria_Label1); case eCriteria_SearchSet: { cdstring style = ::GetPopupMenuItemTextUTF8(mPopup7); const CSearchItem* found = CPreferences::sPrefs->mSearchStyles.GetValue().FindStyle(style)->GetSearchItem(); // May need to negate if (mPopup8->GetValue() == eSearchSetMethod_Is) return (found ? new CSearchItem(CSearchItem::eNamedStyle, style) : NULL); else return (found ? new CSearchItem(CSearchItem::eNot, new CSearchItem(CSearchItem::eNamedStyle, style)) : NULL); } case eCriteria_Group: return mGroupItems->ConstructSearch(); case eCriteria_All: return new CSearchItem(CSearchItem::eAll); case eCriteria_Selected: return new CSearchItem(CSearchItem::eSelected); default: return NULL; } } CSearchItem* CSearchCriteriaLocal::ParseAddress(CSearchItem::ESearchType type) const { cdstring text = mText1->GetText(); switch(mPopup2->GetValue()) { case eAddressMethod_Contains: return new CSearchItem(type, text); case eAddressMethod_NotContains: return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, text)); case eAddressMethod_IsMe: return new CSearchItem(type); case eAddressMethod_IsNotMe: return new CSearchItem(CSearchItem::eNot, new CSearchItem(type)); default: return NULL; } } CSearchItem* CSearchCriteriaLocal::ParseDate(bool sent) const { switch(mPopup2->GetValue()) { case eDateMethod_Before: return new CSearchItem(sent ? CSearchItem::eSentBefore : CSearchItem::eBefore, mDate->GetDate()); case eDateMethod_On: return new CSearchItem(sent ? CSearchItem::eSentOn : CSearchItem::eOn, mDate->GetDate()); case eDateMethod_After: return new CSearchItem(sent ? CSearchItem::eSentSince : CSearchItem::eSince, mDate->GetDate()); // Look at relative date popup case eDateMethod_Is: case eDateMethod_IsNot: { bool is = (mPopup2->GetValue() == eDateMethod_Is); // Set up types for different categories CSearchItem::ESearchType typeToday = (sent ? CSearchItem::eSentOn : CSearchItem::eOn); CSearchItem::ESearchType typeOther = (sent ? CSearchItem::eSentSince : CSearchItem::eSince); CSearchItem::ESearchType typeNot = (sent ? CSearchItem::eSentBefore : CSearchItem::eBefore); // Look at menu item chosen switch(mPopup5->GetValue()) { case eDateRelMethod_SentToday: return new CSearchItem(is ? typeToday : typeNot, static_cast<unsigned long>(CSearchItem::eToday)); case eDateRelMethod_SentYesterday: return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eSinceYesterday)); case eDateRelMethod_SentWeek: return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisWeek)); case eDateRelMethod_Sent7Days: return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eWithin7Days)); case eDateRelMethod_SentMonth: return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisMonth)); case eDateRelMethod_SentYear: return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisYear)); default: return NULL; } break; } // Look at relative date popup case eDateMethod_IsWithin: case eDateMethod_IsNotWithin: { bool is = (mPopup2->GetValue() == eDateMethod_IsWithin); // Set up types for different categories CSearchItem::ESearchType typeIs = (sent ? CSearchItem::eSentSince : CSearchItem::eSince); CSearchItem::ESearchType typeIsNot = (sent ? CSearchItem::eSentBefore : CSearchItem::eBefore); // Get numeric value long size = mText3->GetNumber(); unsigned long within = (size > 0) ? size : 1; if (within > 0x0000FFFF) within = 0x0000FFFF; // Look at menu item chosen switch(mPopup6->GetValue()) { case eDateWithin_Days: return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinDays) | within); case eDateWithin_Weeks: return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinWeeks) | within); case eDateWithin_Months: return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinMonths) | within); case eDateWithin_Years: return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinYears) | within); default: return NULL; } break; } default: return NULL; } } CSearchItem* CSearchCriteriaLocal::ParseText(CSearchItem::ESearchType type) const { cdstring text = mText1->GetText(); if (mPopup2->GetValue() == eTextMethod_Contains) return new CSearchItem(type, text); else return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, text)); } CSearchItem* CSearchCriteriaLocal::ParseSize() const { long size = mText3->GetNumber(); switch(mPopup3->GetValue()) { case eSize_Bytes: break; case eSize_KBytes: size *= 1024L; break; case eSize_MBytes: size *= 1024L * 1024L; break; } return new CSearchItem((mPopup2->GetValue() == eSizeMethod_Larger) ? CSearchItem::eLarger : CSearchItem::eSmaller, size); } CSearchItem* CSearchCriteriaLocal::ParseFlag(CSearchItem::ESearchType type1, CSearchItem::ESearchType type2) const { return new CSearchItem((mPopup2->GetValue() == eFlagMethod_Set) ? type1 : type2); } CSearchItem* CSearchCriteriaLocal::ParseLabel(CSearchItem::ESearchType type, unsigned long index) const { if (mPopup2->GetValue() == eFlagMethod_Set) return new CSearchItem(type, index); else return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, index)); } void CSearchCriteriaLocal::SetSearchItem(const CSearchItem* spec, bool negate) { long popup1 = 1; long popup2 = 1; long popup3 = eSize_Bytes; long popup5 = 1; long popup6 = 1; long popup7 = 1; long popup8 = 1; cdstring text1; cdstring text2; cdstring text3; time_t date = ::time(NULL); if (spec) { switch(spec->GetType()) { case CSearchItem::eAll: // - popup1 = eCriteria_All; break; case CSearchItem::eAnd: // CSearchItemList* break; case CSearchItem::eAnswered: // - popup1 = eCriteria_Answered; popup2 = eFlagMethod_Set; break; case CSearchItem::eBcc: // cdstring* popup1 = eCriteria_Bcc; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eBefore: // date popup1 = eCriteria_DateReceived; popup2 = GetDatePopup(spec, eDateMethod_Before, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eBody: // cdstring* popup1 = eCriteria_Body; text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains; break; case CSearchItem::eCC: // cdstring* popup1 = eCriteria_CC; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eDeleted: // - popup1 = eCriteria_Deleted; popup2 = eFlagMethod_Set; break; case CSearchItem::eDraft: // - popup1 = eCriteria_Draft; popup2 = eFlagMethod_Set; break; case CSearchItem::eFlagged: // - popup1 = eCriteria_Flagged; popup2 = eFlagMethod_Set; break; case CSearchItem::eFrom: // cdstring* popup1 = eCriteria_From; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eGroup: // CSearchItemList* popup1 = eCriteria_Group; break; case CSearchItem::eHeader: // cdstrpair* popup1 = eCriteria_Header; if (negate) text2 = "!"; text2 += static_cast<const cdstrpair*>(spec->GetData())->first; text1 = static_cast<const cdstrpair*>(spec->GetData())->second; break; case CSearchItem::eKeyword: // cdstring* break; case CSearchItem::eLabel: // unsigned long { unsigned long index = reinterpret_cast<unsigned long>(spec->GetData()); if (index >= NMessage::eMaxLabels) index = 0; popup1 = eCriteria_Label1 + index; popup2 = negate ? eFlagMethod_NotSet : eFlagMethod_Set; break; } case CSearchItem::eLarger: // long popup1 = eCriteria_Size; popup2 = eSizeMethod_Larger; long size = reinterpret_cast<long>(spec->GetData()); if (size >= 1024L * 1024L) { size /= 1024L * 1024L; popup3 = eSize_MBytes; } else if (size >= 1024L) { size /= 1024L; popup3 = eSize_KBytes; } text3 = size; break; case CSearchItem::eNew: // - break; case CSearchItem::eNot: // CSearchItem* // Do negated - can only be text based items SetSearchItem(static_cast<const CSearchItem*>(spec->GetData()), true); // Must exit now without changing any UI item since they have already been done return; case CSearchItem::eNumber: // ulvector* only - no key break; case CSearchItem::eOld: // - popup1 = eCriteria_Recent; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eOn: // date popup1 = eCriteria_DateReceived; popup2 = GetDatePopup(spec, eDateMethod_On, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eOr: // CSearchItemList* break; case CSearchItem::eRecent: // - popup1 = eCriteria_Recent; popup2 = eFlagMethod_Set; break; case CSearchItem::eSeen: // - popup1 = eCriteria_Seen; popup2 = eFlagMethod_Set; break; case CSearchItem::eSelected: // - popup1 = eCriteria_Selected; break; case CSearchItem::eSentBefore: // date popup1 = eCriteria_DateSent; popup2 = GetDatePopup(spec, eDateMethod_Before, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eSentOn: // date popup1 = eCriteria_DateSent; popup2 = GetDatePopup(spec, eDateMethod_On, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eSentSince: // date popup1 = eCriteria_DateSent; popup2 = GetDatePopup(spec, eDateMethod_After, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eSince: // date popup1 = eCriteria_DateReceived; popup2 = GetDatePopup(spec, eDateMethod_After, text1, text3, popup5, popup6); date = reinterpret_cast<time_t>(spec->GetData()); break; case CSearchItem::eSmaller: // long popup1 = eCriteria_Size; popup2 = eSizeMethod_Smaller; size = reinterpret_cast<long>(spec->GetData()); if (size >= 1024L) { size /= 1024L; popup3 = eSize_KBytes; } else if (size >= 1024L * 1024L) { size /= 1024L * 1024L; popup3 = eSize_MBytes; } text3 = size; break; case CSearchItem::eSubject: // cdstring* popup1 = eCriteria_Subject; text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains; break; case CSearchItem::eText: // cdstring* popup1 = eCriteria_Text; text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains; break; case CSearchItem::eTo: // cdstring* popup1 = eCriteria_To; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eUID: // ulvector* break; case CSearchItem::eUnanswered: // - popup1 = eCriteria_Answered; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eUndeleted: // - popup1 = eCriteria_Deleted; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eUndraft: // - popup1 = eCriteria_Draft; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eUnflagged: // - popup1 = eCriteria_Flagged; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eUnkeyword: // cdstring* break; case CSearchItem::eUnseen: // - popup1 = eCriteria_Seen; popup2 = eFlagMethod_NotSet; break; case CSearchItem::eRecipient: // cdstring* popup1 = eCriteria_Recipient; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eCorrespondent: // cdstring* popup1 = eCriteria_Correspondent; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eSender: // cdstring* popup1 = eCriteria_Sender; if (spec->GetData()) text1 = *static_cast<const cdstring*>(spec->GetData()); popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) : (negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe); break; case CSearchItem::eNamedStyle: // - popup1 = eCriteria_SearchSet; popup7 = CPreferences::sPrefs->mSearchStyles.GetValue().FindIndexOf(*static_cast<const cdstring*>(spec->GetData())) + 1; popup8 = negate ? eSearchSetMethod_IsNot : eSearchSetMethod_Is; break; default:; } } mPopup1->SetValue(popup1); mPopup2->SetValue(popup2); mPopup3->SetValue(popup3); mText1->SetText(text1); mText2->SetText(text2); mText3->SetText(text3); mDate->SetDate(date); mPopup5->SetValue(popup5); mPopup6->SetValue(popup6); mPopup7->SetValue(popup7); mPopup8->SetValue(popup8); // Set group contents if ((spec != NULL) && (spec->GetType() == CSearchItem::eGroup)) mGroupItems->InitGroup(CFilterItem::eLocal, spec); } long CSearchCriteriaLocal::GetDatePopup(const CSearchItem* spec, long original, cdstring& text1, cdstring& text3, long& popup5, long& popup6) const { switch(reinterpret_cast<unsigned long>(spec->GetData())) { // Relative date case CSearchItem::eToday: case CSearchItem::eSinceYesterday: case CSearchItem::eThisWeek: case CSearchItem::eWithin7Days: case CSearchItem::eThisMonth: case CSearchItem::eThisYear: { // Set relative popup switch(reinterpret_cast<unsigned long>(spec->GetData())) { case CSearchItem::eToday: default: popup5 = eDateRelMethod_SentToday; return (original == eDateMethod_On) ? eDateMethod_Is : eDateMethod_IsNot; case CSearchItem::eSinceYesterday: popup5 = eDateRelMethod_SentYesterday; return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot; case CSearchItem::eThisWeek: popup5 = eDateRelMethod_SentWeek; return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot; case CSearchItem::eWithin7Days: popup5 = eDateRelMethod_Sent7Days; return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot; case CSearchItem::eThisMonth: popup5 = eDateRelMethod_SentMonth; return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot; case CSearchItem::eThisYear: popup5 = eDateRelMethod_SentYear; return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot; } } default:; } switch(reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinMask) { // Relative date case CSearchItem::eWithinDays: case CSearchItem::eWithinWeeks: case CSearchItem::eWithinMonths: case CSearchItem::eWithinYears: { unsigned long within = reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinValueMask; // Set relative popup switch(reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinMask) { case CSearchItem::eWithinDays: default: popup6 = eDateWithin_Days; text3 = within; return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin; case CSearchItem::eWithinWeeks: popup6 = eDateWithin_Weeks; text3 = within; return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin; case CSearchItem::eWithinMonths: popup6 = eDateWithin_Months; text3 = within; return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin; case CSearchItem::eWithinYears: popup6 = eDateWithin_Years; text3 = within; return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin; } } default:; } // Standard date text1 = spec->GenerateDate(false); return original; }
26.429192
147
0.724918
mulberry-mail
90d554c1623d331c06660d1d43126e3b7abd061f
1,655
cpp
C++
Interface/ViewDeath.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
1
2016-05-22T21:28:29.000Z
2016-05-22T21:28:29.000Z
Interface/ViewDeath.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
Interface/ViewDeath.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
/* ViewDeath.cpp (c)2000 Palestar, Richard Lyle */ #include "Debug/Assert.h" #include "Interface/GameDocument.h" #include "DarkSpace/Constants.h" #include "Interface/ViewDeath.h" //---------------------------------------------------------------------------- IMPLEMENT_FACTORY( ViewDeath, WindowView::View ); REGISTER_FACTORY_KEY( ViewDeath, 4096729882495776647 ); ViewDeath::ViewDeath() { // Construct your view class } //---------------------------------------------------------------------------- void ViewDeath::onActivate() { //{{BEGIN_DATA_INIT m_pObserveWindow = WidgetCast<NodeWindow>( window()->findNode( "ObserveWindow" ) ); m_pTextMessage = WidgetCast<WindowText>( window()->findNode( "TextMessage" ) ); //END_DATA_INIT}} // restore the normal cursor in case they were rotating their view on death setCursorState( POINTER ); } void ViewDeath::onDeactivate() { // called before this view is destroyed } void ViewDeath::onUpdate( float t ) { } bool ViewDeath::onMessage( const Message & msg ) { //{{BEGIN_MSG_MAP MESSAGE_MAP( WB_BUTTONUP, 1501550643, onButtonExit); MESSAGE_MAP( WB_BUTTONUP, 1507228051, onButtonOkay); //END_MSG_MAP}} return false; } void ViewDeath::onDocumentUpdate() { // document data has changed, update this view if needed } void ViewDeath::onRender( RenderContext & context, const RectInt & window ) {} //---------------------------------------------------------------------------- bool ViewDeath::onButtonOkay(const Message & msg) { document()->setScene( "SelectShip" ); return true; } bool ViewDeath::onButtonExit(const Message & msg) { document()->setScene( "Main" ); return true; }
21.776316
84
0.627795
SnipeDragon
90da5135ad9024db6593e77809d421ad0c4915d2
710
cpp
C++
acwing/base/829. 模拟队列.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
1
2020-03-26T13:40:52.000Z
2020-03-26T13:40:52.000Z
acwing/base/829. 模拟队列.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
acwing/base/829. 模拟队列.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
/** * author: xmmmmmovo * generation time: 2021/01/31 * filename: 829. 模拟队列.cpp * language & build version : C 11 & C++ 17 */ #include <algorithm> #include <iostream> using namespace std; const int N = 1e5 + 10; int n, s[N]; int l = 0, r = -1; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; string op; int val; while (n--) { cin >> op; if (op == "push") { cin >> val; s[++r] = val; } else if (op == "query") { printf("%d\n", s[l]); } else if (op == "pop") { l++; } else { printf("%s\n", (l > r) ? "YES" : "NO"); } } return 0; }
18.205128
51
0.425352
xmmmmmovo
90ddce7fbe6b187e387f9d462b8526871d82a2b8
704
hpp
C++
llvm/projects/ton-compiler/cpp-sdk/tvm/tuple.hpp
NoamDev/TON-Compiler
f76aa2084c7f09a228afef4a6e073c37b350c8f3
[ "Apache-2.0" ]
59
2019-10-22T16:21:33.000Z
2022-02-01T20:32:32.000Z
llvm/projects/ton-compiler/cpp-sdk/tvm/tuple.hpp
NoamDev/TON-Compiler
f76aa2084c7f09a228afef4a6e073c37b350c8f3
[ "Apache-2.0" ]
51
2019-10-23T11:55:08.000Z
2021-12-21T06:32:11.000Z
llvm/projects/ton-compiler/cpp-sdk/tvm/tuple.hpp
NoamDev/TON-Compiler
f76aa2084c7f09a228afef4a6e073c37b350c8f3
[ "Apache-2.0" ]
15
2019-10-22T19:56:12.000Z
2022-01-12T14:45:15.000Z
#pragma once #include <tvm/untuple_caller.hpp> #include <tvm/unpackfirst_caller.hpp> namespace tvm { template<class T> class __attribute__((tvm_tuple)) tuple { public: tuple() {} explicit tuple(__tvm_tuple tp) : tp_(tp) {} explicit tuple(T tpVal) : tp_(__builtin_tvm_tuple(tpVal)) {} T unpack() const { return tvm::untuple_caller<sizeof(T)>::untuple(tp_); } void pack(const T &tpVal) { tp_ = __builtin_tvm_tuple(tpVal); } static tuple<T> create(T val) { tuple<T> rv; rv.pack(val); return rv; } T unpackfirst() const { return tvm::unpackfirst_caller<sizeof(T)>::unpack(tp_); } __tvm_tuple get() const { return tp_; } private: __tvm_tuple tp_; }; } // namespace tvm
22
83
0.681818
NoamDev