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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2cc4c8b4378b4d8b9f4621e2b5599b8ee8d786d2 | 447 | cpp | C++ | headers/10-throw1.cpp | cpp-tutor/learnmoderncpp-tutorial | 96ca86a2508c80093f51f8ac017f41a994d04d52 | [
"MIT"
] | 1 | 2022-03-07T09:14:07.000Z | 2022-03-07T09:14:07.000Z | headers/10-throw1.cpp | cpp-tutor/learnmoderncpp-tutorial | 96ca86a2508c80093f51f8ac017f41a994d04d52 | [
"MIT"
] | null | null | null | headers/10-throw1.cpp | cpp-tutor/learnmoderncpp-tutorial | 96ca86a2508c80093f51f8ac017f41a994d04d52 | [
"MIT"
] | null | null | null | // 10-throw1.cpp : simple exception demonstration, throw and catch
#include <iostream>
#include <exception>
using namespace std;
template <typename T>
void getInteger(T& value) {
cout << "Please enter an integer (0 to throw): ";
cin >> value;
if (!value) {
throw exception{};
}
}
int main() {
long long v{};
try {
getInteger(v);
}
catch (...) {
cerr << "Caught exception!\n";
return 1;
}
cout << "Got value: " << v << '\n';
}
| 16.555556 | 66 | 0.612975 | cpp-tutor |
2cc77442f3f1ac290fd662ee4c3e018d2c6df545 | 4,664 | cpp | C++ | libraries/vulkan_utils/private/VulkanMemory.cpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | 132 | 2021-04-04T21:19:46.000Z | 2022-03-13T13:47:00.000Z | libraries/vulkan_utils/private/VulkanMemory.cpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | null | null | null | libraries/vulkan_utils/private/VulkanMemory.cpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | 7 | 2021-04-04T21:19:48.000Z | 2021-04-09T09:16:34.000Z | #include "VulkanMemory.hpp"
#include <stdexcept>
#include <cstring>
#include "VulkanCommandBuffer.hpp"
uint32_t
findMemoryType(VkPhysicalDevice physical_device,
uint32_t type_filter,
VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties mem_prop;
vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_prop);
for (uint32_t i = 0; i < mem_prop.memoryTypeCount; i++) {
if (type_filter & (1 << i) && ((mem_prop.memoryTypes[i].propertyFlags &
properties) == properties)) {
return i;
}
}
throw std::runtime_error("VkMemory: Failed to get memory type");
}
void
createBuffer(VkDevice device,
VkBuffer &buffer,
VkDeviceSize size,
VkBufferUsageFlags usage)
{
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = size;
buffer_info.usage = usage;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &buffer_info, nullptr, &buffer) != VK_SUCCESS) {
throw std::runtime_error("VkMemory: Failed to create buffer");
}
}
void
allocateBuffer(VkPhysicalDevice physical_device,
VkDevice device,
VkBuffer &buffer,
VkDeviceMemory &buffer_memory,
VkMemoryPropertyFlags properties)
{
VkMemoryRequirements mem_requirement;
vkGetBufferMemoryRequirements(device, buffer, &mem_requirement);
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = mem_requirement.size;
alloc_info.memoryTypeIndex = findMemoryType(
physical_device, mem_requirement.memoryTypeBits, properties);
if (vkAllocateMemory(device, &alloc_info, nullptr, &buffer_memory) !=
VK_SUCCESS) {
throw std::runtime_error("VkMemory: Failed to allocate memory");
}
vkBindBufferMemory(device, buffer, buffer_memory, 0);
}
void
copyBufferOnGpu(VkDevice device,
VkCommandPool command_pool,
VkQueue gfx_queue,
VkBuffer dst_buffer,
VkBuffer src_buffer,
VkDeviceSize size)
{
VkCommandBuffer cmd_buffer = beginSingleTimeCommands(device, command_pool);
VkBufferCopy copy_region{};
copy_region.size = size;
copy_region.dstOffset = 0;
copy_region.srcOffset = 0;
vkCmdCopyBuffer(cmd_buffer, src_buffer, dst_buffer, 1, ©_region);
endSingleTimeCommands(device, command_pool, cmd_buffer, gfx_queue);
}
void
copyBufferOnGpu(VkDevice device,
VkCommandPool command_pool,
VkQueue gfx_queue,
VkBuffer dst_buffer,
VkBuffer src_buffer,
VkBufferCopy copy_region)
{
VkCommandBuffer cmd_buffer = beginSingleTimeCommands(device, command_pool);
vkCmdCopyBuffer(cmd_buffer, src_buffer, dst_buffer, 1, ©_region);
endSingleTimeCommands(device, command_pool, cmd_buffer, gfx_queue);
}
void
copyOnCpuCoherentMemory(VkDevice device,
VkDeviceMemory memory,
VkDeviceSize offset,
VkDeviceSize size,
void const *dataToCopy)
{
void *mapped_data{};
vkMapMemory(device, memory, offset, size, 0, &mapped_data);
memcpy(mapped_data, dataToCopy, size);
vkUnmapMemory(device, memory);
}
void
copyCpuBufferToGpu(VkDevice device,
VkPhysicalDevice physicalDevice,
VkCommandPool commandPool,
VkQueue queue,
VkBuffer dstBuffer,
void *srcData,
VkBufferCopy copyRegion)
{
// Staging buffer on CPU
VkBuffer staging_buffer{};
VkDeviceMemory staging_buffer_memory{};
createBuffer(device,
staging_buffer,
copyRegion.size,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
allocateBuffer(physicalDevice,
device,
staging_buffer,
staging_buffer_memory,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
// Copy on staging buffer
copyOnCpuCoherentMemory(
device, staging_buffer_memory, 0, copyRegion.size, srcData);
// Copy on GPU
copyBufferOnGpu(
device, commandPool, queue, dstBuffer, staging_buffer, copyRegion);
// Cleaning
vkDestroyBuffer(device, staging_buffer, nullptr);
vkFreeMemory(device, staging_buffer_memory, nullptr);
}
| 31.727891 | 79 | 0.65416 | jcelerier |
2cc81dc413167b8d02de7c92c789bfdbe81d834d | 816 | hpp | C++ | src/monitors/probes/list.hpp | owenmylotte/ablate | 92b190a2d422eb89748338c04fd7b29976be54b1 | [
"BSD-3-Clause"
] | null | null | null | src/monitors/probes/list.hpp | owenmylotte/ablate | 92b190a2d422eb89748338c04fd7b29976be54b1 | [
"BSD-3-Clause"
] | null | null | null | src/monitors/probes/list.hpp | owenmylotte/ablate | 92b190a2d422eb89748338c04fd7b29976be54b1 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ABLATELIBRARY_PROBEINITIALIZER_LIST_HPP
#define ABLATELIBRARY_PROBEINITIALIZER_LIST_HPP
#include <memory>
#include <vector>
#include "probeInitializer.hpp"
namespace ablate::monitors::probes {
class List : public ProbeInitializer {
private:
const std::vector<Probe> list;
public:
/**
* default list of probe monitors, useful for the parser init
* @param probes
*/
explicit List(const std::vector<std::shared_ptr<Probe>>& probes);
/**
* list of probe monitors
* @param probes
*/
explicit List(std::vector<Probe> probes);
/**
* list of probe locations with names
* @return
*/
const std::vector<Probe>& GetProbes() const override { return list; }
};
} // namespace ablate::monitors::probes
#endif // ABLATELIBRARY_LIST_HPP
| 22.666667 | 73 | 0.675245 | owenmylotte |
2cc82bfa7ec04687ec56f78e45d1b268fc14af9c | 8,688 | cpp | C++ | tests/tria/math/quat_test.cpp | BastianBlokland/tria | a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78 | [
"MIT"
] | null | null | null | tests/tria/math/quat_test.cpp | BastianBlokland/tria | a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78 | [
"MIT"
] | null | null | null | tests/tria/math/quat_test.cpp | BastianBlokland/tria | a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78 | [
"MIT"
] | null | null | null | #include "catch2/catch.hpp"
#include "tria/math/mat.hpp"
#include "tria/math/quat.hpp"
#include "tria/math/quat_io.hpp"
#include "tria/math/utils.hpp"
#include "tria/math/vec.hpp"
namespace tria::math::tests {
TEST_CASE("[math] - Quat", "[math]") {
SECTION("Quaternions are fixed size") {
auto q1 = Quatf{};
CHECK(sizeof(q1) == sizeof(float) * 4);
auto q2 = Quat<double>{};
CHECK(sizeof(q2) == sizeof(double) * 4);
}
SECTION("Quaternions can be reassigned") {
auto q = Quatf{};
q = identityQuatf();
CHECK(q[0] == 0);
CHECK(q[1] == 0);
CHECK(q[2] == 0);
CHECK(q[3] == 1);
}
SECTION("Quaternions can be checked for equality") {
CHECK(identityQuatf() == identityQuatf());
CHECK(!(Quatf{} == identityQuatf()));
}
SECTION("Quaternions can be checked for inequality") {
CHECK(Quatf{} != identityQuatf());
CHECK(!(identityQuatf() != identityQuatf()));
}
SECTION("Dividing a quaternion by a scalar divides each component") {
CHECK(approx(Quatf{2, 4, 6, 2} / 2, Quatf{1, 2, 3, 1}));
}
SECTION("Multiplying a quaternion by a scalar multiplies each component") {
CHECK(approx(Quatf{2, 4, 6, 2} * 2, Quatf{4, 8, 12, 4}));
}
SECTION("Square magnitude is sum of squared components") {
const auto q = Quatf{1.f, 2.f, 3.f, 1.f};
CHECK(approx(q.getSqrMag(), 15.f));
}
SECTION("Magnitude is the square root of the sum of squared components") {
const auto q = Quatf{0.f, 42.f, 0.f, 0.f};
CHECK(approx(q.getMag(), 42.0f));
}
SECTION("Identity quat multiplied by a identity quat returns another identity quat") {
CHECK(approx(identityQuatf() * identityQuatf(), identityQuatf()));
}
SECTION("Inverse an of identity quaternion is also a identity quaternion") {
CHECK(approx(identityQuatf().getInv(), identityQuatf()));
}
SECTION("Square magnitude of an identity quaternion is 1") {
CHECK(approx(identityQuatf().getSqrMag(), 1.f));
}
SECTION("Multiplying an identity quaternion by a vector yields the same vector") {
auto q = identityQuatf();
CHECK(approx(q * dir3d::forward(), dir3d::forward()));
CHECK(approx(q * Vec3f{.42, 13.37, -42}, Vec3f{.42, 13.37, -42}));
}
SECTION("Quaternions can be composed") {
auto rot1 = angleAxisQuatf(dir3d::up(), 42.f);
auto rot2 = angleAxisQuatf(dir3d::right(), 13.37f);
auto comb1 = rot1 * rot2;
auto comb2 = rot2 * rot1;
CHECK(approx(comb1 * Vec3f{.42, 13.37, -42}, rot1 * (rot2 * Vec3f{.42, 13.37, -42}), .000001f));
CHECK(approx(comb2 * Vec3f{.42, 13.37, -42}, rot2 * (rot1 * Vec3f{.42, 13.37, -42}), .000001f));
}
SECTION(
"Multiplying a quaternion by a normalized quaternion returns in a normalized quaternion") {
auto rot1 = angleAxisQuatf(dir3d::up(), 42.f);
auto rot2 = angleAxisQuatf(dir3d::right(), 13.37f);
CHECK(approx(rot1.getSqrMag(), 1.f, .000001f));
CHECK(approx(rot2.getSqrMag(), 1.f, .000001f));
CHECK(approx((rot1 * rot2).getSqrMag(), 1.f, .000001f));
}
SECTION("Inverse of a normalized quaternion is also normalized") {
auto rot = angleAxisQuatf(Vec3f{.42, 13.37, -42}.getNorm(), 13.37f);
CHECK(approx(rot.getSqrMag(), 1.f, .000001f));
CHECK(approx(rot.getInv().getSqrMag(), 1.f, .000001f));
}
SECTION("Rotating 'left' 180 degrees over y axis results in 'right'") {
auto rot = angleAxisQuatf(dir3d::up(), 180.f * math::degToRad<float>);
CHECK(approx(rot * dir3d::left(), dir3d::right(), .000001f));
}
SECTION("Rotating 'left' 90 degrees over y axis results in 'forward'") {
auto rot = angleAxisQuatf(dir3d::up(), 90.f * math::degToRad<float>);
CHECK(approx(rot * dir3d::left(), dir3d::forward(), .000001f));
}
SECTION("Rotating 'left' by inverse of 90 degrees over y axis results in 'backward'") {
auto rot = angleAxisQuatf(dir3d::up(), 90.f * math::degToRad<float>);
CHECK(approx(rot.getInv() * dir3d::left(), dir3d::backward(), .000001f));
}
SECTION("Rotating a vector by 42 degrees results in a vector that is 42 degrees away") {
auto rot = angleAxisQuatf(dir3d::up(), 42.f * math::degToRad<float>);
CHECK(approx(
angle(dir3d::forward(), rot * dir3d::forward()) * math::radToDeg<float>, 42.f, .000001f));
CHECK(approx(
angle(dir3d::forward(), rot.getInv() * dir3d::forward()) * math::radToDeg<float>,
42.f,
.000001f));
}
SECTION("Quaternion angle axis over right axis provides the same results as x-rotation matrix") {
auto rotMat = rotXMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::right(), 42.f);
auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f};
auto vec2 = rotQuat * Vec3f{.42, 13.37, -42};
CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f));
}
SECTION("Quaternion angle axis over up axis provides the same results as y-rotation matrix") {
auto rotMat = rotYMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::up(), 42.f);
auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f};
auto vec2 = rotQuat * Vec3f{.42, 13.37, -42};
CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f));
}
SECTION(
"Quaternion angle axis over forward axis provides the same results as z-rotation matrix") {
auto rotMat = rotZMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::forward(), 42.f);
auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f};
auto vec2 = rotQuat * Vec3f{.42, 13.37, -42};
CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f));
}
SECTION(
"Creating rotation matrix from angle-axis over right is the same as a x-rotation matrix") {
auto rotMat = rotXMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::right(), 42.f);
CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f));
}
SECTION("Creating rotation matrix from angle-axis over up is the same as a y-rotation matrix") {
auto rotMat = rotYMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::up(), 42.f);
CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f));
}
SECTION(
"Creating rotation matrix from angle-axis over forward is the same as a z-rotation matrix") {
auto rotMat = rotZMat4f(42.f);
auto rotQuat = angleAxisQuatf(dir3d::forward(), 42.f);
CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f));
}
SECTION("Rotation matrix from axes is the same as from a quaternion") {
auto rot = angleAxisQuatf(dir3d::up(), 42.f) * angleAxisQuatf(dir3d::right(), 13.f);
auto newRight = rot * dir3d::right();
auto newUp = rot * dir3d::up();
auto newForward = rot * dir3d::forward();
auto matFromAxes = rotMat4f(newRight, newUp, newForward);
CHECK(approx(matFromAxes, rotMat4f(rot), .000001f));
}
SECTION("Rotate 180 degrees over y axis rotation can be retrieved from rotation matrix") {
auto mat = Mat3f{};
mat[0][0] = -1.f;
mat[1][1] = 1.f;
mat[2][2] = -1.f;
CHECK(approx(quatFromMat(mat), angleAxisQuatf(dir3d::up(), math::pi<float>), .000001f));
}
SECTION("Quaternion -> Matrix -> Quaternion produces the same value") {
auto rotQuat1 = angleAxisQuatf(dir3d::up(), 42.f) * angleAxisQuatf(dir3d::right(), 13.f);
auto rotQuat2 = quatFromMat(rotMat3f(rotQuat1));
auto vec = Vec3f{.42, 13.37, -42};
CHECK(approx(rotQuat1 * vec, rotQuat2 * vec, .00001f));
}
SECTION("Quaternion created from orthogonal rotation matrix is normalized") {
auto mat = rotXMat3f(42.f) * rotYMat3f(-13.37f) * rotZMat3f(1.1f);
auto quat = quatFromMat(mat);
CHECK(approx(quat.getSqrMag(), 1.f, .000001f));
}
SECTION("Look rotation rotates from identity to the given axis system") {
auto newFwd = Vec3f{.42, 13.37, -42}.getNorm();
auto rot = lookRotQuatf(newFwd, dir3d::up());
CHECK(approx(rot * dir3d::forward(), newFwd, .000001f));
}
SECTION("Look rotation returns a normalized quaternion") {
auto rot = lookRotQuatf(Vec3f{.42, 13.37, -42}, dir3d::down());
CHECK(approx(rot.getSqrMag(), 1.f, .000001f));
}
SECTION("Look rotation is the same as building a rotation matrix from axes") {
auto rotQuat = lookRotQuatf(dir3d::right(), dir3d::down());
auto rotMat = rotMat4f(dir3d::forward(), dir3d::down(), dir3d::right());
auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f};
auto vec2 = rotQuat * Vec3f{.42, 13.37, -42};
CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f));
}
SECTION("Normalizing a quaterion results in a quaternion with length 1") {
auto q = Quatf{1337.f, 42.f, -42.f, 5.f};
CHECK(approx(q.getNorm().getMag(), 1.f));
q.norm();
CHECK(approx(q.getMag(), 1.f));
}
}
} // namespace tria::math::tests
| 37.61039 | 100 | 0.635474 | BastianBlokland |
2cc90b7810bdaed73909a516e876826a4a64bb4c | 2,104 | cpp | C++ | uppdev/SvoValue/Checks.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/SvoValue/Checks.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/SvoValue/Checks.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "SvoValue.h"
void DumpNumber(const Value& v)
{
RDUMP((int)v);
RDUMP((double)v);
RDUMP((int64)v);
RDUMP((bool)v);
}
int xx;
Value Opt0();
void Opt() {
Value v = Opt0();
xx = v;
}
void CheckString()
{
Value v = "ahoj";
for(int i = 0; i < 2; i++) {
String s = v;
RDUMP(s);
ASSERT(s == "ahoj");
WString ws = v;
RDUMP(ws);
ASSERT(ws == WString("ahoj"));
v = ws;
}
v = String("ahoj");
Value w = WString("ahoj");
ASSERT(v == w);
RDUMP(GetHashValue(v));
RDUMP(GetHashValue(w));
ASSERT(GetHashValue(v) == GetHashValue(w));
}
void CheckDateTime()
{
Time tm = GetSysTime();
Date dt = tm;
Value c;
Value v = tm;
RDUMP(v);
ASSERT(v == dt);
Date xx = v;
ASSERT(xx == dt);
c = v;
RDUMP(c);
ASSERT(c == dt);
Value cv = v;
RDUMP(cv);
ASSERT(cv == dt);
Value v2 = tm;
RDUMP(v2);
ASSERT(v2 == v);
c = v;
RDUMP(c);
ASSERT(c == dt);
ASSERT(c == tm);
v = dt;
v2 = ToTime(v);
ASSERT(v == v2);
ASSERT(GetHashValue(v) == GetHashValue(v2));
}
void CheckValueMap()
{
RLOG("------------------------------");
RLOG("CheckValueMap");
Value x = 123;
Value y = x;
ValueMap h;
h.Add("0", 123);
RDUMP(h["0"]);
h.Add("1", Date(2001, 12, 1));
h.Add("2", "test");
Value v = h;
ASSERT(v.GetCount() == 3);
RDUMP(v["0"]);
ASSERT(v["0"] == 123);
ASSERT(v["1"] == Date(2001, 12, 1));
ASSERT(v["2"] == "test");
ValueMap hh = v;
ASSERT(hh == h);
}
void OtherChecks()
{
Value c;
ASSERT(c.IsVoid());
RDUMP(c.IsVoid());
Value x = "Ahoj";
String xx = x;
RDUMP(xx);
ASSERT(xx == "Ahoj");
Value xw = WString("Ahoj");
RDUMP(xw);
RDUMP(xw == x);
Value xc = x;
RDUMP(xc);
c = xc;
RDUMP(c);
Value y = 123;
int yy = y;
RDUMP(yy);
Value xn = (int)Null;
RDUMP(IsNull(xn));
RDUMP(IsNull(yy));
Value yc = y;
RDUMP(y);
c = y;
RDUMP(c);
Value v2 = 123.0;
Value v3 = 123;
Value v4 = 125;
RDUMP(v2 == y);
RDUMP(v3 == y);
RDUMP(v4 == y);
RDUMP(v4 == v2);
Value uu = Uuid::Create();
RDUMP(uu);
Value uuc = uu;
RDUMP(uuc);
{
Color c = Blue;
Value v = c;
RDUMP(v);
Value v2 = v;
c = v2;
RDUMP(c);
}
}
| 13.662338 | 45 | 0.532795 | dreamsxin |
2cca7b2d7c7dc21b45de21c60391fab7a08e3f31 | 7,798 | cpp | C++ | src/services/openid_connect.cpp | umr-dbs/mapping-gfbio | 820f0ccde16cab9f5780864d2402149230f01acf | [
"MIT"
] | null | null | null | src/services/openid_connect.cpp | umr-dbs/mapping-gfbio | 820f0ccde16cab9f5780864d2402149230f01acf | [
"MIT"
] | 2 | 2018-04-04T10:38:47.000Z | 2020-12-07T13:26:04.000Z | src/services/openid_connect.cpp | umr-dbs/mapping-gfbio | 820f0ccde16cab9f5780864d2402149230f01acf | [
"MIT"
] | 2 | 2018-03-07T07:50:24.000Z | 2018-06-05T13:51:58.000Z | #include "openid_connect.h"
void OpenIdConnectService::OpenIdConnectService::run() {
try {
const std::string &request = params.get("request");
if (request == "login") {
this->login(params.get("access_token"));
} else { // FALLBACK
response.sendFailureJSON("OpenIdConnectService: Invalid request");
}
} catch (const std::exception &e) {
response.sendFailureJSON(e.what());
}
}
auto OpenIdConnectService::login(const std::string &access_token) const -> void {
static const std::unordered_set<std::string> allowed_jwt_algorithms{"RS256"};
static const auto jwks_endpoint_url = Configuration::get<std::string>("oidc.jwks_endpoint");
static const auto user_endpoint_url = Configuration::get<std::string>("oidc.user_endpoint");
static const auto allowed_clock_skew_seconds = Configuration::get<uint32_t>("oidc.allowed_clock_skew_seconds");
const auto jwks = download_jwks(jwks_endpoint_url);
const auto jwt_algorithm = jwks.get("alg", "").asString();
if (allowed_jwt_algorithms.count(jwt_algorithm) <= 0) {
throw OpenIdConnectService::OpenIdConnectServiceException(
concat("OpenIdConnectService: Algorithm ", jwt_algorithm, " is not supported"));
}
const std::string pem = jwks_to_pem(jwks.get("n", "").asString(), jwks.get("e", "").asString());
const auto decoded_token = jwt::decode(access_token,
jwt::params::algorithms({jwt_algorithm}),
jwt::params::secret(pem),
jwt::params::leeway(allowed_clock_skew_seconds),
jwt::params::verify(true));
const auto &payload = decoded_token.payload();
const uint32_t expiration_time = payload.get_claim_value<uint32_t>(jwt::registered_claims::expiration);
const auto user_json = download_user_data(user_endpoint_url, access_token);
OpenIdConnectService::User user{
.goe_id = user_json.get("goe_id", "").asString(),
.email = user_json.get("email", "").asString(),
.given_name = user_json.get("given_name", "").asString(),
.family_name = user_json.get("family_name", "").asString(),
.preferred_username = user_json.get("preferred_username", "").asString(),
.expiration_time = expiration_time,
};
response.sendSuccessJSON("session", createSessionAndAccountIfNotExist(user));
}
auto OpenIdConnectService::jwks_to_pem(const std::string &n, const std::string &e) -> std::string {
auto n_decoded = cppcodec::base64_url_unpadded::decode(n);
auto e_decoded = cppcodec::base64_url_unpadded::decode(e);
BIGNUM *modul = BN_bin2bn(n_decoded.data(), n_decoded.size(), nullptr);
BIGNUM *expon = BN_bin2bn(e_decoded.data(), e_decoded.size(), nullptr);
std::unique_ptr<RSA, std::function<void(RSA *)>> rsa(
RSA_new(),
[](RSA *rsa) { RSA_free(rsa); }
);
RSA_set0_key(rsa.get(), modul, expon, nullptr);
std::unique_ptr<BIO, std::function<void(BIO *)>> memory_file(
BIO_new(BIO_s_mem()),
[](BIO *bio) {
BIO_set_close(bio, BIO_CLOSE);
BIO_free_all(bio);
}
);
PEM_write_bio_RSA_PUBKEY(memory_file.get(), rsa.get());
BUF_MEM *memory_pointer;
BIO_get_mem_ptr(memory_file.get(), &memory_pointer);
return std::string(memory_pointer->data, memory_pointer->length);
}
auto OpenIdConnectService::download_jwks(const std::string &url) -> Json::Value {
std::stringstream data;
cURL curl;
curl.setOpt(CURLOPT_PROXY, Configuration::get<std::string>("proxy", "").c_str());
curl.setOpt(CURLOPT_URL, url.c_str());
curl.setOpt(CURLOPT_WRITEFUNCTION, cURL::defaultWriteFunction);
curl.setOpt(CURLOPT_WRITEDATA, &data);
curl.perform();
try {
curl.perform();
} catch (const cURLException &e) {
throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: JSON Web Key Set service unavailable");
}
Json::Reader reader(Json::Features::strictMode());
Json::Value response;
if (!reader.parse(data.str(), response)
|| response.empty() || !response.isMember("keys")
|| !response["keys"][0].isMember("n") || !response["keys"][0].isMember("e") || !response["keys"][0].isMember("alg")) {
Log::error(concat(
"OpenIdConnectService: JSON Web Key Set is invalid (malformed JSON)",
'\n',
data.str()
));
throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: JSON Web Key Set is invalid (malformed JSON)");
}
// return first key
return response["keys"][0];
}
auto OpenIdConnectService::download_user_data(const std::string &url, const std::string &access_token) -> Json::Value {
std::stringstream data;
cURL curl;
curl.setOpt(CURLOPT_PROXY, Configuration::get<std::string>("proxy", "").c_str());
curl.setOpt(CURLOPT_URL, url.c_str());
curl.setOpt(CURLOPT_HTTPAUTH, CURLAUTH_BEARER); // NOLINT(hicpp-signed-bitwise)
curl.setOpt(CURLOPT_XOAUTH2_BEARER, access_token.c_str());
curl.setOpt(CURLOPT_WRITEFUNCTION, cURL::defaultWriteFunction);
curl.setOpt(CURLOPT_WRITEDATA, &data);
curl.perform();
try {
curl.perform();
} catch (const cURLException &e) {
throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: User endpoint unavailable");
}
Json::Reader reader(Json::Features::strictMode());
Json::Value response;
if (!reader.parse(data.str(), response) || response.empty()
|| !response.isMember("goe_id") || !response.isMember("email")) {
Log::error(concat(
"OpenIdConnectService: User data is invalid (malformed JSON)",
'\n',
data.str()
));
throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: User data is invalid (malformed JSON)");
}
return response;
}
auto OpenIdConnectService::createSessionAndAccountIfNotExist(const User &user) -> std::string {
std::shared_ptr<UserDB::Session> session;
const auto user_id = OpenIdConnectService::EXTERNAL_ID_PREFIX + user.goe_id;
const std::time_t current_time = std::time(nullptr);
const auto expiration_time_in_seconds = user.expiration_time - current_time;
try {
// create session for user if he already exists
session = UserDB::createSessionForExternalUser(user_id, expiration_time_in_seconds);
// TODO: think about updating user data like email, etc.
} catch (const UserDB::authentication_error &e) {
// user does not exist locally => CREATE
try {
auto mapping_user = UserDB::createExternalUser(
user.preferred_username,
concat(user.given_name, ' ', user.family_name),
user.email,
user_id
);
try {
auto gfbio_group = UserDB::loadGroup("gfbio");
mapping_user->joinGroup(*gfbio_group);
} catch (const UserDB::database_error &) {
auto gfbio_group = UserDB::createGroup("gfbio");
mapping_user->joinGroup(*gfbio_group);
}
session = UserDB::createSessionForExternalUser(user_id, expiration_time_in_seconds);
} catch (const std::exception &e) {
throw OpenIdConnectService::OpenIdConnectServiceException(
"OpenIdConnectService: Could not create new user from GFBio Single Sign On.");
}
}
return session->getSessiontoken();
}
| 39.989744 | 136 | 0.63901 | umr-dbs |
2ccb796330e3327c55b510dd9d986ad25ad94a3b | 4,344 | hpp | C++ | include/algorithms/nicol2d.hpp | GT-TDAlab/SARMA | dab79f7d87a4dfb663b09e9f7331726811e05c1a | [
"BSD-3-Clause"
] | 10 | 2020-07-03T02:41:45.000Z | 2022-02-08T02:28:09.000Z | include/algorithms/nicol2d.hpp | GT-TDAlab/SARMA | dab79f7d87a4dfb663b09e9f7331726811e05c1a | [
"BSD-3-Clause"
] | null | null | null | include/algorithms/nicol2d.hpp | GT-TDAlab/SARMA | dab79f7d87a4dfb663b09e9f7331726811e05c1a | [
"BSD-3-Clause"
] | 1 | 2021-03-08T17:05:02.000Z | 2021-03-08T17:05:02.000Z | #pragma once
#include <vector>
#include <cassert>
#include <utility>
#include <algorithm>
#include <functional>
#include <numeric>
#include "data_structures/csr_matrix.hpp"
#include "tools/utils.hpp"
#include "nicol1d.hpp"
/**
* @brief This namespace contains required functions for
* Nicol's two-dimensional partitioning algorithm
* described in "David Nicol, Rectilinear Partitioning of Irregular Data Parallel Computations, JPDC, 1994".
*/
#if defined(ENABLE_CPP_PARALLEL)
namespace sarma::nicol2d {
#else
namespace sarma{
namespace nicol2d {
#endif
template <class Ordinal, class Value, bool use_indices = true>
auto partition(const Matrix<Ordinal, Value> &A, const std::vector<Ordinal> &p, const Ordinal Q, const bool p_is_rows = true, int max_iteration = 0) {
if (max_iteration == 0)
max_iteration = std::max((Ordinal)10, (Ordinal)p.size() - 1 + Q);
else if (max_iteration < 0)
max_iteration = std::numeric_limits<int>::max();
std::vector<std::vector<Ordinal>> ps = {p, p};
const auto AT_ = A.transpose();
const std::vector<Matrix<Ordinal, Value> const *> As = {&A, &AT_};
const std::vector<Ordinal> Ps = {p_is_rows ? (Ordinal)p.size() - 1 : Q, p_is_rows ? Q : (Ordinal)p.size() - 1};
std::vector<std::vector<std::vector<Value>>> prefixess;
for (int i = 0; i < 2; i++)
prefixess.emplace_back(Ps[~i & 1], std::vector<Value>(As[i & 1]->indptr.size(), 0));
for (int i = p_is_rows ? 1 : 0; i <= max_iteration; i++) {
const auto &A = *As[i & 1];
auto &p = ps[i & 1];
const auto P = Ps[i & 1];
const auto &q = ps[~i & 1];
auto &prefixes = prefixess[i & 1];
for (auto &v: prefixes)
#if defined(ENABLE_CPP_PARALLEL)
std::fill(exec_policy, v.begin(), v.end(), 0);
std::for_each(exec_policy, A.indptr.begin(), A.indptr.end() - 1, [&](const auto &indptr_i) {
#else
std::fill(v.begin(), v.end(), 0);
std::for_each( A.indptr.begin(), A.indptr.end() - 1, [&](const auto &indptr_i) {
#endif
const auto i = std::distance(&A.indptr[0], &indptr_i);
for (auto j = indptr_i; j < A.indptr[i + 1]; j++)
prefixes[utils::lowerbound_index(q, A.indices[j])][i + 1] += A.data(j);
});
for (auto &v: prefixes){
#if defined(ENABLE_CPP_PARALLEL)
std::inclusive_scan(exec_policy, v.begin(), v.end(), v.begin());
#else
for (size_t j=1; j<v.size(); j++){
v[j] += v[j-1];
}
#endif
}
const auto prev_p = p;
p = nicol1d::partition<Ordinal, Value, use_indices>(&prefixes[0], (Ordinal)prefixes.size(), P);
#ifdef DEBUG
const auto o_p = nicol1d::partition<Ordinal, Value, !use_indices>(&prefixes[0], (Ordinal)prefixes.size(), P);
assert(p == o_p);
const auto l = A.compute_maxload(p, q);
std::cerr << i << ' ' << l << std::endl;
for (auto x: p)
std::cerr << x << ' ';
std::cerr << std::endl;
for (auto x: o_p)
std::cerr << x << ' ';
std::cerr << std::endl;
#endif
if (p == prev_p)
break;
}
return std::make_pair(ps[0], ps[1]);
}
/**
* @brief Implements the rectilinear partitioning algorithm with
* iterative refinement described in "David Nicol, Rectilinear
* Partitioning of Irregular Data Parallel Computations, JPDC,
* 1994".
*
* @param A Matrix
* @param P number of parts
* @param Q number of parts in the other dimension
* @param max_iteration limit on refinement iterations
* @return two cut vectors as a pair
*/
template <class Ordinal, class Value, bool use_indices = true>
auto partition(const Matrix<Ordinal, Value> &A, const Ordinal P, const Ordinal Q, const int max_iteration = 0) {
const auto p = nicol1d::partition<Ordinal, Ordinal, use_indices>(&A.indptr, (Ordinal)1, P);
return partition<Ordinal, Value, use_indices>(A, p, Q, true, max_iteration);
}
}
#if !defined(ENABLE_CPP_PARALLEL)
} // nested namespace
#endif | 41.371429 | 153 | 0.56837 | GT-TDAlab |
2cd067070b2e7be96aa262c8a9c3d38d039051b4 | 607 | hpp | C++ | nucleo/Inc/globals.hpp | cerberuspower/monochromator | 0324831743652bccea7c760b3994d06c7a766c16 | [
"Apache-2.0"
] | null | null | null | nucleo/Inc/globals.hpp | cerberuspower/monochromator | 0324831743652bccea7c760b3994d06c7a766c16 | [
"Apache-2.0"
] | null | null | null | nucleo/Inc/globals.hpp | cerberuspower/monochromator | 0324831743652bccea7c760b3994d06c7a766c16 | [
"Apache-2.0"
] | null | null | null | #ifndef __GLOBALS_INCLUDED__
#define __GLOBALS_INCLUDED__
#include "motor.hpp"
#include "uart.hpp"
#include <string.h>
#include <stdlib.h>
#include "stm32f3xx_hal.h"
typedef struct monochromator_t {
Motor *motor;
Uart *uart;
uint16_t end_stop_forward;
uint16_t end_stop_reverse;
uint8_t aBuffer[RX_BUFFER_SIZE];
uint32_t current_position;
uint8_t step_divider_settings;
uint32_t Max_Wavelength;
uint32_t Min_Wavelength;
} monochromator_t;
void buffer_analyze(char buffer[12]);
extern monochromator_t monochromator;
#endif // ifndef __GLOBALS_INCLUDED__
| 21.678571 | 38 | 0.75453 | cerberuspower |
2cd0a5a2921bf137a93200689ec6ee945b6a5417 | 5,573 | cpp | C++ | tools/test/systemtest/aa/aa_command_start_system_test.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | null | null | null | tools/test/systemtest/aa/aa_command_start_system_test.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | null | null | null | tools/test/systemtest/aa/aa_command_start_system_test.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:48.000Z | 2021-09-13T11:17:48.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <thread>
#include "ability_command.h"
#include "ability_manager_client.h"
#include "ability_manager_interface.h"
#include "bundle_command.h"
#include "tool_system_test.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace {
const std::string STRING_DEVICE_NAME = "device";
const std::string STRING_PAGE_ABILITY_BUNDLE_PATH = "/data/test/resource/aa/pageAbilityBundleForStart.hap";
const std::string STRING_PAGE_ABILITY_BUNDLE_NAME = "com.ohos.tools.pageAbilityBundleForStart";
const std::string STRING_PAGE_ABILITY_BUNDLE_NAME_INVALID = STRING_PAGE_ABILITY_BUNDLE_NAME + ".invalid";
const std::string STRING_PAGE_ABILITY_NAME = "com.ohos.tools.pageAbilityForStart.MainAbility";
const std::string STRING_PAGE_ABILITY_NAME_INVALID = STRING_PAGE_ABILITY_NAME + ".Invalid";
const std::string STRING_SERVICE_ABILITY_BUNDLE_PATH = "/data/test/resource/aa/serviceAbilityBundleForStart.hap";
const std::string STRING_SERVICE_ABILITY_BUNDLE_NAME = "com.ohos.tools.serviceAbilityBundleForStart";
const std::string STRING_SERVICE_ABILITY_BUNDLE_NAME_INVALID = STRING_SERVICE_ABILITY_BUNDLE_NAME + ".invalid";
const std::string STRING_SERVICE_ABILITY_NAME = "MainAbility";
const std::string STRING_SERVICE_ABILITY_NAME_INVALID = STRING_SERVICE_ABILITY_NAME + ".Invalid";
} // namespace
class AaCommandStartSystemTest : public ::testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
};
void AaCommandStartSystemTest::SetUpTestCase()
{}
void AaCommandStartSystemTest::TearDownTestCase()
{}
void AaCommandStartSystemTest::SetUp()
{
// reset optind to 0
optind = 0;
}
void AaCommandStartSystemTest::TearDown()
{}
/**
* @tc.number: Aa_Command_Start_SystemTest_0100
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa start -d <device-id> -a <ability-name> -b <bundle-name> -D" command.
*/
HWTEST_F(AaCommandStartSystemTest, Aa_Command_Start_SystemTest_0100, Function | MediumTest | Level1)
{
// uninstall the bundle
ToolSystemTest::UninstallBundle(STRING_PAGE_ABILITY_BUNDLE_NAME);
// install the bundle
ToolSystemTest::InstallBundle(STRING_PAGE_ABILITY_BUNDLE_PATH, true);
// start the page ability
std::string command = "aa start -d " + STRING_DEVICE_NAME + " -a " + STRING_PAGE_ABILITY_NAME + " -b " +
STRING_PAGE_ABILITY_BUNDLE_NAME + " -D";
std::string commandResult = ToolSystemTest::ExecuteCommand(command);
EXPECT_EQ(commandResult, STRING_START_ABILITY_OK + "\n");
// uninstall the bundle
ToolSystemTest::UninstallBundle(STRING_PAGE_ABILITY_BUNDLE_NAME);
}
/**
* @tc.number: Aa_Command_Start_SystemTest_0200
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa start -d <device-id> -a <ability-name> -b <bundle-name>" command.
*/
HWTEST_F(AaCommandStartSystemTest, Aa_Command_Start_SystemTest_0200, Function | MediumTest | Level1)
{
// uninstall the bundle
ToolSystemTest::UninstallBundle(STRING_SERVICE_ABILITY_BUNDLE_NAME);
// install the bundle
ToolSystemTest::InstallBundle(STRING_SERVICE_ABILITY_BUNDLE_PATH, true);
// start the service ability
std::string command = "aa start -d " + STRING_DEVICE_NAME + " -a " + STRING_SERVICE_ABILITY_NAME + " -b " +
STRING_SERVICE_ABILITY_BUNDLE_NAME;
std::string commandResult = ToolSystemTest::ExecuteCommand(command);
EXPECT_EQ(commandResult, STRING_START_ABILITY_OK + "\n");
// uninstall the bundle
ToolSystemTest::UninstallBundle(STRING_SERVICE_ABILITY_BUNDLE_NAME);
}
/**
* @tc.number: Aa_Command_Start_SystemTest_0300
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa start -d <device-id> -a <ability-name> -b <bundle-name>" command.
*/
HWTEST_F(AaCommandStartSystemTest, Aa_Command_Start_SystemTest_0300, Function | MediumTest | Level1)
{
// start the invalid page ability
std::string command = "aa start -d " + STRING_DEVICE_NAME + " -a " + STRING_PAGE_ABILITY_NAME_INVALID + " -b " +
STRING_PAGE_ABILITY_BUNDLE_NAME_INVALID;
std::string commandResult = ToolSystemTest::ExecuteCommand(command);
EXPECT_EQ(commandResult, STRING_START_ABILITY_NG + "\n");
}
/**
* @tc.number: Aa_Command_Start_SystemTest_0400
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa start -d <device-id> -a <ability-name> -b <bundle-name>" command.
*/
HWTEST_F(AaCommandStartSystemTest, Aa_Command_Start_SystemTest_0400, Function | MediumTest | Level1)
{
// start the invalid service ability
std::string command = "aa start -d " + STRING_DEVICE_NAME + " -a " + STRING_SERVICE_ABILITY_NAME_INVALID + " -b " +
STRING_SERVICE_ABILITY_BUNDLE_NAME_INVALID;
std::string commandResult = ToolSystemTest::ExecuteCommand(command);
EXPECT_EQ(commandResult, STRING_START_ABILITY_NG + "\n");
}
| 38.171233 | 119 | 0.746636 | openharmony-gitee-mirror |
2cd1ac3fb25fb98b56eaa28c3651066337683585 | 5,618 | cpp | C++ | Engine/Source/Runtime/Projects/Private/PluginReferenceDescriptor.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Projects/Private/PluginReferenceDescriptor.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Projects/Private/PluginReferenceDescriptor.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "PluginReferenceDescriptor.h"
#include "Misc/FileHelper.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
#include "ProjectDescriptor.h"
#define LOCTEXT_NAMESPACE "PluginDescriptor"
FPluginReferenceDescriptor::FPluginReferenceDescriptor( const FString& InName, bool bInEnabled )
: Name(InName)
, bEnabled(bInEnabled)
, bOptional(false)
{ }
bool FPluginReferenceDescriptor::IsEnabledForPlatform( const FString& Platform ) const
{
// If it's not enabled at all, return false
if(!bEnabled)
{
return false;
}
// If there is a list of whitelisted platforms, and this isn't one of them, return false
if(WhitelistPlatforms.Num() > 0 && !WhitelistPlatforms.Contains(Platform))
{
return false;
}
// If this platform is blacklisted, also return false
if(BlacklistPlatforms.Contains(Platform))
{
return false;
}
return true;
}
bool FPluginReferenceDescriptor::IsEnabledForTarget(const FString& Target) const
{
// If it's not enabled at all, return false
if (!bEnabled)
{
return false;
}
// If there is a list of whitelisted platforms, and this isn't one of them, return false
if (WhitelistTargets.Num() > 0 && !WhitelistTargets.Contains(Target))
{
return false;
}
// If this platform is blacklisted, also return false
if (BlacklistTargets.Contains(Target))
{
return false;
}
return true;
}
bool FPluginReferenceDescriptor::IsSupportedTargetPlatform(const FString& Platform) const
{
return SupportedTargetPlatforms.Num() == 0 || SupportedTargetPlatforms.Contains(Platform);
}
bool FPluginReferenceDescriptor::Read( const FJsonObject& Object, FText& OutFailReason )
{
// Get the name
if(!Object.TryGetStringField(TEXT("Name"), Name))
{
OutFailReason = LOCTEXT("PluginReferenceWithoutName", "Plugin references must have a 'Name' field");
return false;
}
// Get the enabled field
if(!Object.TryGetBoolField(TEXT("Enabled"), bEnabled))
{
OutFailReason = LOCTEXT("PluginReferenceWithoutEnabled", "Plugin references must have an 'Enabled' field");
return false;
}
// Read the optional field
Object.TryGetBoolField(TEXT("Optional"), bOptional);
// Read the metadata for users that don't have the plugin installed
Object.TryGetStringField(TEXT("Description"), Description);
Object.TryGetStringField(TEXT("MarketplaceURL"), MarketplaceURL);
// Get the platform lists
Object.TryGetStringArrayField(TEXT("WhitelistPlatforms"), WhitelistPlatforms);
Object.TryGetStringArrayField(TEXT("BlacklistPlatforms"), BlacklistPlatforms);
// Get the target lists
Object.TryGetStringArrayField(TEXT("WhitelistTargets"), WhitelistTargets);
Object.TryGetStringArrayField(TEXT("BlacklistTargets"), BlacklistTargets);
// Get the supported platform list
Object.TryGetStringArrayField(TEXT("SupportedTargetPlatforms"), SupportedTargetPlatforms);
return true;
}
bool FPluginReferenceDescriptor::ReadArray( const FJsonObject& Object, const TCHAR* Name, TArray<FPluginReferenceDescriptor>& OutPlugins, FText& OutFailReason )
{
const TArray< TSharedPtr<FJsonValue> > *Array;
if (Object.TryGetArrayField(Name, Array))
{
for (const TSharedPtr<FJsonValue> &Item : *Array)
{
const TSharedPtr<FJsonObject> *ObjectPtr;
if (Item.IsValid() && Item->TryGetObject(ObjectPtr))
{
FPluginReferenceDescriptor Plugin;
if (!Plugin.Read(*ObjectPtr->Get(), OutFailReason))
{
return false;
}
OutPlugins.Add(Plugin);
}
}
}
return true;
}
void FPluginReferenceDescriptor::Write( TJsonWriter<>& Writer ) const
{
Writer.WriteObjectStart();
Writer.WriteValue(TEXT("Name"), Name);
Writer.WriteValue(TEXT("Enabled"), bEnabled);
if (bEnabled && bOptional)
{
Writer.WriteValue(TEXT("Optional"), bOptional);
}
if (Description.Len() > 0)
{
Writer.WriteValue(TEXT("Description"), Description);
}
if (MarketplaceURL.Len() > 0)
{
Writer.WriteValue(TEXT("MarketplaceURL"), MarketplaceURL);
}
if (WhitelistPlatforms.Num() > 0)
{
Writer.WriteArrayStart(TEXT("WhitelistPlatforms"));
for (int Idx = 0; Idx < WhitelistPlatforms.Num(); Idx++)
{
Writer.WriteValue(WhitelistPlatforms[Idx]);
}
Writer.WriteArrayEnd();
}
if (BlacklistPlatforms.Num() > 0)
{
Writer.WriteArrayStart(TEXT("BlacklistPlatforms"));
for (int Idx = 0; Idx < BlacklistPlatforms.Num(); Idx++)
{
Writer.WriteValue(BlacklistPlatforms[Idx]);
}
Writer.WriteArrayEnd();
}
if (WhitelistTargets.Num() > 0)
{
Writer.WriteArrayStart(TEXT("WhitelistTargets"));
for (int Idx = 0; Idx < WhitelistTargets.Num(); Idx++)
{
Writer.WriteValue(WhitelistTargets[Idx]);
}
Writer.WriteArrayEnd();
}
if (BlacklistTargets.Num() > 0)
{
Writer.WriteArrayStart(TEXT("BlacklistTargets"));
for (int Idx = 0; Idx < BlacklistTargets.Num(); Idx++)
{
Writer.WriteValue(BlacklistTargets[Idx]);
}
Writer.WriteArrayEnd();
}
if (SupportedTargetPlatforms.Num() > 0)
{
Writer.WriteArrayStart(TEXT("SupportedTargetPlatforms"));
for (int Idx = 0; Idx < SupportedTargetPlatforms.Num(); Idx++)
{
Writer.WriteValue(SupportedTargetPlatforms[Idx]);
}
Writer.WriteArrayEnd();
}
Writer.WriteObjectEnd();
}
void FPluginReferenceDescriptor::WriteArray( TJsonWriter<>& Writer, const TCHAR* Name, const TArray<FPluginReferenceDescriptor>& Plugins )
{
if( Plugins.Num() > 0)
{
Writer.WriteArrayStart(Name);
for (int Idx = 0; Idx < Plugins.Num(); Idx++)
{
Plugins[Idx].Write(Writer);
}
Writer.WriteArrayEnd();
}
}
#undef LOCTEXT_NAMESPACE
| 23.805085 | 160 | 0.719829 | windystrife |
2cd2b742faf6023ff160a7276bbbf12f21043749 | 554 | cc | C++ | BetaScatt/src/PadEventAction.cc | eric-presbitero/BetaScatt | 3dc27e088483d6c34f714825a76439382ea08204 | [
"MIT"
] | 5 | 2020-10-14T09:45:57.000Z | 2022-02-08T10:45:59.000Z | BetaScatt/src/PadEventAction.cc | eric-presbitero/BetaScatt | 3dc27e088483d6c34f714825a76439382ea08204 | [
"MIT"
] | null | null | null | BetaScatt/src/PadEventAction.cc | eric-presbitero/BetaScatt | 3dc27e088483d6c34f714825a76439382ea08204 | [
"MIT"
] | null | null | null | #ifdef G4ANALYSIS_USE
#include "PadAnalysisManager.hh"
#endif
#include "PadEventAction.hh"
PadEventAction::PadEventAction(
PadAnalysisManager* aAnalysisManager
):fAnalysisManager(aAnalysisManager){}
PadEventAction::~PadEventAction(){}
void PadEventAction::BeginOfEventAction(const G4Event* aEvent){
#ifdef G4ANALYSIS_USE
if(fAnalysisManager) fAnalysisManager->BeginOfEvent(aEvent);
#endif
}
void PadEventAction::EndOfEventAction(const G4Event* aEvent) {
#ifdef G4ANALYSIS_USE
if(fAnalysisManager) fAnalysisManager->EndOfEvent(aEvent);
#endif
}
| 23.083333 | 63 | 0.815884 | eric-presbitero |
2cd524148cb8c4d18e66358a72d90effe06160dc | 2,062 | cpp | C++ | examples/dfa/src/dfa_layer.cpp | ktnyt/LAPlus | d750862c758a2d6fa3acc5b2b567efc05008b5ae | [
"MIT"
] | null | null | null | examples/dfa/src/dfa_layer.cpp | ktnyt/LAPlus | d750862c758a2d6fa3acc5b2b567efc05008b5ae | [
"MIT"
] | null | null | null | examples/dfa/src/dfa_layer.cpp | ktnyt/LAPlus | d750862c758a2d6fa3acc5b2b567efc05008b5ae | [
"MIT"
] | null | null | null | /******************************************************************************
*
* dfa_layer.cpp
*
* MIT License
*
* Copyright (c) 2016 Kotone Itaya
*
* 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 "dfa_layer.hpp"
#include <cmath>
namespace lp = laplus;
DFALayer::DFALayer(const std::size_t n_input,
const std::size_t n_output,
const std::size_t n_final)
: W(lp::Matrixf::Normal(n_input, n_output, 0.0, std::sqrt((float)n_input)))
, B(lp::Matrixf::Normal(n_final, n_output, 0.0, std::sqrt((float)n_final)))
{
W /= std::sqrt(static_cast<float>(n_input));
B /= std::sqrt(static_cast<float>(n_final));
}
lp::Matrixf DFALayer::operator()(lp::Matrixf x)
{ return x.dot(W).apply(lp::sigmoid); }
void DFALayer::update(lp::Matrixf e, lp::Matrixf x, lp::Matrixf y, float lr)
{
lp::Matrixf d_x = e.dot(B) * y.apply(lp::dsigmoid);
lp::Matrixf d_W = -x.transpose().dot(d_x);
W += d_W * lr;
}
| 38.90566 | 79 | 0.654219 | ktnyt |
2cd56cb89fd0767da7a50c9e43b3f01b3ec777aa | 2,362 | cpp | C++ | libs/interprocess/test/intermodule_singleton_test.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/interprocess/test/intermodule_singleton_test.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/interprocess/test/intermodule_singleton_test.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/intermodule_singleton.hpp>
#include <iostream>
using namespace boost::interprocess;
class MyClass
{
public:
MyClass()
{
std::cout << "Constructor\n";
}
void shout() const
{
std::cout << "Shout\n";
}
~MyClass()
{
std::cout << "Destructor\n";
}
};
class MyDerivedClass
: public MyClass
{};
class MyThrowingClass
{
public:
MyThrowingClass()
{
throw int(0);
}
};
template < template<class, bool = false> class IntermoduleType >
int intermodule_singleton_test()
{
bool exception_thrown = false;
bool exception_2_thrown = false;
try{
IntermoduleType<MyThrowingClass, true>::get();
}
catch(int &){
exception_thrown = true;
//Second try
try{
IntermoduleType<MyThrowingClass, true>::get();
}
catch(interprocess_exception &){
exception_2_thrown = true;
}
}
if(!exception_thrown || !exception_2_thrown){
return 1;
}
MyClass & mc = IntermoduleType<MyClass>::get();
mc.shout();
IntermoduleType<MyClass>::get().shout();
IntermoduleType<MyDerivedClass>::get().shout();
//Second try
exception_2_thrown = false;
try{
IntermoduleType<MyThrowingClass, true>::get();
}
catch(interprocess_exception &){
exception_2_thrown = true;
}
if(!exception_2_thrown){
return 1;
}
return 0;
}
int main ()
{
if(0 != intermodule_singleton_test<ipcdetail::portable_intermodule_singleton>()){
return 1;
}
#ifdef BOOST_INTERPROCESS_WINDOWS
if(0 != intermodule_singleton_test<ipcdetail::windows_intermodule_singleton>()){
return 1;
}
#endif
return 0;
}
#include <boost/interprocess/detail/config_end.hpp>
| 21.472727 | 85 | 0.578323 | Ron2014 |
2cd7cf85017d8c97a5a3a16b7d89b7552d83b960 | 1,359 | cpp | C++ | src/617.merge-two-binary-trees.cpp | Hilbert-Yaa/heil-my-lc | 075567698e3b826a542f63389e9a8f3136df799a | [
"MIT"
] | null | null | null | src/617.merge-two-binary-trees.cpp | Hilbert-Yaa/heil-my-lc | 075567698e3b826a542f63389e9a8f3136df799a | [
"MIT"
] | null | null | null | src/617.merge-two-binary-trees.cpp | Hilbert-Yaa/heil-my-lc | 075567698e3b826a542f63389e9a8f3136df799a | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=617 lang=cpp
*
* [617] Merge Two Binary Trees
*/
#include <bits/stdc++.h>
#using namespace std;
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==nullptr && root2==nullptr) return nullptr;
else if(root1==nullptr) return root2;
else if(root2==nullptr) return root1;
else {
return new TreeNode(root1->val + root2->val, mergeTrees(root1->left, root2->left), mergeTrees(root1->right,root2->right));
} // * there might be memory problems, since I don't have the implementation of constructors...
/* could be faster if replacing the else block with expanded code:
* else {
* TreeNode* root = new TreeNode(root1->val + root2->val);
* root->left = mergeTrees(root1->left, root2->left);
* root->right = mergeTrees(root1->right,root2->right);
* return root;
* }
*/
}
};
// @lc code=end
| 33.146341 | 134 | 0.597498 | Hilbert-Yaa |
2cda2623e923f4dc411d197b1b6e215b64a3f9aa | 35,118 | cpp | C++ | hip/hip/kernels/share/qDataUpdateS.cpp | artv3/Laghos | 64449d427349b0ca35086a63ae4e7d1ed5894f08 | [
"BSD-2-Clause"
] | 1 | 2019-11-20T21:45:18.000Z | 2019-11-20T21:45:18.000Z | hip/hip/kernels/share/qDataUpdateS.cpp | jeffhammond/Laghos | 12e62aa7eb6175f27380106b40c9286d710a0f52 | [
"BSD-2-Clause"
] | null | null | null | hip/hip/kernels/share/qDataUpdateS.cpp | jeffhammond/Laghos | 12e62aa7eb6175f27380106b40c9286d710a0f52 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#include "../hip.hpp"
// *****************************************************************************
template<const int NUM_DIM,
const int NUM_QUAD,
const int NUM_QUAD_1D,
const int NUM_DOFS_1D> kernel
void rUpdateQuadratureData2S(const double GAMMA,
const double H0,
const double CFL,
const bool USE_VISCOSITY,
const int numElements,
const double* restrict dofToQuad,
const double* restrict dofToQuadD,
const double* restrict quadWeights,
const double* restrict v,
const double* restrict e,
const double* restrict rho0DetJ0w,
const double* restrict invJ0,
const double* restrict J,
const double* restrict invJ,
const double* restrict detJ,
double* restrict stressJinvT,
double* restrict dtEst)
{
const int NUM_QUAD_2D = NUM_QUAD_1D*NUM_QUAD_1D;
const int NUM_QUAD_DOFS_1D = (NUM_QUAD_1D * NUM_DOFS_1D);
const int NUM_MAX_1D = (NUM_QUAD_1D<NUM_DOFS_1D)?NUM_DOFS_1D:NUM_QUAD_1D;
const int idx = blockIdx.x;
const int el = idx;
if (el < numElements)
{
share double s_dofToQuad[NUM_QUAD_DOFS_1D];//@dim(NUM_QUAD_1D, NUM_DOFS_1D);
share double s_dofToQuadD[NUM_QUAD_DOFS_1D];//@dim(NUM_QUAD_1D, NUM_DOFS_1D);
share double s_xy[NUM_DIM *
NUM_QUAD_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D, NUM_QUAD_1D);
share double s_xDy[NUM_DIM *
NUM_QUAD_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D, NUM_QUAD_1D);
share double s_gradv[NUM_DIM * NUM_DIM *
NUM_QUAD_2D];//@dim(NUM_DIM, NUM_DIM, NUM_QUAD_2D);
double r_v[NUM_DIM * NUM_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D);
{
const int x = threadIdx.x;
for (int id = x; id < NUM_QUAD_DOFS_1D; id += NUM_MAX_1D)
{
s_dofToQuad[id] = dofToQuad[id];
s_dofToQuadD[id] = dofToQuadD[id];
}
}
sync;
{
const int dx = threadIdx.x;
if (dx < NUM_DOFS_1D)
{
for (int qy = 0; qy < NUM_QUAD_1D; ++qy)
{
for (int vi = 0; vi < NUM_DIM; ++vi)
{
s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = 0;
s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = 0;
}
}
for (int dy = 0; dy < NUM_DOFS_1D; ++dy)
{
for (int vi = 0; vi < NUM_DIM; ++vi)
{
r_v[ijN(vi, dy,NUM_DIM)] = v[_ijklNM(vi,dx,dy,el,NUM_DOFS_1D,numElements)];
}
}
for (int qy = 0; qy < NUM_QUAD_1D; ++qy)
{
double xy[NUM_DIM];
double xDy[NUM_DIM];
for (int vi = 0; vi < NUM_DIM; ++vi)
{
xy[vi] = 0;
xDy[vi] = 0;
}
for (int dy = 0; dy < NUM_DOFS_1D; ++dy)
{
for (int vi = 0; vi < NUM_DIM; ++vi)
{
xy[vi] += r_v[ijN(vi, dy,NUM_DIM)] * s_dofToQuad[ijN(qy,dy,NUM_QUAD_1D)];
xDy[vi] += r_v[ijN(vi, dy,NUM_DIM)] * s_dofToQuadD[ijN(qy,dy,NUM_QUAD_1D)];
}
}
for (int vi = 0; vi < NUM_DIM; ++vi)
{
s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = xy[vi];
s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = xDy[vi];
}
}
}
}
sync;
{
const int qy = threadIdx.x;
if (qy < NUM_QUAD_1D)
{
for (int qx = 0; qx < NUM_MAX_1D; ++qx)
{
double gradX[NUM_DIM];
double gradY[NUM_DIM];
for (int vi = 0; vi < NUM_DIM; ++vi)
{
gradX[vi] = 0;
gradY[vi] = 0;
}
for (int dx = 0; dx < NUM_DOFS_1D; ++dx)
{
for (int vi = 0; vi < NUM_DIM; ++vi)
{
gradX[vi] += s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] * s_dofToQuadD[ijN(qx,
dx,NUM_QUAD_1D)];
gradY[vi] += s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] * s_dofToQuad[ijN(qx,
dx,NUM_QUAD_1D)];
}
}
for (int vi = 0; vi < NUM_DIM; ++vi)
{
s_gradv[ijkN(vi, 0, qx + qy*NUM_QUAD_1D,NUM_DIM)] = gradX[vi];
s_gradv[ijkN(vi, 1, qx + qy*NUM_QUAD_1D,NUM_DIM)] = gradY[vi];
}
}
}
}
sync;
{
const int qBlock = threadIdx.x;
for (int q = qBlock; q < NUM_QUAD; q += NUM_MAX_1D)
{
double q_gradv[NUM_DIM * NUM_DIM];//@dim(NUM_DIM, NUM_DIM);
double q_stress[NUM_DIM * NUM_DIM];//@dim(NUM_DIM, NUM_DIM);
const double invJ_00 = invJ[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)];
const double invJ_10 = invJ[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)];
const double invJ_01 = invJ[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)];
const double invJ_11 = invJ[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)];
q_gradv[ijN(0,0,2)] = ((s_gradv[ijkN(0,0,q,2)]*invJ_00) + (s_gradv[ijkN(1,0,q,
2)]*invJ_01));
q_gradv[ijN(1,0,2)] = ((s_gradv[ijkN(0,0,q,2)]*invJ_10) + (s_gradv[ijkN(1,0,q,
2)]*invJ_11));
q_gradv[ijN(0,1,2)] = ((s_gradv[ijkN(0,1,q,2)]*invJ_00) + (s_gradv[ijkN(1,1,q,
2)]*invJ_01));
q_gradv[ijN(1,1,2)] = ((s_gradv[ijkN(0,1,q,2)]*invJ_10) + (s_gradv[ijkN(1,1,q,
2)]*invJ_11));
const double q_Jw = detJ[ijN(q,el,NUM_QUAD)]*quadWeights[q];
const double q_rho = rho0DetJ0w[ijN(q,el,NUM_QUAD)]/q_Jw;
const double q_e = fmax(0.0,e[ijN(q,el,NUM_QUAD)]);
// TODO: Input OccaVector eos(q,e) -> (stress, soundSpeed)
const double s = -(GAMMA - 1.0) * q_rho * q_e;
q_stress[ijN(0,0,2)] = s; q_stress[ijN(1,0,2)] = 0;
q_stress[ijN(0,1,2)] = 0; q_stress[ijN(1,1,2)] = s;
const double gradv00 = q_gradv[ijN(0,0,2)];
const double gradv11 = q_gradv[ijN(1,1,2)];
const double gradv10 = 0.5 * (q_gradv[ijN(1,0,2)] + q_gradv[ijN(0,1,2)]);
q_gradv[ijN(1,0,2)] = gradv10;
q_gradv[ijN(0,1,2)] = gradv10;
double comprDirX = 1;
double comprDirY = 0;
double minEig = 0;
// linalg/densemat.cpp: Eigensystem2S()
if (gradv10 == 0)
{
minEig = (gradv00 < gradv11) ? gradv00 : gradv11;
}
else
{
const double zeta = (gradv11 - gradv00) / (2.0 * gradv10);
const double azeta = fabs(zeta);
double t = 1.0 / (azeta + sqrt(1.0 + zeta*zeta));
if ((t < 0) != (zeta < 0))
{
t = -t;
}
const double c = sqrt(1.0 / (1.0 + t*t));
const double s = c * t;
t *= gradv10;
if ((gradv00 - t) <= (gradv11 + t))
{
minEig = gradv00 - t;
comprDirX = c;
comprDirY = -s;
}
else
{
minEig = gradv11 + t;
comprDirX = s;
comprDirY = c;
}
}
// Computes the initial->physical transformation Jacobian.
const double J_00 = J[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)];
const double J_10 = J[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)];
const double J_01 = J[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)];
const double J_11 = J[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)];
const double invJ0_00 = invJ0[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)];
const double invJ0_10 = invJ0[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)];
const double invJ0_01 = invJ0[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)];
const double invJ0_11 = invJ0[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)];
const double Jpi_00 = ((J_00 * invJ0_00) + (J_10 * invJ0_01));
const double Jpi_10 = ((J_00 * invJ0_10) + (J_10 * invJ0_11));
const double Jpi_01 = ((J_01 * invJ0_00) + (J_11 * invJ0_01));
const double Jpi_11 = ((J_01 * invJ0_10) + (J_11 * invJ0_11));
const double physDirX = (Jpi_00 * comprDirX) + (Jpi_10 * comprDirY);
const double physDirY = (Jpi_01 * comprDirX) + (Jpi_11 * comprDirY);
const double q_h = H0 * sqrt((physDirX * physDirX) + (physDirY * physDirY));
// TODO: soundSpeed will be an input as well (function call or values per q)
const double soundSpeed = sqrt(GAMMA * (GAMMA - 1.0) * q_e);
dtEst[ijN(q, el,NUM_QUAD)] = CFL * q_h / soundSpeed;
if (USE_VISCOSITY)
{
// TODO: Check how we can extract outside of kernel
const double mu = minEig;
double coeff = 2.0 * q_rho * q_h * q_h * fabs(mu);
if (mu < 0)
{
coeff += 0.5 * q_rho * q_h * soundSpeed;
}
for (int y = 0; y < NUM_DIM; ++y)
{
for (int x = 0; x < NUM_DIM; ++x)
{
q_stress[ijN(x,y,2)] += coeff * q_gradv[ijN(x,y,2)];
}
}
}
const double S00 = q_stress[ijN(0,0,2)];
const double S10 = q_stress[ijN(1,0,2)];
const double S01 = q_stress[ijN(0,1,2)];
const double S11 = q_stress[ijN(1,1,2)];
stressJinvT[ijklNM(0,0,q,el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S00 * invJ_00) + (S10 * invJ_01));
stressJinvT[ijklNM(1,0,q,el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S00 * invJ_10) + (S10 * invJ_11));
stressJinvT[ijklNM(0,1,q,el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S01 * invJ_00) + (S11 * invJ_01));
stressJinvT[ijklNM(1,1,q,el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S01 * invJ_10) + (S11 * invJ_11));
}
}
}
}
// *****************************************************************************
template<const int NUM_DIM,
const int NUM_QUAD,
const int NUM_QUAD_1D,
const int NUM_DOFS_1D> kernel
void rUpdateQuadratureData3S(const double GAMMA,
const double H0,
const double CFL,
const bool USE_VISCOSITY,
const int numElements,
const double* restrict dofToQuad,
const double* restrict dofToQuadD,
const double* restrict quadWeights,
const double* restrict v,
const double* restrict e,
const double* restrict rho0DetJ0w,
const double* restrict invJ0,
const double* restrict J,
const double* restrict invJ,
const double* restrict detJ,
double* restrict stressJinvT,
double* restrict dtEst)
{
const int NUM_QUAD_2D = NUM_QUAD_1D*NUM_QUAD_1D;
const int NUM_QUAD_DOFS_1D = (NUM_QUAD_1D * NUM_DOFS_1D);
const int el = blockIdx.x;
if (el < numElements)
{
share double s_dofToQuad[NUM_QUAD_DOFS_1D];
share double s_dofToQuadD[NUM_QUAD_DOFS_1D];
{
const int y = threadIdx.y;
{
const int x = threadIdx.x;
const int id = (y * NUM_QUAD_1D) + x;
for (int i = id; i < (NUM_DOFS_1D * NUM_QUAD_1D); i += NUM_QUAD_2D)
{
s_dofToQuad[id] = dofToQuad[id];
s_dofToQuadD[id] = dofToQuadD[id];
}
}
}
sync;
for (int qz = 0; qz < NUM_QUAD_1D; ++qz)
{
{
const int qy = threadIdx.y;
{
const int qx = 0 + threadIdx.x;
const int q = qx + qy*NUM_QUAD_1D + qz*NUM_QUAD_2D;
double gradv[9];
double q_gradv[9];
double q_stress[9];
// Brute-force convertion of dof -> quad for now
for (int i = 0; i < 9; ++i)
{
gradv[i] = 0;
}
for (int dz = 0; dz < NUM_DOFS_1D; ++dz)
{
double xy[3];
double Dxy[3];
double xDy[3];
for (int vi = 0; vi < 3; ++vi)
{
xy[vi] = Dxy[vi] = xDy[vi] = 0;
}
for (int dy = 0; dy < NUM_DOFS_1D; ++dy)
{
double x[3];
double Dx[3];
for (int vi = 0; vi < 3; ++vi)
{
x[vi] = Dx[vi] = 0;
}
for (int dx = 0; dx < NUM_DOFS_1D; ++dx)
{
const double wx = s_dofToQuad[ijN(qx,dx,NUM_QUAD_1D)];
const double wDx = s_dofToQuadD[ijN(qx,dx,NUM_QUAD_1D)];
for (int vi = 0; vi < 3; ++vi)
{
const double r_v = v[_ijklmNM(vi,dx,dy,dz,el,NUM_DOFS_1D,numElements)];
x[vi] += wx * r_v;
Dx[vi] += wDx * r_v;
}
}
const double wy = s_dofToQuad[ijN(qy,dy,NUM_QUAD_1D)];
const double wDy = s_dofToQuadD[ijN(qy,dy,NUM_QUAD_1D)];
for (int vi = 0; vi < 3; ++vi)
{
xy[vi] += wy * x[vi];
Dxy[vi] += wy * Dx[vi];
xDy[vi] += wDy * x[vi];
}
}
const double wz = s_dofToQuad[ijN(qz,dz,NUM_QUAD_1D)];
const double wDz = s_dofToQuadD[ijN(qz,dz,NUM_QUAD_1D)];
for (int vi = 0; vi < 3; ++vi)
{
gradv[ijN(vi,0,3)] += wz * Dxy[vi];
gradv[ijN(vi,1,3)] += wz * xDy[vi];
gradv[ijN(vi,2,3)] += wDz * xy[vi];
}
}
const double invJ_00 = invJ[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_10 = invJ[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_20 = invJ[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_01 = invJ[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_11 = invJ[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_21 = invJ[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_02 = invJ[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_12 = invJ[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)];
const double invJ_22 = invJ[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)];
q_gradv[ijN(0,0,3)] = ((gradv[ijN(0,0,3)] * invJ_00) + (gradv[ijN(1,0,
3)] * invJ_01) + (gradv[ijN(2,0,3)] * invJ_02));
q_gradv[ijN(1,0,3)] = ((gradv[ijN(0,0,3)] * invJ_10) + (gradv[ijN(1,0,
3)] * invJ_11) + (gradv[ijN(2,0,3)] * invJ_12));
q_gradv[ijN(2,0,3)] = ((gradv[ijN(0,0,3)] * invJ_20) + (gradv[ijN(1,0,
3)] * invJ_21) + (gradv[ijN(2,0,3)] * invJ_22));
q_gradv[ijN(0,1,3)] = ((gradv[ijN(0,1,3)] * invJ_00) + (gradv[ijN(1,1,
3)] * invJ_01) + (gradv[ijN(2,1,3)] * invJ_02));
q_gradv[ijN(1,1,3)] = ((gradv[ijN(0,1,3)] * invJ_10) + (gradv[ijN(1,1,
3)] * invJ_11) + (gradv[ijN(2,1,3)] * invJ_12));
q_gradv[ijN(2,1,3)] = ((gradv[ijN(0,1,3)] * invJ_20) + (gradv[ijN(1,1,
3)] * invJ_21) + (gradv[ijN(2,1,3)] * invJ_22));
q_gradv[ijN(0,2,3)] = ((gradv[ijN(0,2,3)] * invJ_00) + (gradv[ijN(1,2,
3)] * invJ_01) + (gradv[ijN(2,2,3)] * invJ_02));
q_gradv[ijN(1,2,3)] = ((gradv[ijN(0,2,3)] * invJ_10) + (gradv[ijN(1,2,
3)] * invJ_11) + (gradv[ijN(2,2,3)] * invJ_12));
q_gradv[ijN(2,2,3)] = ((gradv[ijN(0,2,3)] * invJ_20) + (gradv[ijN(1,2,
3)] * invJ_21) + (gradv[ijN(2,2,3)] * invJ_22));
const double q_Jw = detJ[ijN(q,el,NUM_QUAD)] * quadWeights[q];
const double q_rho = rho0DetJ0w[ijN(q,el,NUM_QUAD)] / q_Jw;
const double q_e = fmax(0.0, e[ijN(q,el,NUM_QUAD)]);
const double s = -(GAMMA - 1.0) * q_rho * q_e;
q_stress[ijN(0, 0,3)] = s; q_stress[ijN(1, 0,3)] = 0; q_stress[ijN(2, 0,3)] = 0;
q_stress[ijN(0, 1,3)] = 0; q_stress[ijN(1, 1,3)] = s; q_stress[ijN(2, 1,3)] = 0;
q_stress[ijN(0, 2,3)] = 0; q_stress[ijN(1, 2,3)] = 0; q_stress[ijN(2, 2,3)] = s;
const double gradv00 = q_gradv[ijN(0, 0,3)];
const double gradv11 = q_gradv[ijN(1, 1,3)];
const double gradv22 = q_gradv[ijN(2, 2,3)];
const double gradv10 = 0.5 * (q_gradv[ijN(1, 0,3)] + q_gradv[ijN(0, 1,3)]);
const double gradv20 = 0.5 * (q_gradv[ijN(2, 0,3)] + q_gradv[ijN(0, 2,3)]);
const double gradv21 = 0.5 * (q_gradv[ijN(2, 1,3)] + q_gradv[ijN(1, 2,3)]);
q_gradv[ijN(1, 0,3)] = gradv10; q_gradv[ijN(2, 0,3)] = gradv20;
q_gradv[ijN(0, 1,3)] = gradv10; q_gradv[ijN(2, 1,3)] = gradv21;
q_gradv[ijN(0, 2,3)] = gradv20; q_gradv[ijN(1, 2,3)] = gradv21;
double minEig = 0;
double comprDirX = 1;
double comprDirY = 0;
double comprDirZ = 0;
{
// Compute eigenvalues using quadrature formula
const double q_ = (gradv00 + gradv11 + gradv22) / 3.0;
const double gradv_q00 = (gradv00 - q_);
const double gradv_q11 = (gradv11 - q_);
const double gradv_q22 = (gradv22 - q_);
const double p1 = ((gradv10 * gradv10) +
(gradv20 * gradv20) +
(gradv21 * gradv21));
const double p2 = ((gradv_q00 * gradv_q00) +
(gradv_q11 * gradv_q11) +
(gradv_q22 * gradv_q22) +
(2.0 * p1));
const double p = sqrt(p2 / 6.0);
const double pinv = 1.0 / p;
// det(pinv * (gradv - q*I))
const double r = (0.5 * pinv * pinv * pinv *
((gradv_q00 * gradv_q11 * gradv_q22) +
(2.0 * gradv10 * gradv21 * gradv20) -
(gradv_q11 * gradv20 * gradv20) -
(gradv_q22 * gradv10 * gradv10) -
(gradv_q00 * gradv21 * gradv21)));
double phi = 0;
if (r <= -1.0)
{
phi = M_PI / 3.0;
}
else if (r < 1.0)
{
phi = acos(r) / 3.0;
}
minEig = q_ + (2.0 * p * cos(phi + (2.0 * M_PI / 3.0)));
const double eig3 = q_ + (2.0 * p * cos(phi));
const double eig2 = 3.0 * q_ - minEig - eig3;
double maxNorm = 0;
for (int i = 0; i < 3; ++i)
{
const double x = q_gradv[i + 3*0] - (i == 0)*eig3;
const double y = q_gradv[i + 3*1] - (i == 1)*eig3;
const double z = q_gradv[i + 3*2] - (i == 2)*eig3;
const double cx = ((x * (gradv00 - eig2)) +
(y * gradv10) +
(z * gradv20));
const double cy = ((x * gradv10) +
(y * (gradv11 - eig2)) +
(z * gradv21));
const double cz = ((x * gradv20) +
(y * gradv21) +
(z * (gradv22 - eig2)));
const double cNorm = (cx*cx + cy*cy + cz*cz);
if ((cNorm > 1e-16) && (maxNorm < cNorm))
{
comprDirX = cx;
comprDirY = cy;
comprDirZ = cz;
maxNorm = cNorm;
}
}
if (maxNorm > 1e-16)
{
const double maxNormInv = 1.0 / sqrt(maxNorm);
comprDirX *= maxNormInv;
comprDirY *= maxNormInv;
comprDirZ *= maxNormInv;
}
}
// Computes the initial->physical transformation Jacobian.
const double J_00 = J[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)];
const double J_10 = J[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)];
const double J_20 = J[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)];
const double J_01 = J[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)];
const double J_11 = J[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)];
const double J_21 = J[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)];
const double J_02 = J[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)];
const double J_12 = J[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)];
const double J_22 = J[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_00 = invJ0[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_10 = invJ0[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_20 = invJ0[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_01 = invJ0[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_11 = invJ0[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_21 = invJ0[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_02 = invJ0[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_12 = invJ0[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)];
const double invJ0_22 = invJ0[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)];
const double Jpi_00 = ((J_00 * invJ0_00) + (J_10 * invJ0_01) +
(J_20 * invJ0_02));
const double Jpi_10 = ((J_00 * invJ0_10) + (J_10 * invJ0_11) +
(J_20 * invJ0_12));
const double Jpi_20 = ((J_00 * invJ0_20) + (J_10 * invJ0_21) +
(J_20 * invJ0_22));
const double Jpi_01 = ((J_01 * invJ0_00) + (J_11 * invJ0_01) +
(J_21 * invJ0_02));
const double Jpi_11 = ((J_01 * invJ0_10) + (J_11 * invJ0_11) +
(J_21 * invJ0_12));
const double Jpi_21 = ((J_01 * invJ0_20) + (J_11 * invJ0_21) +
(J_21 * invJ0_22));
const double Jpi_02 = ((J_02 * invJ0_00) + (J_12 * invJ0_01) +
(J_22 * invJ0_02));
const double Jpi_12 = ((J_02 * invJ0_10) + (J_12 * invJ0_11) +
(J_22 * invJ0_12));
const double Jpi_22 = ((J_02 * invJ0_20) + (J_12 * invJ0_21) +
(J_22 * invJ0_22));
const double physDirX = ((Jpi_00 * comprDirX) + (Jpi_10 * comprDirY) +
(Jpi_20 * comprDirZ));
const double physDirY = ((Jpi_01 * comprDirX) + (Jpi_11 * comprDirY) +
(Jpi_21 * comprDirZ));
const double physDirZ = ((Jpi_02 * comprDirX) + (Jpi_12 * comprDirY) +
(Jpi_22 * comprDirZ));
const double q_h = H0 * sqrt((physDirX * physDirX) + (physDirY * physDirY) +
(physDirZ * physDirZ));
const double soundSpeed = sqrt(GAMMA * (GAMMA - 1.0) * q_e);
dtEst[ijN(q, el,NUM_QUAD)] = CFL * q_h / soundSpeed;
if (USE_VISCOSITY)
{
// TODO: Check how we can extract outside of kernel
const double mu = minEig;
double coeff = 2.0 * q_rho * q_h * q_h * fabs(mu);
if (mu < 0)
{
coeff += 0.5 * q_rho * q_h * soundSpeed;
}
for (int y = 0; y < 3; ++y)
{
for (int x = 0; x < 3; ++x)
{
q_stress[ijN(x, y,3)] += coeff * q_gradv[ijN(x, y,3)];
}
}
}
const double S00 = q_stress[ijN(0, 0,3)];
const double S10 = q_stress[ijN(1, 0,3)];
const double S20 = q_stress[ijN(2, 0,3)];
const double S01 = q_stress[ijN(0, 1,3)];
const double S11 = q_stress[ijN(1, 1,3)];
const double S21 = q_stress[ijN(2, 1,3)];
const double S02 = q_stress[ijN(0, 2,3)];
const double S12 = q_stress[ijN(1, 2,3)];
const double S22 = q_stress[ijN(2, 2,3)];
stressJinvT[ijklNM(0, 0, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S00 * invJ_00) + (S10 * invJ_01) + (S20 * invJ_02));
stressJinvT[ijklNM(1, 0, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S00 * invJ_10) + (S10 * invJ_11) + (S20 * invJ_12));
stressJinvT[ijklNM(2, 0, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S00 * invJ_20) + (S10 * invJ_21) + (S20 * invJ_22));
stressJinvT[ijklNM(0, 1, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S01 * invJ_00) + (S11 * invJ_01) + (S21 * invJ_02));
stressJinvT[ijklNM(1, 1, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S01 * invJ_10) + (S11 * invJ_11) + (S21 * invJ_12));
stressJinvT[ijklNM(2, 1, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S01 * invJ_20) + (S11 * invJ_21) + (S21 * invJ_22));
stressJinvT[ijklNM(0, 2, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S02 * invJ_00) + (S12 * invJ_01) + (S22 * invJ_02));
stressJinvT[ijklNM(1, 2, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S02 * invJ_10) + (S12 * invJ_11) + (S22 * invJ_12));
stressJinvT[ijklNM(2, 2, q, el,NUM_DIM,
NUM_QUAD)] = q_Jw * ((S02 * invJ_20) + (S12 * invJ_21) + (S22 * invJ_22));
}
}
}
}
}
// *****************************************************************************
typedef void (*fUpdateQuadratureDataS)(const double GAMMA,
const double H0,
const double CFL,
const bool USE_VISCOSITY,
const int numElements,
const double* restrict dofToQuad,
const double* restrict dofToQuadD,
const double* restrict quadWeights,
const double* restrict v,
const double* restrict e,
const double* restrict rho0DetJ0w,
const double* restrict invJ0,
const double* restrict J,
const double* restrict invJ,
const double* restrict detJ,
double* restrict stressJinvT,
double* restrict dtEst);
// *****************************************************************************
void rUpdateQuadratureDataS(const double GAMMA,
const double H0,
const double CFL,
const bool USE_VISCOSITY,
const int NUM_DIM,
const int NUM_QUAD,
const int NUM_QUAD_1D,
const int NUM_DOFS_1D,
const int nzones,
const double* restrict dofToQuad,
const double* restrict dofToQuadD,
const double* restrict quadWeights,
const double* restrict v,
const double* restrict e,
const double* restrict rho0DetJ0w,
const double* restrict invJ0,
const double* restrict J,
const double* restrict invJ,
const double* restrict detJ,
double* restrict stressJinvT,
double* restrict dtEst)
{
const int grid = nzones;
const int b1d = (NUM_QUAD_1D<NUM_DOFS_1D)?NUM_DOFS_1D:NUM_QUAD_1D;
const dim3 blck(b1d,b1d,1);
assert(LOG2(NUM_DIM)<=4);
assert(LOG2(NUM_DOFS_1D-2)<=4);
assert(NUM_QUAD_1D==2*(NUM_DOFS_1D-1));
assert(IROOT(NUM_DIM,NUM_QUAD)==NUM_QUAD_1D);
const unsigned int id = (NUM_DIM<<4)|(NUM_DOFS_1D-2);
static std::unordered_map<unsigned int,fUpdateQuadratureDataS> call =
{
// 2D
{0x20,&rUpdateQuadratureData2S<2,2*2,2,2>},
{0x21,&rUpdateQuadratureData2S<2,4*4,4,3>},
{0x22,&rUpdateQuadratureData2S<2,6*6,6,4>},
{0x23,&rUpdateQuadratureData2S<2,8*8,8,5>},
{0x24,&rUpdateQuadratureData2S<2,10*10,10,6>},
{0x25,&rUpdateQuadratureData2S<2,12*12,12,7>},
{0x26,&rUpdateQuadratureData2S<2,14*14,14,8>},
{0x27,&rUpdateQuadratureData2S<2,16*16,16,9>},
{0x28,&rUpdateQuadratureData2S<2,18*18,18,10>},
{0x29,&rUpdateQuadratureData2S<2,20*20,20,11>},
{0x2A,&rUpdateQuadratureData2S<2,22*22,22,12>},
{0x2B,&rUpdateQuadratureData2S<2,24*24,24,13>},
{0x2C,&rUpdateQuadratureData2S<2,26*26,26,14>},
{0x2D,&rUpdateQuadratureData2S<2,28*28,28,15>},
//{0x2E,&rUpdateQuadratureData2S<2,30*30,30,16>}, uses too much shared data
//{0x2F,&rUpdateQuadratureData2S<2,32*32,32,17>}, uses too much shared data
// 3D
{0x30,&rUpdateQuadratureData3S<3,2*2*2,2,2>},
{0x31,&rUpdateQuadratureData3S<3,4*4*4,4,3>},
{0x32,&rUpdateQuadratureData3S<3,6*6*6,6,4>},
{0x33,&rUpdateQuadratureData3S<3,8*8*8,8,5>},
{0x34,&rUpdateQuadratureData3S<3,10*10*10,10,6>},
{0x35,&rUpdateQuadratureData3S<3,12*12*12,12,7>},
{0x36,&rUpdateQuadratureData3S<3,14*14*14,14,8>},
{0x37,&rUpdateQuadratureData3S<3,16*16*16,16,9>},
{0x38,&rUpdateQuadratureData3S<3,18*18*18,18,10>},
{0x39,&rUpdateQuadratureData3S<3,20*20*20,20,11>},
{0x3A,&rUpdateQuadratureData3S<3,22*22*22,22,12>},
{0x3B,&rUpdateQuadratureData3S<3,24*24*24,24,13>},
{0x3C,&rUpdateQuadratureData3S<3,26*26*26,26,14>},
{0x3D,&rUpdateQuadratureData3S<3,28*28*28,28,15>},
{0x3E,&rUpdateQuadratureData3S<3,30*30*30,30,16>},
{0x3F,&rUpdateQuadratureData3S<3,32*32*32,32,17>},
};
if (!call[id])
{
printf("\n[rUpdateQuadratureDataS] id \033[33m0x%X\033[m ",id);
fflush(stdout);
}
assert(call[id]);
call0(id,grid,blck,
GAMMA,H0,CFL,USE_VISCOSITY,
nzones,dofToQuad,dofToQuadD,quadWeights,
v,e,rho0DetJ0w,invJ0,J,invJ,detJ,
stressJinvT,dtEst);
}
| 48.371901 | 129 | 0.440287 | artv3 |
2cddcd8889216dde8e8197eab76a84f25b0bdbe1 | 410 | hpp | C++ | library/ATF/stdext__hash_compare.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/stdext__hash_compare.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/stdext__hash_compare.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <std__less.hpp>
START_ATF_NAMESPACE
namespace stdext
{
template<typename _Ty, typename _Less = std::less<_Ty>>
struct hash_compare
{
_Less comp;
};
}; // end namespace stdext
END_ATF_NAMESPACE
| 22.777778 | 108 | 0.663415 | lemkova |
2ce53f1ddd4256efc827fbc3b541617004c1c6bc | 1,977 | cc | C++ | leetcode/leet-117.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | 4 | 2020-03-20T10:39:08.000Z | 2020-12-04T00:36:54.000Z | leetcode/leet-117.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | null | null | null | leetcode/leet-117.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | null | null | null | #include <queue>
using std::queue;
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(nullptr), right(nullptr), next(nullptr) {}
Node(int _val) : val(_val), left(nullptr), right(nullptr), next(nullptr) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution {
public:
//origin solution , same as leetcode-116 ????
Node* connect(Node* root) {
queue<Node*> level;
Node *tmp = nullptr;
if(root == nullptr){
return root;
}
level.push(root);
while(!level.empty()){
int size = level.size();
for(int i = 0; i < size; i++){
tmp = level.front();
level.pop();
if(i != size - 1){
tmp->next = level.front();
}else{
tmp->next = nullptr;
}
if(tmp->left != nullptr){
level.push(tmp->left);
}
if(tmp->right != nullptr){
level.push(tmp->right);
}
}
}
return root;
}
//leetcode solution
Node* connect(Node* root) {
//递归处理
if(!root) return NULL;
if(root->left){
if(root->right){
root->left->next = root->right;
}else{
root->left->next = findNext(root->next);
}
}
if(root->right){
root->right->next = findNext(root->next);
}
//再递归处理
connect(root->right);
connect(root->left);
return root;
}
Node* findNext(Node* root){
if(!root) return root;
if(root->left) return root->left;
if(root->right) return root->right;
return findNext(root->next);
}
}; | 25.675325 | 79 | 0.454729 | yanrong |
2ce5982951e8331ea1d02d7b12f25da0b03c43b5 | 742 | cpp | C++ | main.cpp | fore-head/210810_Make-to-1_LIS | 2595e1fd34042248cc22d825df966dcfb08311a3 | [
"MIT"
] | null | null | null | main.cpp | fore-head/210810_Make-to-1_LIS | 2595e1fd34042248cc22d825df966dcfb08311a3 | [
"MIT"
] | null | null | null | main.cpp | fore-head/210810_Make-to-1_LIS | 2595e1fd34042248cc22d825df966dcfb08311a3 | [
"MIT"
] | 1 | 2021-08-03T13:51:37.000Z | 2021-08-03T13:51:37.000Z | //
// Created by 이인성 on 2021/08/03.
//
#include <iostream>
int min_op[1000001];
int min(int n, int m) {
if(n <= m)
return n;
else
return m;
}
int main() {
int N;
scanf("%d", &N);
min_op[0] = 0;
min_op[1] = 0;
for(int i = 2; i <= N; i++) {
if((i%2 != 0) && (i%3 != 0)) {
min_op[i] = min_op[i-1] + 1;
}
else if((i%2 == 0) && (i%3 != 0)) {
min_op[i] = 1 + min(min_op[i-1], min_op[i/2]);
}
else if((i%2 != 0) && (i%3 == 0)) {
min_op[i] = 1 + min(min_op[i-1], min_op[i/3]);
}
else
min_op[i] = 1 + min(min_op[i-1], min(min_op[i/2], min_op[i/3]));
}
// for(int i=0; i<=N; i++) {
// printf("%d -> %d\n", i, min_op[i]);
// }
printf("%d\n", min_op[N]);
return 0;
} | 19.526316 | 70 | 0.442049 | fore-head |
2ce63e80b8f71d64e5679b4285fc09e75113ef92 | 4,105 | cpp | C++ | src/hir2mpl/test/common/hir2mpl_ut_options.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | 2 | 2019-09-06T07:02:41.000Z | 2019-09-09T12:24:46.000Z | src/hir2mpl/test/common/hir2mpl_ut_options.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | src/hir2mpl/test/common/hir2mpl_ut_options.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) [2020-2022] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "cl_option.h"
#include "hir2mpl_ut_options.h"
#include <iostream>
#include "mpl_logging.h"
#include "parser_opt.h"
namespace maple {
namespace opts::hir2mplut {
static maplecl::OptionCategory hir2mplUTCategory;
maplecl::Option<bool> help({"--help", "-h"},
" -h, -help : print usage and exit",
{hir2mplUTCategory});
maplecl::Option<std::string> genBase64({"--gen-base64", "-gen-base64"},
" -gen-base64 file.xx : generate base64 string for file.xx",
{hir2mplUTCategory});
maplecl::Option<std::string> mplt({"--mplt", "-mplt"},
" -mplt lib1.mplt,lib2.mplt\n"
" : input mplt files",
{hir2mplUTCategory});
maplecl::Option<std::string> inClass({"--in-class", "-in-class"},
" -in-class file1.jar,file2.jar\n"
" : input class files",
{hir2mplUTCategory});
maplecl::Option<std::string> inJar({"--in-jar", "-in-jar"},
" -in-jar file1.jar,file2.jar\n"
" : input jar files",
{hir2mplUTCategory});
}
HIR2MPLUTOptions::HIR2MPLUTOptions()
: runAll(false),
runAllWithCore(false),
genBase64(false),
base64SrcFileName(""),
coreMpltName("") {}
void HIR2MPLUTOptions::DumpUsage() const {
std::cout << "========================================\n"
<< " Run gtest: hir2mplUT\n"
<< " Run gtest: hir2mplUT test [ options for gtest ]\n"
<< " Run ext mode: hir2mplUT ext [ options ]\n"
<< "========= options for ext mode =========\n";
maplecl::CommandLine::GetCommandLine().HelpPrinter(opts::hir2mplut::hir2mplUTCategory);
exit(1);
}
bool HIR2MPLUTOptions::SolveArgs(int argc, char **argv) {
if (argc == 1) {
runAll = true;
return true;
}
if (std::string(argv[1]).compare("test") == 0) {
runAll = true;
return true;
}
if (std::string(argv[1]).compare("testWithMplt") == 0) {
runAllWithCore = true;
CHECK_FATAL(argc > 2, "In TestWithMplt mode, core.mplt must be specified");
coreMpltName = argv[2];
return true;
}
if (std::string(argv[1]).compare("ext") != 0) {
FATAL(kLncFatal, "Undefined mode");
return false;
}
runAll = false;
maplecl::CommandLine::GetCommandLine().Parse(argc, (char **)argv,
opts::hir2mplut::hir2mplUTCategory);
if (opts::hir2mplut::help) {
DumpUsage();
return false;
}
if (opts::hir2mplut::genBase64.IsEnabledByUser()) {
base64SrcFileName = opts::hir2mplut::genBase64;
}
if (opts::hir2mplut::inClass.IsEnabledByUser()) {
Split(opts::hir2mplut::inClass, ',', std::back_inserter(classFileList));
}
if (opts::hir2mplut::inJar.IsEnabledByUser()) {
Split(opts::hir2mplut::inJar, ',', std::back_inserter(jarFileList));
}
if (opts::hir2mplut::mplt.IsEnabledByUser()) {
Split(opts::hir2mplut::mplt, ',', std::back_inserter(mpltFileList));
}
return true;
}
template <typename Out>
void HIR2MPLUTOptions::Split(const std::string &s, char delim, Out result) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
} // namespace maple | 33.647541 | 101 | 0.568575 | venshine |
2ce95a4f2a6bb7558949c48cd0cf73414da05e50 | 798 | cpp | C++ | examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp | ronggong/TensorFlowTTS | 7541ee6cdf2f6e264384d2a47a74ae56d6305d33 | [
"Apache-2.0"
] | null | null | null | examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp | ronggong/TensorFlowTTS | 7541ee6cdf2f6e264384d2a47a74ae56d6305d33 | [
"Apache-2.0"
] | null | null | null | examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp | ronggong/TensorFlowTTS | 7541ee6cdf2f6e264384d2a47a74ae56d6305d33 | [
"Apache-2.0"
] | null | null | null | #include "MultiBandMelGAN.h"
bool MultiBandMelGAN::Initialize(const std::string & VocoderPath)
{
MelGAN = std::make_unique<Model>(VocoderPath);
return true;
}
Tensor MultiBandMelGAN::DoInference(Tensor& InMel)
{
VX_IF_EXCEPT(!MelGAN, "Tried to infer MB-MelGAN on uninitialized model!!!!");
// Convenience reference so that we don't have to constantly derefer pointers.
Tensor input_mels{ *MelGAN,"serving_default_mels" };
input_mels.set_data(InMel.get_data<float>(), InMel.get_shape());
Tensor out_audio{ *MelGAN, "StatefulPartitionedCall" };
MelGAN->run(input_mels, out_audio);
// TFTensor<float> RetTensor = VoxUtil::CopyTensor<float>(out_audio);
return out_audio;
}
MultiBandMelGAN::MultiBandMelGAN()
{
// MelGAN = nullptr;
}
MultiBandMelGAN::~MultiBandMelGAN()
{
}
| 19.95 | 81 | 0.741855 | ronggong |
f8ebd0e4432c71e9c8f689f4a14ea4e5ed4a7eb3 | 1,891 | cpp | C++ | src/lib/Colour.cpp | gtirloni/procdraw | 34ddb1b96f0f47af7304914e938f53d10ca5478d | [
"Apache-2.0"
] | null | null | null | src/lib/Colour.cpp | gtirloni/procdraw | 34ddb1b96f0f47af7304914e938f53d10ca5478d | [
"Apache-2.0"
] | null | null | null | src/lib/Colour.cpp | gtirloni/procdraw | 34ddb1b96f0f47af7304914e938f53d10ca5478d | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Simon Bates
//
// 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 "Colour.h"
namespace Procdraw {
// Foley and van Dam Fig. 13.34
// h [0, 360)
// s [0, 1]
// v [0, 1]
std::tuple<float, float, float> Hsv2rgb(float h, float s, float v)
{
float r = 0.0f;
float g = 0.0f;
float b = 0.0f;
if (s == 0) {
r = v;
g = v;
b = v;
}
else {
if (h == 360) {
h = 0;
}
h = h / 60;
int i = static_cast<int>(h);
float f = h - i;
float p = v * (1 - s);
float q = v * (1 - (s * f));
float t = v * (1 - (s * (1 - f)));
switch (i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
}
return std::make_tuple(r, g, b);
}
} // namespace Procdraw
| 23.345679 | 76 | 0.424114 | gtirloni |
f8f0e3500e42ada3b9423b0291d2d2a5cb689350 | 15,161 | hpp | C++ | src/api/face/cpp/doc/Vortex_FACE.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/face/cpp/doc/Vortex_FACE.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/face/cpp/doc/Vortex_FACE.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | /*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef VORTEX_FACE_ISOCPP2_Data_HPP_
#define VORTEX_FACE_ISOCPP2_Data_HPP_
#include "Vortex_FACE.hpp"
#include "Vortex/FACE/Macros.hpp"
namespace FACE {
namespace TS {
/**
* The Initialize function call allows for the Portable Components Segment (PCS) and Platform-Specific Services Segment (PSSS)
* component to trigger the initialization of the Transport Services Segment (TSS) component.
*
* Possible return codes:
* <ul>
* <li>INVALID_PARAM - The provided configuration is not valid
* <li>INVALID_CONFIG - The provided configuration contains invalid settings
* <li>NO_ACTION - There is already an initialized configuration.
* </ul>
* @param configuration
* The configuration defined as an xml file which hold the connection configuration.
* This is an input parameter
* @param return_code
* The return_code
*/
void Initialize(
/* in */ const FACE::CONFIGURATION_RESOURCE &configuration,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The Transport Services Segment (TSS) provides an interface to create a connection.
* The parameters for the individual connections are determined through the TSS configuration
* capability which is set by the Initialize function call.
*
* Possible return codes:
* <ul>
* <li>NO_ERROR - Successful completion.</li>
* <li>NO_ACTION - Returned if the participant has already been created and
* registered. - Type has already been registered.</li>
* <li>INVALID_CONFIG - Could not allocate enough memory. - Policies are not
* consistent with each other (e.g., configuration data is invalid, QoS
* attributes not supported).
* <ul>
* <li>Generic, unspecified error.</li>
* <li>Attempted to modify an immutable QoSPolicy.</li>
* </ul></li>
* <li>INVALID_PARAM - Returned under the following conditions: - Could not
* find topic name associated with the connection.</li>
* <li>NOT_AVAILABLE - Unsupported operation.</li>
* <li>INVALID_MODE - Connection could not be created in the current mode or
* operation performed at an inappropriate type.</li>
* </ul>
*
* @param connection_name
* The connection_name which needs to match one of the configured connection names in the configuration
* This is an input parameter.
* @param pattern
* The pattern set in the connection configuration which for DDS only can be PUB_SUB.
* This is an input parameter.
* @param connection_id
* The connection_id which is generated by DDS and set on successful creation.
* This is an output parameter.
* @param connection_direction
* The connection_direction of the connection that is created. This can be SOURCE or DESTINATION.
* This is an output parameter.
* @param max_message_size
* The max_message_size for DDS this parameter is not relevant.
* This is an output parameter.
* @param timeout
* The timeout for DDS this parameter is not relevant.
* This is an input parameter.
* @param return_code
* The return_code
* This is an output parameter.
*/
void Create_Connection(
/* in */ const FACE::CONNECTION_NAME_TYPE &connection_name,
/* in */ const FACE::MESSAGING_PATTERN_TYPE &pattern,
/* out */ FACE::CONNECTION_ID_TYPE &connection_id,
/* out */ FACE::CONNECTION_DIRECTION_TYPE &connection_direction,
/* out */ FACE::MESSAGE_SIZE_TYPE &max_message_size,
/* in */ const FACE::TIMEOUT_TYPE &timeout,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The Destroy_Connection function frees up any resources allocated to the connection.
*
* Possible return codes:
* <ul>
* <li>NO_ERROR - Successful completion.</li>
* <li>NO_ACTION - Object target of this operation has already been deleted.</li>
* <li>INVALID_MODE - An operation was invoked on an inappropriate object or
* at an inappropriate time.</li>
* <li>INVALID_PARAM - Connection identification (ID) invalid.</li>
* <li>NOT_AVAILABLE - Unsupported operation.</li>
* <li>INVALID_CONFIG - Generic, unspecified error.</li>
* <li>INVALID_MODE - A pre-condition for the operation was not met. Note:
* In a FACE implementation, this error may imply an implementation problem
* since the connection is deleted and should clean up all entities/children
* associated with the connection.</li>
* </ul>
*
* @param connection_id
* The connection_id of the connection that needs to be destroyed.
* This is an input parameter.
* @param return_code
* The return_code.
* This is an output parameter.
*/
void Destroy_Connection(
/* in */ const FACE::CONNECTION_ID_TYPE &connection_id,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The purpose of Get_Connection_Parameters is to get the information regarding the requested connection.
*
* @param connection_name
* The connection_name which belongs to the given connection_id.
* This is an output parameter.
* @param connection_id
* The connection_id for which this status needs to return information
* This is an input parameter.
* @param connection_status
* The connection_status which consists of the following settings:
* <ul>
* <li>MESSAGE - Always 0
* <li>MAX_MESSAGE - Always 0.
* <li>MAX_MESSAGE_SIZE - Always 0.
* <li>CONNECTION_DIRECTION - SOURCE or DESTINATION
* <li>WAITING_PROCESSES_OR_MESSAGES - Not implemented
* <li>REFRESH_PERIOD - The configured refresh period.
* <li>LAST_MSG_VALIDITY - Whether or not the refresh period of last taken message has expired or not (DESTINATION)
* </ul>
* This is an output parameter.
* @param return_code
* The return_code
* This is an output parameter.
*/
void Get_Connection_Parameters(
/* inout */ FACE::CONNECTION_NAME_TYPE &connection_name,
/* inout */ FACE::CONNECTION_ID_TYPE &connection_id,
/* out */ FACE::TRANSPORT_CONNECTION_STATUS_TYPE &connection_status,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The purpose of Unregister_Callback is to provide a mechanism to unregister the callback
* associated with a connection_id.
*
* @param connection_id
* The connection_id of the connection where the callback was registered.
* This is an input parameter.
* @param return_code
* The return_code
* This is an output parameter.
*/
void Unregister_Callback(
/* in */ const FACE::CONNECTION_ID_TYPE &connection_id,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The Receive_Message Function is used to receive data from another source.
*
* Possible return codes:
* <ul>
* <li>NO_ERROR - Successful completion.
* <li>NO_ACTION - Object target of this operation has already been deleted.
* <li>INVALID_MODE - An operation was invoked on an inappropriate object or
* <li>INVALID_PARAM - Illegal parameter value (e.g., connection ID).
* <li>INVALID_CONFIG - Generic, unspecified error.
* <li>NOT_AVAILABLE - Unsupported operation.
* <li>INVALID_MODE
* <ul>
* <li>A pre-condition for the operation was not met.
* <li>Operation invoked on an entity that is not yet enabled.
* </ul>
* <li>NO_ACTION - Indicates a transient situation where the operation did
* </ul>
* @param connection_id
* The connection_id which is used to get the connection where to receive messages on.
* This is an input parameter.
* @param timeout
* The timeout in nanoseconds, this is used to determine how long DDS should wait for new messages
* to arrive before returning the result.
* This is an input parameter.
* @param transaction_id
* The transaction_id, each time a message is read an unique transaction_id is generated for it.
* This is an output parameter.
* @param message
* The message that is read by DDS
* This is an output parameter.
* @param message_type_id
* The message_type_id for DDS this parameter is not relevant.
* This is an output parameter.
* @param message_size
* The message_type_id for DDS this parameter is not relevant.
* This is an output parameter.
* @param return_code
* The return_code
* This is an output parameter.
*/
void Receive_Message(
/* in */ const FACE::CONNECTION_ID_TYPE &connection_id,
/* in */ const FACE::TIMEOUT_TYPE &timeout,
/* inout */ FACE::TRANSACTION_ID_TYPE &transaction_id,
/* inout */ Data::Type &message,
/* inout */ FACE::MESSAGE_TYPE_GUID &message_type_id,
/* inout */ FACE::MESSAGE_SIZE_TYPE &message_size,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The Send_Message Function is used to send data to another source.
*
* Possible return codes:
* <ul>
* <li>NO_ERROR - Successful completion.
* <li>NO_ACTION - Object target of this operation has already been deleted.
* <li>INVALID_MODE - An operation was invoked on an inappropriate object or
* at an inappropriate time.
* <li>INVALID_PARAM - Illegal parameter value (e.g., connection ID).
* <li>INVALID_CONFIG - Generic, unspecified error.
* <li>NOT_AVAILABLE - Unsupported operation.
* <li>INVALID_MODE
* <ul>
* <li>A pre-condition for the operation was not met.
* <li>Operation invoked on an entity that is not yet enabled.
* </ul>
* <li>INVALID_CONFIG - Service ran out of resources needed to complete the
* operation.
* <li>TIMED_OUT - DDS will not return TIMEOUT, but this could be returned
* by the TSS implementation.
* </ul>
*
* @param connection_id
* The connection_id which is used to get the connection where to send messages to.
* This is an input parameter.
* @param timeout
* The timeout in nanoseconds, this is used to determine how long DDS at maximum can wait to send the message.
* This timeout cannot be greater than max_blocking_time of the supplied DataWriter QoS.
* This is an input parameter.
* @param transaction_id
* The transaction_id, each time a message is send an unique transaction_id is generated for it.
* This is an output parameter.
* @param message
* The message that is read by DDS
* This is an output parameter.
* @param message_type_id
* The message_type_id for DDS this parameter is not relevant.
* This is an output parameter.
* @param message_size
* The message_type_id for DDS this parameter is not relevant.
* This is an output parameter.
* @param return_code
* The return_code
* This is an output parameter.
*/
void Send_Message(
/* in */ const FACE::CONNECTION_ID_TYPE &connection_id,
/* in */ const FACE::TIMEOUT_TYPE &timeout,
/* inout */ FACE::TRANSACTION_ID_TYPE &transaction_id,
/* inout */ Data::Type &message,
/* in */ const FACE::MESSAGE_TYPE_GUID &message_type_id,
/* in */ const FACE::MESSAGE_SIZE_TYPE &message_size,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
/**
* The purpose of Register_Callback is to provide a mechanism to read data without polling.
* This needs to be called on the generated type interface without using the TS Interface.
* There can only be one callback registration per connection_id.
*
* Possible return codes:
* <ul>
* <li>NO_ERROR - Successful completion.
* <li>NO_ACTION - Callback already registered for specified type.
* <li>INVALID_PARAM - One or more of the parameters are incorrect (e.g.,
* invalid connection identification (ID), invalid callback, invalid message
* size).
* <li>NOT_AVAILABLE - Callback/routing function not available (e.g.,
* callback service is not provided in this implementation).
* <li>INVALID_CONFIG - One or more fields in the configuration data for the
* connection is invalid (e.g., invalid TSS thread parameters).
* </ul>
*
* <p>
* <b><i>Register_Callback Example</i></b>
* <pre>
* <code>
*
* static void data_callback (const FACE::TRANSACTION_ID_TYPE &transaction_id,
* Data::Type &message,
* const FACE::MESSAGE_TYPE_GUID &message_type_id,
* const FACE::MESSAGE_SIZE_TYPE &message_size,
* const FACE::WAITSET_TYPE &waitset,
* FACE::RETURN_CODE_TYPE &return_code)
* {
* do your action here
* }
*
* then the callback can be registered by calling:
* FACE::TS::Register_Callback(connection_id, waitset, data_callback, maxMessageSize, status);
* </code>
* </pre>
*
* @param connection_id
* The connection_id of the connection that needs to be used for the callback.
* This is an input parameter.
* @param waitset
* The waitset for DDS this parameter is not relevant.
* This is an input parameter.
* @param data_callback
* The data_callback class in which an action can be set on how to react when receiving data.
* This data_callback is the external operation (interface, which must be implemented by the application see example)
* that is called by the FACE API when new data is available for this connection.
* This is an input parameter.
* @param max_message_size
* The max_message_size for DDS this parameter is not relevant however the max_message_size supplied
* needs to be less then the max_message_size of the configured connection.
* This is an input parameter.
* @param return_code the return_code
* This is an output parameter.
*/
void Register_Callback(
/* in */ const FACE::CONNECTION_ID_TYPE &connection_id,
/* in */ const FACE::WAITSET_TYPE &waitset,
/* inout */ FACE::Read_Callback<Data::Type>::send_event data_callback,
/* in */ const FACE::MESSAGE_SIZE_TYPE &max_message_size,
/* out */ FACE::RETURN_CODE_TYPE &return_code);
} /* namespace TS */
} /* namespace FACE */
#endif /* VORTEX_FACE_ISOCPP2_Data_HPP_ */
| 43.317143 | 127 | 0.675879 | agenihorganization |
f8f320e68bdc82147a13add265cd46a71fee8340 | 1,575 | cpp | C++ | BAC_2nd/ch7/UVa1354.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC_2nd/ch7/UVa1354.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC_2nd/ch7/UVa1354.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa1354 Mobile Computing
// Rujia Liu
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
struct Tree {
double L, R; // distance from the root to the leftmost/rightmost point
Tree():L(0),R(0) {}
};
const int maxn = 6;
int n, vis[1<<maxn];
double r, w[maxn], sum[1<<maxn];
vector<Tree> tree[1<<maxn];
void dfs(int subset) {
if(vis[subset]) return;
vis[subset] = true;
bool have_children = false;
for(int left = (subset-1)⊂ left; left = (left-1)&subset) {
have_children = true;
int right = subset^left;
double d1 = sum[right] / sum[subset];
double d2 = sum[left] / sum[subset];
dfs(left); dfs(right);
for(int i = 0; i < tree[left].size(); i++)
for(int j = 0; j < tree[right].size(); j++) {
Tree t;
t.L = max(tree[left][i].L + d1, tree[right][j].L - d2);
t.R = max(tree[right][j].R + d2, tree[left][i].R - d1);
if(t.L + t.R < r) tree[subset].push_back(t);
}
}
if(!have_children) tree[subset].push_back(Tree());
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
scanf("%lf%d", &r, &n);
for(int i = 0; i < n; i++) scanf("%lf", &w[i]);
for(int i = 0; i < (1<<n); i++) {
sum[i] = 0;
tree[i].clear();
for(int j = 0; j < n; j++)
if(i & (1<<j)) sum[i] += w[j];
}
int root = (1<<n)-1;
memset(vis, 0, sizeof(vis));
dfs(root);
double ans = -1;
for(int i = 0; i < tree[root].size(); i++)
ans = max(ans, tree[root][i].L + tree[root][i].R);
printf("%.10lf\n", ans);
}
return 0;
}
| 22.826087 | 72 | 0.525714 | Anyrainel |
f8f38bd682ef50835a6d1e7a0c972d62133fe7d3 | 1,213 | cpp | C++ | Syl3D/misc/skyboxmanager.cpp | Jedi18/Syl3D | 8f62a3cd5349eaff83c36e9366003da61888ec73 | [
"MIT"
] | 2 | 2020-12-06T06:43:32.000Z | 2021-01-13T14:16:01.000Z | Syl3D/misc/skyboxmanager.cpp | Jedi18/Syl3D | 8f62a3cd5349eaff83c36e9366003da61888ec73 | [
"MIT"
] | 4 | 2020-11-30T03:18:03.000Z | 2021-05-22T16:46:25.000Z | Syl3D/misc/skyboxmanager.cpp | Jedi18/Syl3D | 8f62a3cd5349eaff83c36e9366003da61888ec73 | [
"MIT"
] | 2 | 2020-12-05T07:46:14.000Z | 2020-12-05T12:09:54.000Z | #include "skyboxmanager.h"
#include "../entity/entityfactory.h"
#include "../utility/fileio.h"
SkyboxManager* SkyboxManager::_instance = nullptr;
SkyboxManager::SkyboxManager() {
_skyboxNames = utility::FileIO::filesInPath("resources/skyboxes");
}
SkyboxManager* SkyboxManager::skyboxManager() {
if (_instance == nullptr) {
_instance = new SkyboxManager();
}
return _instance;
}
void SkyboxManager::releaseInstance() {
if (_instance != nullptr) {
delete _instance;
}
}
void SkyboxManager::addSkybox(const std::string& skyboxName) {
if (_skyboxes.find(skyboxName) != _skyboxes.end()) {
setSkybox(skyboxName);
return;
}
std::shared_ptr<CubeMap> skycubebox1 = std::make_shared<CubeMap>("resources/skyboxes/" + skyboxName);
std::shared_ptr<Skybox> skybox = std::make_shared<Skybox>();
skybox->setCubemap(skycubebox1);
_skyboxes[skyboxName] = skybox;
setSkybox(skyboxName);
}
void SkyboxManager::setSkybox(const std::string& skyboxName) {
if (_skyboxes.find(skyboxName) == _skyboxes.end()) {
return;
}
EntityFactory::entityFactory()->entityContainer()->setSkybox(_skyboxes[skyboxName]);
}
const std::vector<std::string>& SkyboxManager::skyboxNames() const {
return _skyboxNames;
} | 24.755102 | 102 | 0.734542 | Jedi18 |
f8f85a34f18c825113ef3cfaddb67d4103cb9dd5 | 3,948 | cc | C++ | ns-allinone-3.27/ns-3.27/src/wimax/model/simple-ofdm-send-param.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 93 | 2019-04-21T08:22:26.000Z | 2022-03-30T04:26:29.000Z | ns-allinone-3.27/ns-3.27/src/wimax/model/simple-ofdm-send-param.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 12 | 2019-04-19T16:39:58.000Z | 2021-06-22T13:18:32.000Z | ns-allinone-3.27/ns-3.27/src/wimax/model/simple-ofdm-send-param.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 21 | 2019-05-27T19:36:12.000Z | 2021-07-26T02:37:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007,2008, 2009 INRIA, UDcast
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mohamed Amine Ismail <amine.ismail@sophia.inria.fr>
* <amine.ismail@udcast.com>
*/
#include "simple-ofdm-send-param.h"
#include "simple-ofdm-wimax-phy.h"
#include "simple-ofdm-wimax-channel.h"
namespace ns3 {
simpleOfdmSendParam::simpleOfdmSendParam (void)
{
// m_fecBlock = 0;
m_burstSize = 0;
m_isFirstBlock = 0;
m_frequency = 0;
m_modulationType = WimaxPhy::MODULATION_TYPE_QPSK_12;
m_direction = 0;
m_rxPowerDbm = 0;
}
simpleOfdmSendParam::simpleOfdmSendParam (const bvec &fecBlock,
uint32_t burstSize,
bool isFirstBlock,
uint64_t Frequency,
WimaxPhy::ModulationType modulationType,
uint8_t direction,
double rxPowerDbm)
{
m_fecBlock = fecBlock;
m_burstSize = burstSize;
m_isFirstBlock = isFirstBlock;
m_frequency = Frequency;
m_modulationType = modulationType;
m_direction = direction;
m_rxPowerDbm = rxPowerDbm;
}
simpleOfdmSendParam::simpleOfdmSendParam (uint32_t burstSize,
bool isFirstBlock,
uint64_t Frequency,
WimaxPhy::ModulationType modulationType,
uint8_t direction,
double rxPowerDbm,
Ptr<PacketBurst> burst)
{
m_burstSize = burstSize;
m_isFirstBlock = isFirstBlock;
m_frequency = Frequency;
m_modulationType = modulationType;
m_direction = direction;
m_rxPowerDbm = rxPowerDbm;
m_burst = burst;
}
simpleOfdmSendParam::~simpleOfdmSendParam (void)
{
}
void
simpleOfdmSendParam::SetFecBlock (const bvec &fecBlock)
{
m_fecBlock = fecBlock;
}
void
simpleOfdmSendParam::SetBurstSize (uint32_t burstSize)
{
m_burstSize = burstSize;
}
void
simpleOfdmSendParam::SetIsFirstBlock (bool isFirstBlock)
{
m_isFirstBlock = isFirstBlock;
}
void
simpleOfdmSendParam::SetFrequency (uint64_t Frequency)
{
m_frequency = Frequency;
}
void
simpleOfdmSendParam::SetModulationType (WimaxPhy::ModulationType modulationType)
{
m_modulationType = modulationType;
}
void
simpleOfdmSendParam::SetDirection (uint8_t direction)
{
m_direction = direction;
}
void
simpleOfdmSendParam::SetRxPowerDbm (double rxPowerDbm)
{
m_rxPowerDbm = rxPowerDbm;
}
bvec
simpleOfdmSendParam::GetFecBlock (void)
{
return m_fecBlock;
}
uint32_t
simpleOfdmSendParam::GetBurstSize (void)
{
return m_burstSize;
}
bool
simpleOfdmSendParam::GetIsFirstBlock (void)
{
return m_isFirstBlock;
}
uint64_t
simpleOfdmSendParam::GetFrequency (void)
{
return m_frequency;
}
WimaxPhy::ModulationType
simpleOfdmSendParam::GetModulationType (void)
{
return m_modulationType;
}
uint8_t
simpleOfdmSendParam::GetDirection (void)
{
return m_direction;
}
double
simpleOfdmSendParam::GetRxPowerDbm (void)
{
return m_rxPowerDbm;
}
Ptr<PacketBurst>
simpleOfdmSendParam::GetBurst (void)
{
return m_burst;
}
}
| 25.146497 | 82 | 0.664387 | zack-braun |
f8f9a636edda72964354efc7bec76edea8cf6d55 | 651 | cpp | C++ | sample/k_distance_main.cpp | iwiwi/top-k-pruned-landmark-labeling | e334aab5faa10b0aa098f6895d8df393644fa532 | [
"BSD-3-Clause"
] | 1 | 2021-06-06T01:31:34.000Z | 2021-06-06T01:31:34.000Z | sample/k_distance_main.cpp | iwiwi/top-k-pruned-landmark-labeling | e334aab5faa10b0aa098f6895d8df393644fa532 | [
"BSD-3-Clause"
] | null | null | null | sample/k_distance_main.cpp | iwiwi/top-k-pruned-landmark-labeling | e334aab5faa10b0aa098f6895d8df393644fa532 | [
"BSD-3-Clause"
] | 1 | 2018-01-10T00:18:42.000Z | 2018-01-10T00:18:42.000Z | #include <cstdlib>
#include <iostream>
#include "top_k_pruned_landmark_labeling.hpp"
using namespace std;
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " (index_file)" << endl;
exit(EXIT_FAILURE);
}
TopKPrunedLandmarkLabeling kpll;
if (!kpll.LoadIndex(argv[1])) {
cerr << "error: Load failed" << endl;
exit(EXIT_FAILURE);
}
for (int u, v; cin >> u >> v; ) {
vector<int> dist;
kpll.KDistanceQuery(u, v, dist);
cout << dist.size();
for (size_t i = 0; i < dist.size(); i++){
cout << " " << dist[i];
}
cout << endl;
}
exit(EXIT_SUCCESS);
}
| 20.34375 | 60 | 0.55914 | iwiwi |
f8fadf65b4383c3b967f70c3c7baef93b581848b | 2,922 | cpp | C++ | plugins/community/repos/Bogaudio/src/FlipFlop.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/Bogaudio/src/FlipFlop.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/Bogaudio/src/FlipFlop.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z |
#include "FlipFlop.hpp"
void FlipFlop::onReset() {
_flipped1 = false;
_flipped2 = false;
_trigger1.reset();
_resetTrigger1.reset();
_trigger2.reset();
_resetTrigger2.reset();
}
void FlipFlop::step() {
channelStep(
inputs[IN1_INPUT],
inputs[RESET1_INPUT],
outputs[A1_OUTPUT],
outputs[B1_OUTPUT],
_trigger1,
_resetTrigger1,
_flipped1
);
channelStep(
inputs[IN2_INPUT],
inputs[RESET2_INPUT],
outputs[A2_OUTPUT],
outputs[B2_OUTPUT],
_trigger2,
_resetTrigger2,
_flipped2
);
}
void FlipFlop::channelStep(
Input& triggerInput,
Input& resetInput,
Output& aOutput,
Output& bOutput,
PositiveZeroCrossing& trigger,
Trigger& resetTrigger,
bool& flipped
) {
bool triggered = trigger.next(triggerInput.value);
resetTrigger.process(resetInput.value);
if (resetTrigger.isHigh()) {
flipped = false;
}
else if (triggered) {
flipped = !flipped;
}
if (flipped) {
aOutput.value = 0.0f;
bOutput.value = 5.0f;
}
else {
aOutput.value = 5.0f;
bOutput.value = 0.0f;
}
}
struct FlipFlopWidget : ModuleWidget {
static constexpr int hp = 3;
FlipFlopWidget(FlipFlop* module) : ModuleWidget(module) {
box.size = Vec(RACK_GRID_WIDTH * hp, RACK_GRID_HEIGHT);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/FlipFlop.svg")));
addChild(panel);
}
addChild(Widget::create<ScrewSilver>(Vec(0, 0)));
addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 15, 365)));
// generated by svg_widgets.rb
auto in1InputPosition = Vec(10.5, 21.0);
auto reset1InputPosition = Vec(10.5, 56.0);
auto in2InputPosition = Vec(10.5, 172.0);
auto reset2InputPosition = Vec(10.5, 207.0);
auto a1OutputPosition = Vec(10.5, 94.0);
auto b1OutputPosition = Vec(10.5, 129.0);
auto a2OutputPosition = Vec(10.5, 245.0);
auto b2OutputPosition = Vec(10.5, 280.0);
// end generated by svg_widgets.rb
addInput(Port::create<Port24>(in1InputPosition, Port::INPUT, module, FlipFlop::IN1_INPUT));
addInput(Port::create<Port24>(reset1InputPosition, Port::INPUT, module, FlipFlop::RESET1_INPUT));
addInput(Port::create<Port24>(in2InputPosition, Port::INPUT, module, FlipFlop::IN2_INPUT));
addInput(Port::create<Port24>(reset2InputPosition, Port::INPUT, module, FlipFlop::RESET2_INPUT));
addOutput(Port::create<Port24>(a1OutputPosition, Port::OUTPUT, module, FlipFlop::A1_OUTPUT));
addOutput(Port::create<Port24>(b1OutputPosition, Port::OUTPUT, module, FlipFlop::B1_OUTPUT));
addOutput(Port::create<Port24>(a2OutputPosition, Port::OUTPUT, module, FlipFlop::A2_OUTPUT));
addOutput(Port::create<Port24>(b2OutputPosition, Port::OUTPUT, module, FlipFlop::B2_OUTPUT));
}
};
RACK_PLUGIN_MODEL_INIT(Bogaudio, FlipFlop) {
Model *modelFlipFlop = createModel<FlipFlop, FlipFlopWidget>("Bogaudio-FlipFlop", "FlipFlop", "dual stateful logic", LOGIC_TAG, DUAL_TAG);
return modelFlipFlop;
}
| 27.566038 | 142 | 0.719713 | guillaume-plantevin |
f8fdb8f91d8b0ab17832f710421b06e8b6141c7e | 1,903 | cc | C++ | chrome/common/privacy_budget/privacy_budget_settings_provider.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/common/privacy_budget/privacy_budget_settings_provider.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/common/privacy_budget/privacy_budget_settings_provider.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 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/common/privacy_budget/privacy_budget_settings_provider.h"
#include <memory>
#include "base/containers/contains.h"
#include "base/ranges/algorithm.h"
#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
#include "chrome/common/privacy_budget/privacy_budget_features.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider()
: blocked_surfaces_(
DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceSet>(
features::kIdentifiabilityStudyBlockedMetrics.Get())),
blocked_types_(
DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceTypeSet>(
features::kIdentifiabilityStudyBlockedTypes.Get())),
enabled_(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy)) {}
PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider(
const PrivacyBudgetSettingsProvider&) = default;
PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider(
PrivacyBudgetSettingsProvider&&) = default;
PrivacyBudgetSettingsProvider::~PrivacyBudgetSettingsProvider() = default;
bool PrivacyBudgetSettingsProvider::IsActive() const {
return enabled_;
}
bool PrivacyBudgetSettingsProvider::IsAnyTypeOrSurfaceBlocked() const {
return !blocked_surfaces_.empty() || !blocked_types_.empty();
}
bool PrivacyBudgetSettingsProvider::IsSurfaceAllowed(
blink::IdentifiableSurface surface) const {
return !base::Contains(blocked_surfaces_, surface) &&
IsTypeAllowed(surface.GetType());
}
bool PrivacyBudgetSettingsProvider::IsTypeAllowed(
blink::IdentifiableSurface::Type type) const {
return !base::Contains(blocked_types_, type);
}
| 39.645833 | 80 | 0.794535 | zealoussnow |
5d04df8ec0c0ac777f13f832d2da1fea6659ef6c | 7,106 | hpp | C++ | dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | 1 | 2022-03-18T14:13:14.000Z | 2022-03-18T14:13:14.000Z | #ifndef DLSfuncs.hpp
#define DLSfuncs.hpp
#include <stdio.h>
#include <iostream>
#include "dakota_data_types.hpp"
namespace Dakota {
class Optimizer1; // treated as anonymous here
struct Opt_Info {
char *begin; // I/O, updated by dlsolver_option for use in next dlsolver_option call
char *name; // out: option name
char *val; // out: start of value (null if no value found)
// output _len values are int rather than size_t for format %.*s
int name_len; // out: length of name
int val_len; // out: length of value (0 if val is null)
int all_len; // out: length of entire name = value phrase
int eq_repl; // in: change '=' to this value
int und_repl; // in: change '_' to this value
// constructor...
inline Opt_Info(char *begin1, int undval = ' ', int eqval = ' '):
begin(begin1), eq_repl(eqval), und_repl(undval) {}
};
struct
Dakota_probsize
{
int n_var; // number of continuous variables
int n_linc; // number of linear constraints
int n_nlinc; // number of nonlinear constraints
int n_obj; // number of objectives
int maxfe; // maximum function evaluations
int numgflag; // numerical gradient flag
int objrecast; // local objective recast flag
};
struct
Dakota_funcs
{
int (*Fprintf)(FILE*, const char*, ...);
void (*abort_handler1)(int);
int (*dlsolver_option1)(Opt_Info*);
RealVector const * (*continuous_lower_bounds)(Optimizer1*);
RealVector const * (*continuous_upper_bounds)(Optimizer1*);
RealVector const * (*nonlinear_ineq_constraint_lower_bounds)(Optimizer1*);
RealVector const * (*nonlinear_ineq_constraint_upper_bounds)(Optimizer1*);
RealVector const * (*nonlinear_eq_constraint_targets)(Optimizer1*);
RealVector const * (*linear_ineq_constraint_lower_bounds)(Optimizer1*);
RealVector const * (*linear_ineq_constraint_upper_bounds)(Optimizer1*);
RealVector const * (*linear_eq_constraint_targets)(Optimizer1*);
RealMatrix const * (*linear_ineq_constraint_coeffs)(Optimizer1*);
RealMatrix const * (*linear_eq_constraint_coeffs)(Optimizer1*);
void (*ComputeResponses1)(Optimizer1*, int mode, int n, double *x);
// ComputeResponses uses x[i], 0 <= i < n
void (*GetFuncs1)(Optimizer1*, int m0, int m1, double *f);
// GetFuncs sets f[i] <-- response(m+i), m0 <= i < m1
void (*GetGrads1)(Optimizer1*, int m0, int m1, int n, int is, int js, double *g);
// g[(i-m0)*is + j*js] <-- partial(Response i)/partial(var j),
// m0 <= i < m1, 0 <= j < n
void (*GetContVars)(Optimizer1*, int n, double *x);
void (*SetBestContVars)(Optimizer1*, int n, double *x); // set best continuous var values
void (*SetBestDiscVars)(Optimizer1*, int n, int *x); // set best discrete var values
void (*SetBestRespFns)(Optimizer1*, int n, double *x); // set best resp func values
double (*get_real)(Optimizer1*, const char*); // for probDescDB.get_real()
int (*get_int) (Optimizer1*, const char*); // for probDescDB.get_int()
bool (*get_bool)(Optimizer1*, const char*); // for probDescDB.get_bool()
Dakota_probsize *ps;
std::ostream *dakota_cerr, *dakota_cout;
FILE *Stderr;
};
#ifdef NO_DAKOTA_DLSOLVER_FUNCS_INLINE
extern int dlsolver_option(Opt_Info *);
#else //!NO_DAKOTA_DLSOLVER_FUNCS_INLINE
extern Dakota_funcs *DF;
#undef Cout
#define Cout (*DF->dakota_cout)
#if 0 // "inline" is not inlined at low optimization levels,
// causing confusion in gdb. It's less confusing to use #define;
// we get type checking in this case much as with inline.
inline void abort_handler(int n)
{ DF->abort_handler1(n); }
inline int dlsolver_option(Opt_Info *oi)
{ return DF->dlsolver_option1(oi); }
inline RealVector const * continuous_lower_bounds(Optimizer1 *o)
{ return DF->continuous_lower_bounds(o); }
inline RealVector const * continuous_upper_bounds(Optimizer1 *o)
{ return DF->continuous_upper_bounds(o); }
inline RealVector const * nonlinear_ineq_constraint_lower_bounds(Optimizer1 *o)
{ return DF->nonlinear_ineq_constraint_lower_bounds(o); }
inline RealVector const * nonlinear_ineq_constraint_upper_bounds(Optimizer1 *o)
{ return DF->nonlinear_ineq_constraint_upper_bounds(o); }
inline RealVector const * nonlinear_eq_constraint_targets(Optimizer1 *o)
{ return DF->nonlinear_eq_constraint_targets(o); }
inline RealVector const * linear_ineq_constraint_lower_bounds(Optimizer1 *o)
{ return DF->linear_ineq_constraint_lower_bounds(o); }
inline RealVector const * linear_ineq_constraint_upper_bounds(Optimizer1 *o)
{ return DF->linear_ineq_constraint_upper_bounds(o); }
inline RealVector const * linear_eq_constraint_targets(Optimizer1 *o)
{ return DF->linear_eq_constraint_targets(o); }
inline RealMatrix const * linear_ineq_constraint_coeffs(Optimizer1 *o)
{ return DF->linear_ineq_constraint_coeffs(o); }
inline RealMatrix const * linear_eq_constraint_coeffs(Optimizer1 *o)
{ return DF->linear_eq_constraint_coeffs(o); }
inline void ComputeResponses(Optimizer1 *o, int mode, int n, double *x)
{ DF->ComputeResponses1(o, mode, n, x); }
inline void GetFuncs(Optimizer1 *o, int m0, int m1, double *f)
{ DF->GetFuncs1(o, m0, m1, f); }
inline void GetGrads(Optimizer1 *o, int m0, int m1, int n, int is, int js, double *g)
{ DF->GetGrads1(o, m0, m1, n, is, js, g); }
inline void GetContVars(Optimizer1 *o, int n, double *x)
{ DF->GetContVars(o, n, x); }
inline void SetBestContVars(Optimizer1 *o, int n, double *x)
{ DF->SetBestContVars(o, n, x); }
inline void SetBestRespFns(Optimizer1 *o, int n, double *x)
{ DF->SetBestRespFns(o, n, x); }
#else // use #define to really inline
#define abort_handler(n) DF->abort_handler1(n)
#define dlsolver_option(oi) DF->dlsolver_option1(oi)
#define continuous_lower_bounds(o) DF->continuous_lower_bounds(o)
#define continuous_upper_bounds(o) DF->continuous_upper_bounds(o)
#define nonlinear_ineq_constraint_lower_bounds(o) DF->nonlinear_ineq_constraint_lower_bounds(o)
#define nonlinear_ineq_constraint_upper_bounds(o) DF->nonlinear_ineq_constraint_upper_bounds(o)
#define nonlinear_eq_constraint_targets(o) DF->nonlinear_eq_constraint_targets(o)
#define linear_ineq_constraint_lower_bounds(o) DF->linear_ineq_constraint_lower_bounds(o)
#define linear_ineq_constraint_upper_bounds(o) DF->linear_ineq_constraint_upper_bounds(o)
#define linear_eq_constraint_targets(o) DF->linear_eq_constraint_targets(o)
#define linear_ineq_constraint_coeffs(o) DF->linear_ineq_constraint_coeffs(o)
#define linear_eq_constraint_coeffs(o) DF->linear_eq_constraint_coeffs(o)
#define ComputeResponses(o,mode,n,x) DF->ComputeResponses1(o, mode, n, x)
#define GetFuncs(o,m0,m1,f) DF->GetFuncs1(o, m0, m1, f)
#define GetGrads(o,m0,m1,n,is,js,g) DF->GetGrads1(o, m0, m1, n, is, js, g)
#define GetContVars(o,n,x) DF->GetContVars(o, n, x)
#define SetBestContVars(o,n,x) DF->SetBestContVars(o, n, x)
#define SetBestDiscVars(o,n,x) DF->SetBestDiscVars(o, n, x)
#define SetBestRespFns(o,n,x) DF->SetBestRespFns(o, n, x)
#endif
#endif //NO_DAKOTA_DLSOLVER_FUNCS_INLINE
typedef void (*dl_find_optimum_t)(void*, Optimizer1*, char*);
typedef void (*dl_destructor_t)(void**);
extern "C" void *dl_constructor(Optimizer1 *, Dakota_funcs*, dl_find_optimum_t *, dl_destructor_t *);
} // namespace Dakota
#endif //DLSfuncs.hpp
| 39.921348 | 101 | 0.753307 | seakers |
5d0944bbcca152ebd69e6ea349b58a1d45764087 | 5,428 | cpp | C++ | PlatformTest/main.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | null | null | null | PlatformTest/main.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | 1 | 2019-06-19T15:55:25.000Z | 2019-06-27T07:47:27.000Z | PlatformTest/main.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | 1 | 2019-07-07T04:37:56.000Z | 2019-07-07T04:37:56.000Z | /*
* Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#ifdef _WINDOWS
#include <Windows.h>
#elif _LINUX
#include <cstdio>
#endif // _WINDOWS
#include <sstream>
#include "Platform/Application.h"
#include "Platform/Input/InputManager.h"
#include "Platform/Multithreading/Manager.h"
#include "Platform/ResourceManagement/MemoryManager.h"
#include "Platform/Timing/TimePeriod.h"
using namespace Input;
using namespace Platform;
using namespace std;
using namespace Timing;
#ifdef MEMORY_MANAGEMENT
const uint32 ResourceManagement::DEFAULT_POOL_BUCKET_NUMBER = 5;
const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_CAPACITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 1024, 1024, 1024, 1024, 1024 };
const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_GRANULARITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 16, 32, 64, 128, 256 };
#endif // MEMORY_MANAGEMENT
std::mutex osMutex;
class OutputTask : public Multithreading::Task
{
public:
OutputTask(wostringstream &os, char c, uint32 count) :
Task(), mOS(os), mChar(c), mCount(count)
{
};
virtual void function()
{
for (uint32 i = 0; i < mCount; ++i)
{
osMutex.lock();
mOS << mChar;
osMutex.unlock();
//Sleep(10);
}
osMutex.lock();
mOS << "\n";
osMutex.unlock();
}
private:
wostringstream &mOS;
char mChar;
uint32 mCount;
};
class MyApp : public Application
{
public:
#ifdef _WINDOWS
MyApp(HINSTANCE instanceHandle) : Application(instanceHandle), mPeriod(5.0f) { }
#elif _LINUX
MyApp() : mPeriod(5.0f) {}
#endif // _WINDOWS
virtual ~MyApp() { }
virtual void onActivation() { Application::onActivation(); }
virtual void onDeactivation() { Application::onDeactivation(); }
void testMultithreading(wostringstream &os)
{
os << "Test multithreading: \n";
for (uint32 i = 0; i < 100; ++i)
{
OutputTask task1(os, 'a', 4);
OutputTask task2(os, 'b', 10);
OutputTask task3(os, 'c', 12);
Multithreading::Manager &manager = Multithreading::Manager::getSingleton();
manager.enqueue(&task1);
manager.enqueue(&task2);
manager.enqueue(&task3);
task1.waitUntilFinished();
osMutex.lock();
os << "Task 1 has finished!\n";
osMutex.unlock();
task2.waitUntilFinished();
osMutex.lock();
os << "Task 2 has finished!\n";
osMutex.unlock();
task3.waitUntilFinished();
osMutex.lock();
os << "Task 3 has finished!\n";
osMutex.unlock();
}
}
protected:
virtual void postRender() { }
virtual void render() { }
virtual void update()
{
const Keyboard &keyboard = InputManager::getSingleton().getKeyboard();
const Mouse &mouse = InputManager::getSingleton().getMouse();
wostringstream os(wostringstream::out);
os.clear();
if (keyboard.isKeyDown(Input::KEY_ESCAPE))
mRunning = false;
bool change = false;
if (mInterpretingTextInput && keyboard.isKeyPressed(Input::KEY_RETURN))
{
wstring text = endTextInput();
os << L"Finished text:\n";
os << text << L"\n";
change = true;
}
else
{
if (!mInterpretingTextInput && keyboard.isKeyPressed(Input::KEY_RETURN))
{
mLastTextLength = 0;
os << L"Start text input.\n";
startTextInput();
change = true;
}
if (keyboard.isKeyDown(Input::KEY_M))
{
change = true;
testMultithreading(os);
}
}
if (isInterpretingTextInput())
{
if (keyboard.isKeyPressed(Input::KEY_LEFT))
{
change = true;
mTextInput.moveCursorToTheLeft();
}
if (keyboard.isKeyPressed(Input::KEY_RIGHT))
{
change = true;
mTextInput.moveCursorToTheRight();
}
if (keyboard.isKeyPressed(Input::KEY_DELETE))
{
change = true;
mTextInput.removeCharacterAtCursorPosition();
}
if (keyboard.isKeyPressed(Input::KEY_BACKSPACE))
{
change = true;
mTextInput.removeCharacterBeforeCursorPosition();
}
}
if (mLastTextLength != mTextInput.getTextLength())
change = true;
if (change && mInterpretingTextInput)
{
wstring text = mTextInput.getText();
text.insert(mTextInput.getCursorPosition(), L"|");
os << text << L"\n";
}
Real mouseXMotion = mouse.getRelativeXMotion();
Real mouseYMotion = mouse.getRelativeYMotion();
if (mouseXMotion != 0.0f && mouseYMotion != 0.0f)
{
change = true;
os << L"\nmouse x: " << mouseXMotion;
os << L"\nmouse y: " << mouseYMotion;
}
#ifdef _LINUX
if (mPeriod.hasExpired())
{
printf("%f seconds have elapsed.\n", mPeriod.getElapsedTime());
mPeriod.reset();
}
#endif // _LINUX
if (change)
{
#ifdef _WINDOWS
OutputDebugString(os.str().c_str());
#elif _LINUX
wprintf(os.str().c_str());
#endif // _WINDOWS etc
}
mLastTextLength = mTextInput.getTextLength();
}
TimePeriod mPeriod;
uint32 mLastTextLength;
};
#ifdef _WINDOWS
int32 WINAPI WinMain(HINSTANCE applicationHandle, HINSTANCE unused, LPSTR commandLineString, int32 windowShowState)
{
#else
int main(int argc, char *argv[])
{
#endif // _WINDOWS
{
#ifdef _WINDOWS
MyApp application(applicationHandle);
#else
MyApp application;
#endif // _WINDOWS
application.run();
}
#ifdef MEMORY_MANAGEMENT
ResourceManagement::MemoryManager::shutDown();
#endif // MEMORY_MANAGEMENT
return 0;
}
| 23 | 128 | 0.670965 | SamirAroudj |
5d0a79aaae43ed98c4d4051a86280e6e621e9e7d | 1,491 | cpp | C++ | redemption/src/utils/hexadecimal_string_to_buffer.cpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/utils/hexadecimal_string_to_buffer.cpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/utils/hexadecimal_string_to_buffer.cpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Product name: redemption, a FLOSS RDP proxy
Copyright (C) Wallix 2021
Author(s): Proxies Team
*/
#include "utils/hexadecimal_string_to_buffer.hpp"
#include "utils/sugar/chars_to_int.hpp"
#include <cassert>
bool hexadecimal_string_to_buffer(chars_view in, writable_bytes_view out) noexcept
{
assert(in.size() <= out.size() * 2);
assert(in.size() % 2 == 0);
unsigned err = 0;
uint8_t const* p = bytes_view{in}.data();
for (uint8_t& outc : out) {
uint8_t c1 = detail::hexadecimal_char_to_int(*p++);
uint8_t c2 = detail::hexadecimal_char_to_int(*p++);
err |= c1 | c2;
outc = uint8_t((c1 << 4) | c2);
}
return err != 0xff;
}
bool hexadecimal_string_to_buffer(chars_view in, uint8_t* out) noexcept
{
return hexadecimal_string_to_buffer(in, {out, in.size() / 2});
}
| 32.413043 | 82 | 0.721663 | DianaAssistant |
5d0c3b90f20d4d8285413757a86b5a10ca171c7a | 16,731 | cpp | C++ | latte-dock/declarativeimports/core/iconitem.cpp | VaughnValle/lush-pop | cdfe9d7b6a7ebb89ba036ab9a4f07d8db6817355 | [
"MIT"
] | 64 | 2020-07-08T18:49:29.000Z | 2022-03-23T22:58:49.000Z | latte-dock/declarativeimports/core/iconitem.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 1 | 2021-04-02T04:39:45.000Z | 2021-09-25T11:53:18.000Z | latte-dock/declarativeimports/core/iconitem.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 11 | 2020-12-04T18:19:11.000Z | 2022-01-10T08:50:08.000Z | /*
* Copyright 2012 Marco Martin <mart@kde.org>
* Copyright 2014 David Edmundson <davidedmudnson@kde.org>
* Copyright 2016 Smith AR <audoban@openmailbox.org>
* Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock and is a Fork of PlasmaCore::IconItem
*
* Latte-Dock 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.
*
* Latte-Dock is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "iconitem.h"
// local
#include "extras.h"
// Qt
#include <QDebug>
#include <QPainter>
#include <QPaintEngine>
#include <QQuickWindow>
#include <QPixmap>
#include <QSGSimpleTextureNode>
#include <QuickAddons/ManagedTextureNode>
// KDE
#include <KIconTheme>
#include <KIconThemes/KIconLoader>
#include <KIconThemes/KIconEffect>
namespace Latte {
IconItem::IconItem(QQuickItem *parent)
: QQuickItem(parent),
m_lastValidSourceName(QString()),
m_smooth(false),
m_active(false),
m_textureChanged(false),
m_sizeChanged(false),
m_usesPlasmaTheme(false),
m_colorGroup(Plasma::Theme::NormalColorGroup)
{
setFlag(ItemHasContents, true);
connect(KIconLoader::global(), SIGNAL(iconLoaderSettingsChanged()),
this, SIGNAL(implicitWidthChanged()));
connect(KIconLoader::global(), SIGNAL(iconLoaderSettingsChanged()),
this, SIGNAL(implicitHeightChanged()));
connect(this, &QQuickItem::enabledChanged,
this, &IconItem::enabledChanged);
connect(this, &QQuickItem::windowChanged,
this, &IconItem::schedulePixmapUpdate);
connect(this, SIGNAL(overlaysChanged()),
this, SLOT(schedulePixmapUpdate()));
connect(this, SIGNAL(providesColorsChanged()),
this, SLOT(schedulePixmapUpdate()));
//initialize implicit size to the Dialog size
setImplicitWidth(KIconLoader::global()->currentSize(KIconLoader::Dialog));
setImplicitHeight(KIconLoader::global()->currentSize(KIconLoader::Dialog));
setSmooth(true);
}
IconItem::~IconItem()
{
}
void IconItem::setSource(const QVariant &source)
{
if (source == m_source) {
return;
}
m_source = source;
QString sourceString = source.toString();
// If the QIcon was created with QIcon::fromTheme(), try to load it as svg
if (source.canConvert<QIcon>() && !source.value<QIcon>().name().isEmpty()) {
sourceString = source.value<QIcon>().name();
}
if (!sourceString.isEmpty()) {
setLastValidSourceName(sourceString);
setLastLoadedSourceId(sourceString);
//If a url in the form file:// is passed, take the image pointed by that from disk
QUrl url(sourceString);
if (url.isLocalFile()) {
m_icon = QIcon();
m_imageIcon = QImage(url.path());
m_svgIconName.clear();
m_svgIcon.reset();
} else {
if (!m_svgIcon) {
m_svgIcon = std::make_unique<Plasma::Svg>(this);
m_svgIcon->setColorGroup(m_colorGroup);
m_svgIcon->setStatus(Plasma::Svg::Normal);
m_svgIcon->setUsingRenderingCache(false);
m_svgIcon->setDevicePixelRatio((window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()));
connect(m_svgIcon.get(), &Plasma::Svg::repaintNeeded, this, &IconItem::schedulePixmapUpdate);
}
if (m_usesPlasmaTheme) {
//try as a svg icon from plasma theme
m_svgIcon->setImagePath(QLatin1String("icons/") + sourceString.split('-').first());
m_svgIcon->setContainsMultipleImages(true);
//invalidate the image path to recalculate it later
} else {
m_svgIcon->setImagePath(QString());
}
//success?
if (m_svgIcon->isValid() && m_svgIcon->hasElement(sourceString)) {
m_icon = QIcon();
m_svgIconName = sourceString;
//ok, svg not available from the plasma theme
} else {
//try to load from iconloader an svg with Plasma::Svg
const auto *iconTheme = KIconLoader::global()->theme();
QString iconPath;
if (iconTheme) {
iconPath = iconTheme->iconPath(sourceString + QLatin1String(".svg")
, static_cast<int>(qMin(width(), height()))
, KIconLoader::MatchBest);
if (iconPath.isEmpty()) {
iconPath = iconTheme->iconPath(sourceString + QLatin1String(".svgz")
, static_cast<int>(qMin(width(), height()))
, KIconLoader::MatchBest);
}
} else {
qWarning() << "KIconLoader has no theme set";
}
if (!iconPath.isEmpty()) {
m_svgIcon->setImagePath(iconPath);
m_svgIconName = sourceString;
//fail, use QIcon
} else {
//if we started with a QIcon use that.
m_icon = source.value<QIcon>();
if (m_icon.isNull()) {
m_icon = QIcon::fromTheme(sourceString);
}
m_svgIconName.clear();
m_svgIcon.reset();
m_imageIcon = QImage();
}
}
}
} else if (source.canConvert<QIcon>()) {
m_icon = source.value<QIcon>();
m_iconCounter++;
setLastLoadedSourceId("_icon_"+QString::number(m_iconCounter));
m_imageIcon = QImage();
m_svgIconName.clear();
m_svgIcon.reset();
} else if (source.canConvert<QImage>()) {
m_imageIcon = source.value<QImage>();
m_iconCounter++;
setLastLoadedSourceId("_image_"+QString::number(m_iconCounter));
m_icon = QIcon();
m_svgIconName.clear();
m_svgIcon.reset();
} else {
m_icon = QIcon();
m_imageIcon = QImage();
m_svgIconName.clear();
m_svgIcon.reset();
}
if (width() > 0 && height() > 0) {
schedulePixmapUpdate();
}
emit sourceChanged();
emit validChanged();
}
QVariant IconItem::source() const
{
return m_source;
}
void IconItem::setLastLoadedSourceId(QString id)
{
if (m_lastLoadedSourceId == id) {
return;
}
m_lastLoadedSourceId = id;
}
QString IconItem::lastValidSourceName()
{
return m_lastValidSourceName;
}
void IconItem::setLastValidSourceName(QString name)
{
if (m_lastValidSourceName == name || name == "" || name == "application-x-executable") {
return;
}
m_lastValidSourceName = name;
emit lastValidSourceNameChanged();
}
void IconItem::setColorGroup(Plasma::Theme::ColorGroup group)
{
if (m_colorGroup == group) {
return;
}
m_colorGroup = group;
if (m_svgIcon) {
m_svgIcon->setColorGroup(group);
}
emit colorGroupChanged();
}
Plasma::Theme::ColorGroup IconItem::colorGroup() const
{
return m_colorGroup;
}
void IconItem::setOverlays(const QStringList &overlays)
{
if (overlays == m_overlays) {
return;
}
m_overlays = overlays;
emit overlaysChanged();
}
QStringList IconItem::overlays() const
{
return m_overlays;
}
bool IconItem::isActive() const
{
return m_active;
}
void IconItem::setActive(bool active)
{
if (m_active == active) {
return;
}
m_active = active;
if (isComponentComplete()) {
schedulePixmapUpdate();
}
emit activeChanged();
}
bool IconItem::providesColors() const
{
return m_providesColors;
}
void IconItem::setProvidesColors(const bool provides)
{
if (m_providesColors == provides) {
return;
}
m_providesColors = provides;
emit providesColorsChanged();
}
void IconItem::setSmooth(const bool smooth)
{
if (smooth == m_smooth) {
return;
}
m_smooth = smooth;
update();
}
bool IconItem::smooth() const
{
return m_smooth;
}
bool IconItem::isValid() const
{
return !m_icon.isNull() || m_svgIcon || !m_imageIcon.isNull();
}
int IconItem::paintedWidth() const
{
return boundingRect().size().toSize().width();
}
int IconItem::paintedHeight() const
{
return boundingRect().size().toSize().height();
}
bool IconItem::usesPlasmaTheme() const
{
return m_usesPlasmaTheme;
}
void IconItem::setUsesPlasmaTheme(bool usesPlasmaTheme)
{
if (m_usesPlasmaTheme == usesPlasmaTheme) {
return;
}
m_usesPlasmaTheme = usesPlasmaTheme;
// Reload icon with new settings
const QVariant src = m_source;
m_source.clear();
setSource(src);
update();
emit usesPlasmaThemeChanged();
}
void IconItem::updatePolish()
{
QQuickItem::updatePolish();
loadPixmap();
}
QSGNode *IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData)
{
Q_UNUSED(updatePaintNodeData)
if (m_iconPixmap.isNull() || width() < 1.0 || height() < 1.0) {
delete oldNode;
return nullptr;
}
ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode *>(oldNode);
if (!textureNode || m_textureChanged) {
if (oldNode)
delete oldNode;
textureNode = new ManagedTextureNode;
textureNode->setTexture(QSharedPointer<QSGTexture>(window()->createTextureFromImage(m_iconPixmap.toImage(), QQuickWindow::TextureCanUseAtlas)));
textureNode->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest);
m_sizeChanged = true;
m_textureChanged = false;
}
if (m_sizeChanged) {
const auto iconSize = qMin(boundingRect().size().width(), boundingRect().size().height());
const QRectF destRect(QPointF(boundingRect().center() - QPointF(iconSize / 2, iconSize / 2)), QSizeF(iconSize, iconSize));
textureNode->setRect(destRect);
m_sizeChanged = false;
}
return textureNode;
}
void IconItem::schedulePixmapUpdate()
{
polish();
}
void IconItem::enabledChanged()
{
schedulePixmapUpdate();
}
QColor IconItem::backgroundColor() const
{
return m_backgroundColor;
}
void IconItem::setBackgroundColor(QColor background)
{
if (m_backgroundColor == background) {
return;
}
m_backgroundColor = background;
emit backgroundColorChanged();
}
QColor IconItem::glowColor() const
{
return m_glowColor;
}
void IconItem::setGlowColor(QColor glow)
{
if (m_glowColor == glow) {
return;
}
m_glowColor = glow;
emit glowColorChanged();
}
void IconItem::updateColors()
{
QImage icon = m_iconPixmap.toImage();
if (icon.format() != QImage::Format_Invalid) {
float rtotal = 0, gtotal = 0, btotal = 0;
float total = 0.0f;
for(int row=0; row<icon.height(); ++row) {
QRgb *line = (QRgb *)icon.scanLine(row);
for(int col=0; col<icon.width(); ++col) {
QRgb pix = line[col];
int r = qRed(pix);
int g = qGreen(pix);
int b = qBlue(pix);
int a = qAlpha(pix);
float saturation = (qMax(r, qMax(g, b)) - qMin(r, qMin(g, b))) / 255.0f;
float relevance = .1 + .9 * (a / 255.0f) * saturation;
rtotal += (float)(r * relevance);
gtotal += (float)(g * relevance);
btotal += (float)(b * relevance);
total += relevance * 255;
}
}
int nr = (rtotal / total) * 255;
int ng = (gtotal / total) * 255;
int nb = (btotal / total) * 255;
QColor tempColor(nr, ng, nb);
if (tempColor.hsvSaturationF() > 0.15f) {
tempColor.setHsvF(tempColor.hueF(), 0.65f, tempColor.valueF());
}
tempColor.setHsvF(tempColor.hueF(), tempColor.saturationF(), 0.55f); //original 0.90f ???
setBackgroundColor(tempColor);
tempColor.setHsvF(tempColor.hueF(), tempColor.saturationF(), 1.0f);
setGlowColor(tempColor);
}
}
void IconItem::loadPixmap()
{
if (!isComponentComplete()) {
return;
}
const auto size = qMin(width(), height());
//final pixmap to paint
QPixmap result;
if (size <= 0) {
m_iconPixmap = QPixmap();
update();
return;
} else if (m_svgIcon) {
m_svgIcon->resize(size, size);
if (m_svgIcon->hasElement(m_svgIconName)) {
result = m_svgIcon->pixmap(m_svgIconName);
} else if (!m_svgIconName.isEmpty()) {
const auto *iconTheme = KIconLoader::global()->theme();
QString iconPath;
if (iconTheme) {
iconPath = iconTheme->iconPath(m_svgIconName + QLatin1String(".svg")
, static_cast<int>(qMin(width(), height()))
, KIconLoader::MatchBest);
if (iconPath.isEmpty()) {
iconPath = iconTheme->iconPath(m_svgIconName + QLatin1String(".svgz"),
static_cast<int>(qMin(width(), height()))
, KIconLoader::MatchBest);
}
} else {
qWarning() << "KIconLoader has no theme set";
}
if (!iconPath.isEmpty()) {
m_svgIcon->setImagePath(iconPath);
}
result = m_svgIcon->pixmap();
}
} else if (!m_icon.isNull()) {
result = m_icon.pixmap(QSize(static_cast<int>(size), static_cast<int>(size))
* (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()));
} else if (!m_imageIcon.isNull()) {
result = QPixmap::fromImage(m_imageIcon);
} else {
m_iconPixmap = QPixmap();
update();
return;
}
// Strangely KFileItem::overlays() returns empty string-values, so
// we need to check first whether an overlay must be drawn at all.
// It is more efficient to do it here, as KIconLoader::drawOverlays()
// assumes that an overlay will be drawn and has some additional
// setup time.
for (const QString &overlay : m_overlays) {
if (!overlay.isEmpty()) {
// There is at least one overlay, draw all overlays above m_pixmap
// and cancel the check
KIconLoader::global()->drawOverlays(m_overlays, result, KIconLoader::Desktop);
break;
}
}
if (!isEnabled()) {
result = KIconLoader::global()->iconEffect()->apply(result, KIconLoader::Desktop, KIconLoader::DisabledState);
} else if (m_active) {
result = KIconLoader::global()->iconEffect()->apply(result, KIconLoader::Desktop, KIconLoader::ActiveState);
}
m_iconPixmap = result;
if (m_providesColors && m_lastLoadedSourceId != m_lastColorsSourceId) {
m_lastColorsSourceId = m_lastLoadedSourceId;
updateColors();
}
m_textureChanged = true;
//don't animate initial setting
update();
}
void IconItem::itemChange(ItemChange change, const ItemChangeData &value)
{
QQuickItem::itemChange(change, value);
}
void IconItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
if (newGeometry.size() != oldGeometry.size()) {
m_sizeChanged = true;
if (newGeometry.width() > 1 && newGeometry.height() > 1) {
schedulePixmapUpdate();
} else {
update();
}
const auto oldSize = qMin(oldGeometry.size().width(), oldGeometry.size().height());
const auto newSize = qMin(newGeometry.size().width(), newGeometry.size().height());
if (!almost_equal(oldSize, newSize, 2)) {
emit paintedSizeChanged();
}
}
QQuickItem::geometryChanged(newGeometry, oldGeometry);
}
void IconItem::componentComplete()
{
QQuickItem::componentComplete();
schedulePixmapUpdate();
}
}
| 27.931553 | 152 | 0.591298 | VaughnValle |
5d15e34175c19f5eb32090cc765af9f62eaeef45 | 585 | cpp | C++ | ThirdParty/cppast/src/cpp_file.cpp | rokups/Urho3DNET | 66b21df316b569ef034c5032f741a378afafb061 | [
"MIT"
] | 5 | 2018-03-01T12:01:12.000Z | 2018-04-15T09:30:20.000Z | ThirdParty/cppast/src/cpp_file.cpp | rokups/Urho3DNET | 66b21df316b569ef034c5032f741a378afafb061 | [
"MIT"
] | 1 | 2018-02-17T17:32:37.000Z | 2018-03-03T03:51:11.000Z | ThirdParty/cppast/src/cpp_file.cpp | rokups/Urho3DNET | 66b21df316b569ef034c5032f741a378afafb061 | [
"MIT"
] | 2 | 2018-08-04T21:12:11.000Z | 2019-02-09T05:04:29.000Z | // Copyright (C) 2017-2018 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <cppast/cpp_file.hpp>
#include <cppast/cpp_entity_kind.hpp>
using namespace cppast;
cpp_entity_kind cpp_file::kind() noexcept
{
return cpp_entity_kind::file_t;
}
cpp_entity_kind cpp_file::do_get_entity_kind() const noexcept
{
return kind();
}
bool detail::cpp_file_ref_predicate::operator()(const cpp_entity& e)
{
return e.kind() == cpp_entity_kind::file_t;
}
| 23.4 | 74 | 0.755556 | rokups |
5d184b089a0766b1185c34f8932657fda107ae31 | 12,451 | cpp | C++ | dali/internal/event/actors/layer-impl.cpp | vcebollada/dali-core | 1f880695d4f6cb871db7f946538721e882ba1633 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | dali/internal/event/actors/layer-impl.cpp | vcebollada/dali-core | 1f880695d4f6cb871db7f946538721e882ba1633 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-03-22T10:19:17.000Z | 2020-03-22T10:19:17.000Z | dali/internal/event/actors/layer-impl.cpp | fayhot/dali-core | a69ea317f30961164520664a645ac36c387055ef | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/event/actors/layer-impl.h>
// EXTERNAL INCLUDES
// INTERNAL INCLUDES
#include <dali/public-api/actors/layer.h>
#include <dali/public-api/common/dali-common.h>
#include <dali/public-api/object/type-registry.h>
#include <dali/internal/event/actors/layer-list.h>
#include <dali/internal/event/common/property-helper.h>
#include <dali/internal/event/common/scene-impl.h>
#include <dali/internal/event/common/event-thread-services.h>
using Dali::Internal::SceneGraph::UpdateManager;
namespace Dali
{
namespace
{
typedef Layer::Behavior Behavior;
DALI_ENUM_TO_STRING_TABLE_BEGIN( BEHAVIOR )
DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_UI )
DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_3D )
DALI_ENUM_TO_STRING_TABLE_END( BEHAVIOR )
} // namespace
namespace Internal
{
namespace
{
// Properties
// Name Type writable animatable constraint-input enum for index-checking
DALI_PROPERTY_TABLE_BEGIN
DALI_PROPERTY( "clippingEnable", BOOLEAN, true, false, true, Dali::Layer::Property::CLIPPING_ENABLE )
DALI_PROPERTY( "clippingBox", RECTANGLE, true, false, true, Dali::Layer::Property::CLIPPING_BOX )
DALI_PROPERTY( "behavior", STRING, true, false, false, Dali::Layer::Property::BEHAVIOR )
DALI_PROPERTY_TABLE_END( DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX, LayerDefaultProperties )
// Actions
const char* const ACTION_RAISE = "raise";
const char* const ACTION_LOWER = "lower";
const char* const ACTION_RAISE_TO_TOP = "raiseToTop";
const char* const ACTION_LOWER_TO_BOTTOM = "lowerToBottom";
BaseHandle Create()
{
return Dali::Layer::New();
}
TypeRegistration mType( typeid( Dali::Layer ), typeid( Dali::Actor ), Create, LayerDefaultProperties );
TypeAction a1( mType, ACTION_RAISE, &Layer::DoAction );
TypeAction a2( mType, ACTION_LOWER, &Layer::DoAction );
TypeAction a3( mType, ACTION_RAISE_TO_TOP, &Layer::DoAction );
TypeAction a4( mType, ACTION_LOWER_TO_BOTTOM, &Layer::DoAction );
} // unnamed namespace
LayerPtr Layer::New()
{
// create node, nodes are owned by UpdateManager
SceneGraph::Layer* layerNode = SceneGraph::Layer::New();
OwnerPointer< SceneGraph::Node > transferOwnership( layerNode );
AddNodeMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership );
LayerPtr layer( new Layer( Actor::LAYER, *layerNode ) );
// Second-phase construction
layer->Initialize();
return layer;
}
LayerPtr Layer::NewRoot( LayerList& layerList )
{
// create node, nodes are owned by UpdateManager
SceneGraph::Layer* rootLayer = SceneGraph::Layer::New();
OwnerPointer< SceneGraph::Layer > transferOwnership( rootLayer );
InstallRootMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership );
LayerPtr root( new Layer( Actor::ROOT_LAYER, *rootLayer ) );
// root actor is immediately considered to be on-stage
root->mIsOnStage = true;
// The root actor will not emit a stage connection signal so set the signalled flag here as well
root->mOnStageSignalled = true;
// layer-list must be set for the root layer
root->mLayerList = &layerList;
layerList.SetRootLayer( &(*root) );
layerList.RegisterLayer( *root );
return root;
}
Layer::Layer( Actor::DerivedType type, const SceneGraph::Layer& layer )
: Actor( type, layer ),
mLayerList( NULL ),
mClippingBox( 0, 0, 0, 0 ),
mSortFunction( Layer::ZValue ),
mBehavior( Dali::Layer::LAYER_UI ),
mIsClipping( false ),
mDepthTestDisabled( true ),
mTouchConsumed( false ),
mHoverConsumed( false )
{
}
void Layer::OnInitialize()
{
}
Layer::~Layer()
{
if ( mIsRoot )
{
// Guard to allow handle destruction after Core has been destroyed
if( EventThreadServices::IsCoreRunning() )
{
UninstallRootMessage( GetEventThreadServices().GetUpdateManager(), &GetSceneLayerOnStage() );
GetEventThreadServices().UnregisterObject( this );
}
}
}
unsigned int Layer::GetDepth() const
{
return mLayerList ? mLayerList->GetDepth( this ) : 0u;
}
void Layer::Raise()
{
if ( mLayerList )
{
mLayerList->RaiseLayer(*this);
}
}
void Layer::Lower()
{
if ( mLayerList )
{
mLayerList->LowerLayer(*this);
}
}
void Layer::RaiseAbove( const Internal::Layer& target )
{
// cannot raise above ourself, both have to be on stage
if( ( this != &target ) && OnStage() && target.OnStage() )
{
// get parameters depth
const uint32_t targetDepth = target.GetDepth();
if( GetDepth() < targetDepth )
{
MoveAbove( target );
}
}
}
void Layer::LowerBelow( const Internal::Layer& target )
{
// cannot lower below ourself, both have to be on stage
if( ( this != &target ) && OnStage() && target.OnStage() )
{
// get parameters depth
const uint32_t targetDepth = target.GetDepth();
if( GetDepth() > targetDepth )
{
MoveBelow( target );
}
}
}
void Layer::RaiseToTop()
{
if ( mLayerList )
{
mLayerList->RaiseLayerToTop(*this);
}
}
void Layer::LowerToBottom()
{
if ( mLayerList )
{
mLayerList->LowerLayerToBottom(*this);
}
}
void Layer::MoveAbove( const Internal::Layer& target )
{
// cannot raise above ourself, both have to be on stage
if( ( this != &target ) && mLayerList && target.OnStage() )
{
mLayerList->MoveLayerAbove(*this, target );
}
}
void Layer::MoveBelow( const Internal::Layer& target )
{
// cannot lower below ourself, both have to be on stage
if( ( this != &target ) && mLayerList && target.OnStage() )
{
mLayerList->MoveLayerBelow(*this, target );
}
}
void Layer::SetBehavior( Dali::Layer::Behavior behavior )
{
mBehavior = behavior;
// Notify update side object.
SetBehaviorMessage( GetEventThreadServices(), GetSceneLayerOnStage(), behavior );
// By default, disable depth test for LAYER_UI, and enable for LAYER_3D.
SetDepthTestDisabled( mBehavior == Dali::Layer::LAYER_UI );
}
void Layer::SetClipping(bool enabled)
{
if (enabled != mIsClipping)
{
mIsClipping = enabled;
// layerNode is being used in a separate thread; queue a message to set the value
SetClippingMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mIsClipping );
}
}
void Layer::SetClippingBox(int x, int y, int width, int height)
{
if( ( x != mClippingBox.x ) ||
( y != mClippingBox.y ) ||
( width != mClippingBox.width ) ||
( height != mClippingBox.height ) )
{
// Clipping box is not animatable; this is the most up-to-date value
mClippingBox.Set(x, y, width, height);
// Convert mClippingBox to GL based coordinates (from bottom-left)
ClippingBox clippingBox( mClippingBox );
if( mScene )
{
clippingBox.y = static_cast<int32_t>( mScene->GetSize().height ) - clippingBox.y - clippingBox.height;
// layerNode is being used in a separate thread; queue a message to set the value
SetClippingBoxMessage( GetEventThreadServices(), GetSceneLayerOnStage(), clippingBox );
}
}
}
void Layer::SetDepthTestDisabled( bool disable )
{
if( disable != mDepthTestDisabled )
{
mDepthTestDisabled = disable;
// Send message.
// layerNode is being used in a separate thread; queue a message to set the value
SetDepthTestDisabledMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mDepthTestDisabled );
}
}
bool Layer::IsDepthTestDisabled() const
{
return mDepthTestDisabled;
}
void Layer::SetSortFunction(Dali::Layer::SortFunctionType function)
{
if( function != mSortFunction )
{
mSortFunction = function;
// layerNode is being used in a separate thread; queue a message to set the value
SetSortFunctionMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mSortFunction );
}
}
void Layer::SetTouchConsumed( bool consume )
{
mTouchConsumed = consume;
}
bool Layer::IsTouchConsumed() const
{
return mTouchConsumed;
}
void Layer::SetHoverConsumed( bool consume )
{
mHoverConsumed = consume;
}
bool Layer::IsHoverConsumed() const
{
return mHoverConsumed;
}
void Layer::OnStageConnectionInternal()
{
if ( !mIsRoot )
{
DALI_ASSERT_DEBUG( NULL == mLayerList );
// Find the ordered layer-list
for ( Actor* parent = mParent; parent != NULL; parent = parent->GetParent() )
{
if( parent->IsLayer() )
{
Layer* parentLayer = static_cast< Layer* >( parent ); // cheaper than dynamic_cast
mLayerList = parentLayer->mLayerList;
}
}
}
DALI_ASSERT_DEBUG( NULL != mLayerList );
mLayerList->RegisterLayer( *this );
}
void Layer::OnStageDisconnectionInternal()
{
mLayerList->UnregisterLayer(*this);
// mLayerList is only valid when on-stage
mLayerList = NULL;
}
const SceneGraph::Layer& Layer::GetSceneLayerOnStage() const
{
return static_cast< const SceneGraph::Layer& >( GetNode() ); // we know our node is a layer node
}
void Layer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
{
if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )
{
Actor::SetDefaultProperty( index, propertyValue );
}
else
{
switch( index )
{
case Dali::Layer::Property::CLIPPING_ENABLE:
{
SetClipping( propertyValue.Get<bool>() );
break;
}
case Dali::Layer::Property::CLIPPING_BOX:
{
Rect<int32_t> clippingBox( propertyValue.Get<Rect<int32_t> >() );
SetClippingBox( clippingBox.x, clippingBox.y, clippingBox.width, clippingBox.height );
break;
}
case Dali::Layer::Property::BEHAVIOR:
{
Behavior behavior(Dali::Layer::LAYER_UI);
if( Scripting::GetEnumeration< Behavior >( propertyValue.Get< std::string >().c_str(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT, behavior ) )
{
SetBehavior( behavior );
}
break;
}
default:
{
DALI_LOG_WARNING( "Unknown property (%d)\n", index );
break;
}
} // switch(index)
} // else
}
Property::Value Layer::GetDefaultProperty( Property::Index index ) const
{
Property::Value ret;
if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )
{
ret = Actor::GetDefaultProperty( index );
}
else
{
switch( index )
{
case Dali::Layer::Property::CLIPPING_ENABLE:
{
ret = mIsClipping;
break;
}
case Dali::Layer::Property::CLIPPING_BOX:
{
ret = mClippingBox;
break;
}
case Dali::Layer::Property::BEHAVIOR:
{
ret = Scripting::GetLinearEnumerationName< Behavior >( GetBehavior(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT );
break;
}
default:
{
DALI_LOG_WARNING( "Unknown property (%d)\n", index );
break;
}
} // switch(index)
}
return ret;
}
Property::Value Layer::GetDefaultPropertyCurrentValue( Property::Index index ) const
{
Property::Value ret;
if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT )
{
ret = Actor::GetDefaultPropertyCurrentValue( index );
}
else
{
ret = GetDefaultProperty( index ); // Layer only has event-side properties
}
return ret;
}
bool Layer::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& /*attributes*/ )
{
bool done = false;
Layer* layer = dynamic_cast<Layer*>( object );
if( layer )
{
if( 0 == actionName.compare( ACTION_RAISE ) )
{
layer->Raise();
done = true;
}
else if( 0 == actionName.compare( ACTION_LOWER ) )
{
layer->Lower();
done = true;
}
else if( 0 == actionName.compare( ACTION_RAISE_TO_TOP ) )
{
layer->RaiseToTop();
done = true;
}
else if( 0 == actionName.compare( ACTION_LOWER_TO_BOTTOM ) )
{
layer->LowerToBottom();
done = true;
}
}
return done;
}
} // namespace Internal
} // namespace Dali
| 25.410204 | 145 | 0.674886 | vcebollada |
5d1b2a4f682f4dd4ba7a71698dff5a1e231f6ddb | 1,943 | cpp | C++ | firmware/src/main.cpp | brianpepin/lpm | 969105a6374fa65c2de4e74a119d614b32e6ea2c | [
"MIT"
] | 3 | 2020-06-02T01:23:18.000Z | 2022-02-25T22:20:24.000Z | firmware/src/main.cpp | brianpepin/lpm | 969105a6374fa65c2de4e74a119d614b32e6ea2c | [
"MIT"
] | null | null | null | firmware/src/main.cpp | brianpepin/lpm | 969105a6374fa65c2de4e74a119d614b32e6ea2c | [
"MIT"
] | null | null | null | #include <globals.h>
#include <adc.h>
#include <battery.h>
#include <button.h>
#include <power.h>
#include <flash.h>
#include <logger.h>
#include <views/default.h>
Button buttons[] =
{
{PIN_UP, BUTTON_ACTIVE_LOW},
{PIN_DOWN, BUTTON_ACTIVE_LOW},
{PIN_LEFT, BUTTON_ACTIVE_LOW},
{PIN_RIGHT, BUTTON_ACTIVE_LOW},
{PIN_SELECT, BUTTON_ACTIVE_LOW}
};
DPad dpad(buttons);
DefaultView defaultView;
View *currentView;
void setup()
{
Serial.begin(9600);
Power::init();
display.begin();
Flash::init();
Adc::init();
Battery::init();
Logger::init();
pinMode(PIN_UP, INPUT_PULLUP);
pinMode(PIN_DOWN, INPUT_PULLUP);
pinMode(PIN_LEFT, INPUT_PULLUP);
pinMode(PIN_RIGHT, INPUT_PULLUP);
pinMode(PIN_SELECT, INPUT_PULLUP);
// Start reading all button state
// so buttons held down during
// power up are ignored.
for (unsigned int i = 0; i < COUNT_OF(buttons); i++)
{
buttons[i].zero();
}
defaultView.init(nullptr);
currentView = &defaultView;
}
void loop()
{
DPad::Action action = dpad.read();
if (action.button == Button_Select)
{
Power::processPowerButton(action.state);
}
Power::tick();
if (action.state.changed || Battery::isCharging() || Logger::isLogging())
{
Power::resetSleep();
}
bool newReading = Adc::update();
bool updated = currentView->processDpad(action, ¤tView);
updated |= currentView->update(newReading);
updated |= Battery::update();
if (newReading && Logger::isLogging())
{
int32_t reading;
Adc::read(&reading);
if (reading < 0)
{
reading = 0;
}
updated |= Logger::update(reading);
}
if (updated)
{
display.firstPage();
display.setFontDirection(0);
do
{
currentView->render();
Battery::render();
Logger::render();
} while (display.nextPage());
}
if (Battery::isDepleted())
{
Power::turnOff();
}
} | 18.158879 | 75 | 0.626866 | brianpepin |
5d1d823c10e30cee858f14367fe30222b494d526 | 1,256 | hpp | C++ | gapvector_impl/gapvector_reverse_iterator_implement.hpp | Catminusminus/gapvector | cdc235fbf26022a12234057877e6189a9312c0b7 | [
"Unlicense"
] | null | null | null | gapvector_impl/gapvector_reverse_iterator_implement.hpp | Catminusminus/gapvector | cdc235fbf26022a12234057877e6189a9312c0b7 | [
"Unlicense"
] | 2 | 2018-03-26T14:06:23.000Z | 2018-03-29T17:08:45.000Z | gapvector_impl/gapvector_reverse_iterator_implement.hpp | Catminusminus/gapvector | cdc235fbf26022a12234057877e6189a9312c0b7 | [
"Unlicense"
] | null | null | null | #ifndef GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP
#define GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP
template <typename T>
void gapvectorReverseIterator<T>::increment()
{
--index;
}
template <typename T>
void gapvectorReverseIterator<T>::decrement()
{
++index;
}
template <typename T>
T &gapvectorReverseIterator<T>::dereference() const
{
return (gap_vector->at(index - 1));
}
template <typename T>
bool gapvectorReverseIterator<T>::equal(const gapvectorReverseIterator<T> &anotherIterator) const
{
return (this->gap_vector == anotherIterator.gap_vector && this->index == anotherIterator.index);
}
template <typename T>
size_t gapvectorReverseIterator<T>::distance_to(const gapvectorReverseIterator<T> &anotherIterator) const
{
if (this->index >= anotherIterator.index)
{
return this->index - anotherIterator.index;
}
return anotherIterator.index - this->index;
}
template <typename T>
void gapvectorReverseIterator<T>::advance(size_t difference)
{
index -= difference;
}
template <typename T>
gapvectorReverseIterator<T>::gapvectorReverseIterator()
{
}
template <typename T>
gapvectorReverseIterator<T>::gapvectorReverseIterator(gapvector<T> *gap_v, size_t ind) : gap_vector(gap_v), index(ind)
{
}
#endif
| 22.836364 | 118 | 0.754777 | Catminusminus |
5d29761d3684c04b79fec3c3688e9df1d29eaf01 | 4,449 | cpp | C++ | Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 110 | 2018-10-20T21:47:54.000Z | 2022-03-14T03:47:58.000Z | Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 68 | 2018-12-19T09:08:56.000Z | 2022-03-09T06:43:38.000Z | Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 45 | 2018-12-03T14:35:47.000Z | 2022-03-05T01:35:24.000Z | // Copyright 2015-2020 Piperift. All Rights Reserved.
#include "ClassFilterNode.h"
#include <Engine/Blueprint.h>
#include <PropertyHandle.h>
#include "Misc/ClassFilter.h"
FSEClassFilterNode::FSEClassFilterNode(const FString& InClassName, const FString& InClassDisplayName)
{
ClassName = InClassName;
ClassDisplayName = InClassDisplayName;
bPassesFilter = false;
bIsBPNormalType = false;
Class = nullptr;
Blueprint = nullptr;
}
FSEClassFilterNode::FSEClassFilterNode( const FSEClassFilterNode& InCopyObject)
{
ClassName = InCopyObject.ClassName;
ClassDisplayName = InCopyObject.ClassDisplayName;
bPassesFilter = InCopyObject.bPassesFilter;
FilterState = InCopyObject.FilterState;
Class = InCopyObject.Class;
Blueprint = InCopyObject.Blueprint;
UnloadedBlueprintData = InCopyObject.UnloadedBlueprintData;
ClassPath = InCopyObject.ClassPath;
ParentClassPath = InCopyObject.ParentClassPath;
ClassName = InCopyObject.ClassName;
BlueprintAssetPath = InCopyObject.BlueprintAssetPath;
bIsBPNormalType = InCopyObject.bIsBPNormalType;
// We do not want to copy the child list, do not add it. It should be the only item missing.
}
/**
* Adds the specified child to the node.
*
* @param Child The child to be added to this node for the tree.
*/
void FSEClassFilterNode::AddChild(FSEClassFilterNodePtr& Child)
{
ChildrenList.Add(Child);
Child->ParentNode = TSharedRef<FSEClassFilterNode>{ AsShared() };
}
void FSEClassFilterNode::AddUniqueChild(FSEClassFilterNodePtr& Child)
{
check(Child.IsValid());
if (const UClass* NewChildClass = Child->Class.Get())
{
for (auto& CurrentChild : ChildrenList)
{
if (CurrentChild.IsValid() && CurrentChild->Class == NewChildClass)
{
const bool bNewChildHasMoreInfo = Child->UnloadedBlueprintData.IsValid();
const bool bOldChildHasMoreInfo = CurrentChild->UnloadedBlueprintData.IsValid();
if (bNewChildHasMoreInfo && !bOldChildHasMoreInfo)
{
// make sure, that new child has all needed children
for (int OldChildIndex = 0; OldChildIndex < CurrentChild->ChildrenList.Num(); ++OldChildIndex)
{
Child->AddUniqueChild(CurrentChild->ChildrenList[OldChildIndex]);
}
// replace child
CurrentChild = Child;
}
return;
}
}
}
AddChild(Child);
}
FString FSEClassFilterNode::GetClassName(EClassViewerNameTypeToDisplay NameType) const
{
switch (NameType)
{
case EClassViewerNameTypeToDisplay::ClassName:
return ClassName;
case EClassViewerNameTypeToDisplay::DisplayName:
return ClassDisplayName;
case EClassViewerNameTypeToDisplay::Dynamic:
FString CombinedName;
FString SanitizedName = FName::NameToDisplayString(ClassName, false);
if (ClassDisplayName.IsEmpty() && !ClassDisplayName.Equals(SanitizedName) && !ClassDisplayName.Equals(ClassName))
{
TArray<FStringFormatArg> Args;
Args.Add(ClassName);
Args.Add(ClassDisplayName);
CombinedName = FString::Format(TEXT("{0} ({1})"), Args);
}
else
{
CombinedName = ClassName;
}
return MoveTemp(CombinedName);
}
ensureMsgf(false, TEXT("FSEClassFilterNode::GetClassName called with invalid name type."));
return ClassName;
}
FText FSEClassFilterNode::GetClassTooltip(bool bShortTooltip) const
{
if (Class.IsValid())
{
return Class->GetToolTipText(bShortTooltip);
}
else if (Blueprint.IsValid() && Blueprint->GeneratedClass)
{
// #NOTE: Unloaded blueprint classes won't show tooltip for now
return Blueprint->GeneratedClass->GetToolTipText(bShortTooltip);
}
return FText::GetEmpty();
}
bool FSEClassFilterNode::IsBlueprintClass() const
{
return BlueprintAssetPath != NAME_None;
}
void FSEClassFilterNode::SetOwnFilterState(EClassFilterState State)
{
FilterState = State;
}
void FSEClassFilterNode::SetStateFromFilter(const FSEClassFilter& Filter)
{
const TSoftClassPtr<> ClassAsset{ ClassPath.ToString() };
if (Filter.AllowedClasses.Contains(ClassAsset))
{
FilterState = EClassFilterState::Allowed;
}
else if (Filter.IgnoredClasses.Contains(ClassAsset))
{
FilterState = EClassFilterState::Denied;
}
else
{
FilterState = EClassFilterState::None;
}
}
EClassFilterState FSEClassFilterNode::GetParentFilterState() const
{
FSEClassFilterNodePtr Parent = ParentNode.Pin();
while (Parent)
{
// return first parent found filter
if (Parent->FilterState != EClassFilterState::None)
return Parent->FilterState;
Parent = Parent->ParentNode.Pin();
}
return EClassFilterState::None;
}
| 26.017544 | 115 | 0.757249 | foobit |
5d2a22a3ee1d87aaad98253af00bf68a0238fa0e | 2,820 | cpp | C++ | libs/network/src/p2pservice/identity_cache.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | null | null | null | libs/network/src/p2pservice/identity_cache.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | null | null | null | libs/network/src/p2pservice/identity_cache.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | 2 | 2019-11-13T10:55:24.000Z | 2019-11-13T11:37:09.000Z | //------------------------------------------------------------------------------
//
// 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 "network/p2pservice/identity_cache.hpp"
#include <algorithm>
#include <iterator>
namespace fetch {
namespace p2p {
void IdentityCache::Update(ConnectionMap const &connections)
{
FETCH_LOCK(lock_);
for (auto const &element : connections)
{
auto const &address = element.first;
auto const &uri = element.second;
UpdateInternal(address, uri);
}
}
void IdentityCache::Update(Address const &address, Uri const &uri)
{
FETCH_LOCK(lock_);
UpdateInternal(address, uri);
}
bool IdentityCache::Lookup(Address const &address, Uri &uri) const
{
bool success = false;
FETCH_LOCK(lock_);
auto it = cache_.find(address);
if (it != cache_.end())
{
uri = it->second.uri;
success = true;
}
return success;
}
IdentityCache::AddressSet IdentityCache::FilterOutUnresolved(AddressSet const &addresses)
{
AddressSet resolvedAddresses;
{
FETCH_LOCK(lock_);
std::copy_if(addresses.begin(), addresses.end(),
std::inserter(resolvedAddresses, resolvedAddresses.begin()),
[this](Address const &address) {
bool resolved = false;
auto it = cache_.find(address);
if ((it != cache_.end()) && (it->second.uri.scheme() != Uri::Scheme::Muddle))
{
resolved = true;
}
return resolved;
});
}
return resolvedAddresses;
}
void IdentityCache::UpdateInternal(Address const &address, Uri const &uri)
{
auto cache_it = cache_.find(address);
if (cache_it != cache_.end())
{
auto &cache_entry = cache_it->second;
// if the cache entry exists them only update it if the
if (uri.scheme() != Uri::Scheme::Muddle)
{
cache_entry.uri = uri;
cache_entry.last_update = Clock::now();
cache_entry.resolve = false; // This entry is considered resolved
}
}
else
{
cache_.emplace(address, uri);
}
}
} // namespace p2p
} // namespace fetch
| 25.87156 | 96 | 0.599645 | jinmannwong |
5d2a6ba7920af77702281f15fe3eef4a488cbdd0 | 21,032 | cpp | C++ | planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | null | null | null | planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | null | null | null | planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 TIER IV, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "obstacle_cruise_planner/pid_based_planner/pid_based_planner.hpp"
#include "obstacle_cruise_planner/utils.hpp"
#include "tier4_autoware_utils/tier4_autoware_utils.hpp"
#include "tier4_planning_msgs/msg/velocity_limit.hpp"
namespace
{
StopSpeedExceeded createStopSpeedExceededMsg(
const rclcpp::Time & current_time, const bool stop_flag)
{
StopSpeedExceeded msg{};
msg.stamp = current_time;
msg.stop_speed_exceeded = stop_flag;
return msg;
}
VelocityLimit createVelocityLimitMsg(
const rclcpp::Time & current_time, const double vel, const double acc, const double max_jerk,
const double min_jerk)
{
VelocityLimit msg;
msg.stamp = current_time;
msg.sender = "obstacle_cruise_planner";
msg.use_constraints = true;
msg.max_velocity = vel;
if (acc < 0) {
msg.constraints.min_acceleration = acc;
}
msg.constraints.max_jerk = max_jerk;
msg.constraints.min_jerk = min_jerk;
return msg;
}
Float32MultiArrayStamped convertDebugValuesToMsg(
const rclcpp::Time & current_time, const DebugValues & debug_values)
{
Float32MultiArrayStamped debug_msg{};
debug_msg.stamp = current_time;
for (const auto & v : debug_values.getValues()) {
debug_msg.data.push_back(v);
}
return debug_msg;
}
template <class T>
size_t getIndexWithLongitudinalOffset(
const T & points, const double longitudinal_offset, boost::optional<size_t> start_idx)
{
if (points.empty()) {
throw std::logic_error("points is empty.");
}
if (start_idx) {
if (/*start_idx.get() < 0 || */ points.size() <= start_idx.get()) {
throw std::out_of_range("start_idx is out of range.");
}
} else {
if (longitudinal_offset > 0) {
start_idx = 0;
} else {
start_idx = points.size() - 1;
}
}
double sum_length = 0.0;
if (longitudinal_offset > 0) {
for (size_t i = start_idx.get(); i < points.size() - 1; ++i) {
const double segment_length =
tier4_autoware_utils::calcDistance2d(points.at(i), points.at(i + 1));
sum_length += segment_length;
if (sum_length >= longitudinal_offset) {
const double front_length = segment_length;
const double back_length = sum_length - longitudinal_offset;
if (front_length < back_length) {
return i;
} else {
return i + 1;
}
}
}
return points.size() - 1;
}
for (size_t i = start_idx.get(); i > 0; --i) {
const double segment_length =
tier4_autoware_utils::calcDistance2d(points.at(i), points.at(i + 1));
sum_length += segment_length;
if (sum_length >= -longitudinal_offset) {
const double front_length = segment_length;
const double back_length = sum_length + longitudinal_offset;
if (front_length < back_length) {
return i;
} else {
return i + 1;
}
}
}
return 0;
}
double calcMinimumDistanceToStop(const double initial_vel, const double min_acc)
{
return -std::pow(initial_vel, 2) / 2.0 / min_acc;
}
tier4_planning_msgs::msg::StopReasonArray makeStopReasonArray(
const rclcpp::Time & current_time, const geometry_msgs::msg::Pose & stop_pose,
const boost::optional<PIDBasedPlanner::StopObstacleInfo> & stop_obstacle_info)
{
// create header
std_msgs::msg::Header header;
header.frame_id = "map";
header.stamp = current_time;
// create stop factor
tier4_planning_msgs::msg::StopFactor stop_factor;
stop_factor.stop_pose = stop_pose;
if (stop_obstacle_info) {
stop_factor.stop_factor_points.emplace_back(stop_obstacle_info->obstacle.collision_point);
}
// create stop reason stamped
tier4_planning_msgs::msg::StopReason stop_reason_msg;
stop_reason_msg.reason = tier4_planning_msgs::msg::StopReason::OBSTACLE_STOP;
stop_reason_msg.stop_factors.emplace_back(stop_factor);
// create stop reason array
tier4_planning_msgs::msg::StopReasonArray stop_reason_array;
stop_reason_array.header = header;
stop_reason_array.stop_reasons.emplace_back(stop_reason_msg);
return stop_reason_array;
}
} // namespace
PIDBasedPlanner::PIDBasedPlanner(
rclcpp::Node & node, const LongitudinalInfo & longitudinal_info,
const vehicle_info_util::VehicleInfo & vehicle_info)
: PlannerInterface(node, longitudinal_info, vehicle_info)
{
min_accel_during_cruise_ =
node.declare_parameter<double>("pid_based_planner.min_accel_during_cruise");
// pid controller
const double kp = node.declare_parameter<double>("pid_based_planner.kp");
const double ki = node.declare_parameter<double>("pid_based_planner.ki");
const double kd = node.declare_parameter<double>("pid_based_planner.kd");
pid_controller_ = std::make_unique<PIDController>(kp, ki, kd);
output_ratio_during_accel_ =
node.declare_parameter<double>("pid_based_planner.output_ratio_during_accel");
// some parameters
// use_predicted_obstacle_pose_ =
// node.declare_parameter<bool>("pid_based_planner.use_predicted_obstacle_pose");
vel_to_acc_weight_ = node.declare_parameter<double>("pid_based_planner.vel_to_acc_weight");
min_cruise_target_vel_ =
node.declare_parameter<double>("pid_based_planner.min_cruise_target_vel");
obstacle_velocity_threshold_from_cruise_to_stop_ = node.declare_parameter<double>(
"pid_based_planner.obstacle_velocity_threshold_from_cruise_to_stop");
// publisher
stop_reasons_pub_ =
node.create_publisher<tier4_planning_msgs::msg::StopReasonArray>("~/output/stop_reasons", 1);
stop_speed_exceeded_pub_ =
node.create_publisher<StopSpeedExceeded>("~/output/stop_speed_exceeded", 1);
debug_values_pub_ = node.create_publisher<Float32MultiArrayStamped>("~/debug/values", 1);
}
Trajectory PIDBasedPlanner::generateTrajectory(
const ObstacleCruisePlannerData & planner_data, boost::optional<VelocityLimit> & vel_limit,
DebugData & debug_data)
{
stop_watch_.tic(__func__);
debug_values_.resetValues();
// calc obstacles to cruise and stop
boost::optional<StopObstacleInfo> stop_obstacle_info;
boost::optional<CruiseObstacleInfo> cruise_obstacle_info;
calcObstaclesToCruiseAndStop(planner_data, stop_obstacle_info, cruise_obstacle_info);
// plan cruise
planCruise(planner_data, vel_limit, cruise_obstacle_info, debug_data);
// plan stop
const auto output_traj = planStop(planner_data, stop_obstacle_info, debug_data);
// publish debug values
publishDebugValues(planner_data);
const double calculation_time = stop_watch_.toc(__func__);
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_,
" %s := %f [ms]", __func__, calculation_time);
return output_traj;
}
void PIDBasedPlanner::calcObstaclesToCruiseAndStop(
const ObstacleCruisePlannerData & planner_data,
boost::optional<StopObstacleInfo> & stop_obstacle_info,
boost::optional<CruiseObstacleInfo> & cruise_obstacle_info)
{
debug_values_.setValues(DebugValues::TYPE::CURRENT_VELOCITY, planner_data.current_vel);
debug_values_.setValues(DebugValues::TYPE::CURRENT_ACCELERATION, planner_data.current_acc);
// search highest probability obstacle for stop and cruise
for (const auto & obstacle : planner_data.target_obstacles) {
// NOTE: from ego's front to obstacle's back
const double dist_to_obstacle = calcDistanceToObstacle(planner_data, obstacle);
const bool is_stop_required = isStopRequired(obstacle);
if (is_stop_required) { // stop
// calculate error distance (= distance to stop)
const double error_dist = dist_to_obstacle - longitudinal_info_.safe_distance_margin;
if (stop_obstacle_info) {
if (error_dist > stop_obstacle_info->dist_to_stop) {
return;
}
}
stop_obstacle_info = StopObstacleInfo(obstacle, error_dist);
// update debug values
debug_values_.setValues(DebugValues::TYPE::STOP_CURRENT_OBJECT_DISTANCE, dist_to_obstacle);
debug_values_.setValues(DebugValues::TYPE::STOP_CURRENT_OBJECT_VELOCITY, obstacle.velocity);
debug_values_.setValues(
DebugValues::TYPE::STOP_TARGET_OBJECT_DISTANCE, longitudinal_info_.safe_distance_margin);
debug_values_.setValues(
DebugValues::TYPE::STOP_TARGET_ACCELERATION, longitudinal_info_.min_strong_accel);
debug_values_.setValues(DebugValues::TYPE::STOP_ERROR_OBJECT_DISTANCE, error_dist);
} else { // cruise
// calculate distance between ego and obstacle based on RSS
const double rss_dist = calcRSSDistance(
planner_data.current_vel, obstacle.velocity, longitudinal_info_.safe_distance_margin);
// calculate error distance and normalized one
const double error_dist = dist_to_obstacle - rss_dist;
if (cruise_obstacle_info) {
if (error_dist > cruise_obstacle_info->dist_to_cruise) {
return;
}
}
const double normalized_dist_to_cruise = error_dist / dist_to_obstacle;
cruise_obstacle_info = CruiseObstacleInfo(obstacle, error_dist, normalized_dist_to_cruise);
// update debug values
debug_values_.setValues(DebugValues::TYPE::CRUISE_CURRENT_OBJECT_VELOCITY, obstacle.velocity);
debug_values_.setValues(DebugValues::TYPE::CRUISE_CURRENT_OBJECT_DISTANCE, dist_to_obstacle);
debug_values_.setValues(DebugValues::TYPE::CRUISE_TARGET_OBJECT_DISTANCE, rss_dist);
debug_values_.setValues(DebugValues::TYPE::CRUISE_ERROR_OBJECT_DISTANCE, error_dist);
}
}
}
double PIDBasedPlanner::calcDistanceToObstacle(
const ObstacleCruisePlannerData & planner_data, const TargetObstacle & obstacle)
{
const double offset = vehicle_info_.max_longitudinal_offset_m;
// TODO(murooka) enable this option considering collision_point (precise obstacle point to measure
// distance) if (use_predicted_obstacle_pose_) {
// // interpolate current obstacle pose from predicted path
// const auto current_interpolated_obstacle_pose =
// obstacle_cruise_utils::getCurrentObjectPoseFromPredictedPath(
// obstacle.predicted_paths.at(0), obstacle.time_stamp, planner_data.current_time);
// if (current_interpolated_obstacle_pose) {
// return tier4_autoware_utils::calcSignedArcLength(
// planner_data.traj.points, planner_data.current_pose.position,
// current_interpolated_obstacle_pose->position) - offset;
// }
//
// RCLCPP_INFO_EXPRESSION(
// rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), true,
// "Failed to interpolated obstacle pose from predicted path. Use non-interpolated obstacle
// pose.");
// }
const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose);
return tier4_autoware_utils::calcSignedArcLength(
planner_data.traj.points, ego_idx, obstacle.collision_point) -
offset;
}
// Note: If stop planning is not required, cruise planning will be done instead.
bool PIDBasedPlanner::isStopRequired(const TargetObstacle & obstacle)
{
const bool is_cruise_obstacle = isCruiseObstacle(obstacle.classification.label);
const bool is_stop_obstacle = isStopObstacle(obstacle.classification.label);
if (is_cruise_obstacle) {
return std::abs(obstacle.velocity) < obstacle_velocity_threshold_from_cruise_to_stop_;
} else if (is_stop_obstacle && !is_cruise_obstacle) {
return true;
}
return false;
}
Trajectory PIDBasedPlanner::planStop(
const ObstacleCruisePlannerData & planner_data,
const boost::optional<StopObstacleInfo> & stop_obstacle_info, DebugData & debug_data)
{
bool will_collide_with_obstacle = false;
size_t zero_vel_idx = 0;
bool zero_vel_found = false;
if (stop_obstacle_info) {
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_,
"stop planning");
auto local_stop_obstacle_info = stop_obstacle_info.get();
// check if the ego will collide with the obstacle with a limit acceleration
const double feasible_dist_to_stop =
calcMinimumDistanceToStop(planner_data.current_vel, longitudinal_info_.min_strong_accel);
if (local_stop_obstacle_info.dist_to_stop < feasible_dist_to_stop) {
will_collide_with_obstacle = true;
local_stop_obstacle_info.dist_to_stop = feasible_dist_to_stop;
}
// set zero velocity index
const auto opt_zero_vel_idx = doStop(
planner_data, local_stop_obstacle_info, debug_data.obstacles_to_stop,
debug_data.stop_wall_marker);
if (opt_zero_vel_idx) {
zero_vel_idx = opt_zero_vel_idx.get();
zero_vel_found = true;
}
}
// generate output trajectory
auto output_traj = planner_data.traj;
if (zero_vel_found) {
// publish stop reason
const auto stop_pose = planner_data.traj.points.at(zero_vel_idx).pose;
const auto stop_reasons_msg =
makeStopReasonArray(planner_data.current_time, stop_pose, stop_obstacle_info);
stop_reasons_pub_->publish(stop_reasons_msg);
// insert zero_velocity
for (size_t traj_idx = zero_vel_idx; traj_idx < output_traj.points.size(); ++traj_idx) {
output_traj.points.at(traj_idx).longitudinal_velocity_mps = 0.0;
}
}
// publish stop_speed_exceeded if the ego will collide with the obstacle
const auto stop_speed_exceeded_msg =
createStopSpeedExceededMsg(planner_data.current_time, will_collide_with_obstacle);
stop_speed_exceeded_pub_->publish(stop_speed_exceeded_msg);
return output_traj;
}
boost::optional<size_t> PIDBasedPlanner::doStop(
const ObstacleCruisePlannerData & planner_data, const StopObstacleInfo & stop_obstacle_info,
std::vector<TargetObstacle> & debug_obstacles_to_stop,
visualization_msgs::msg::MarkerArray & debug_wall_marker) const
{
const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose);
// TODO(murooka) Should I use interpolation?
const auto modified_stop_info = [&]() -> boost::optional<std::pair<size_t, double>> {
const double dist_to_stop = stop_obstacle_info.dist_to_stop;
const size_t obstacle_zero_vel_idx =
getIndexWithLongitudinalOffset(planner_data.traj.points, dist_to_stop, ego_idx);
// check if there is already stop line between obstacle and zero_vel_idx
const auto behavior_zero_vel_idx =
tier4_autoware_utils::searchZeroVelocityIndex(planner_data.traj.points);
if (behavior_zero_vel_idx) {
const double zero_vel_diff_length = tier4_autoware_utils::calcSignedArcLength(
planner_data.traj.points, obstacle_zero_vel_idx, behavior_zero_vel_idx.get());
if (
0 < zero_vel_diff_length &&
zero_vel_diff_length < longitudinal_info_.safe_distance_margin) {
const double modified_dist_to_stop =
dist_to_stop + longitudinal_info_.safe_distance_margin - min_behavior_stop_margin_;
const size_t modified_obstacle_zero_vel_idx =
getIndexWithLongitudinalOffset(planner_data.traj.points, modified_dist_to_stop, ego_idx);
return std::make_pair(modified_obstacle_zero_vel_idx, modified_dist_to_stop);
}
}
return std::make_pair(obstacle_zero_vel_idx, dist_to_stop);
}();
if (!modified_stop_info) {
return {};
}
const size_t modified_zero_vel_idx = modified_stop_info->first;
const double modified_dist_to_stop = modified_stop_info->second;
// virtual wall marker for stop
const auto marker_pose = obstacle_cruise_utils::calcForwardPose(
planner_data.traj, ego_idx, modified_dist_to_stop + vehicle_info_.max_longitudinal_offset_m);
if (marker_pose) {
visualization_msgs::msg::MarkerArray wall_msg;
const auto markers = tier4_autoware_utils::createStopVirtualWallMarker(
marker_pose.get(), "obstacle stop", planner_data.current_time, 0);
tier4_autoware_utils::appendMarkerArray(markers, &debug_wall_marker);
}
debug_obstacles_to_stop.push_back(stop_obstacle_info.obstacle);
return modified_zero_vel_idx;
}
void PIDBasedPlanner::planCruise(
const ObstacleCruisePlannerData & planner_data, boost::optional<VelocityLimit> & vel_limit,
const boost::optional<CruiseObstacleInfo> & cruise_obstacle_info, DebugData & debug_data)
{
// do cruise
if (cruise_obstacle_info) {
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_,
"cruise planning");
vel_limit = doCruise(
planner_data, cruise_obstacle_info.get(), debug_data.obstacles_to_cruise,
debug_data.cruise_wall_marker);
// update debug values
debug_values_.setValues(DebugValues::TYPE::CRUISE_TARGET_VELOCITY, vel_limit->max_velocity);
debug_values_.setValues(
DebugValues::TYPE::CRUISE_TARGET_ACCELERATION, vel_limit->constraints.min_acceleration);
} else {
// reset previous target velocity if adaptive cruise is not enabled
prev_target_vel_ = {};
}
}
VelocityLimit PIDBasedPlanner::doCruise(
const ObstacleCruisePlannerData & planner_data, const CruiseObstacleInfo & cruise_obstacle_info,
std::vector<TargetObstacle> & debug_obstacles_to_cruise,
visualization_msgs::msg::MarkerArray & debug_wall_marker)
{
const double dist_to_cruise = cruise_obstacle_info.dist_to_cruise;
const double normalized_dist_to_cruise = cruise_obstacle_info.normalized_dist_to_cruise;
const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose);
// calculate target velocity with acceleration limit by PID controller
const double pid_output_vel = pid_controller_->calc(normalized_dist_to_cruise);
[[maybe_unused]] const double prev_vel =
prev_target_vel_ ? prev_target_vel_.get() : planner_data.current_vel;
const double additional_vel = [&]() {
if (normalized_dist_to_cruise > 0) {
return pid_output_vel * output_ratio_during_accel_;
}
return pid_output_vel;
}();
const double positive_target_vel =
std::max(min_cruise_target_vel_, planner_data.current_vel + additional_vel);
// calculate target acceleration
const double target_acc = vel_to_acc_weight_ * additional_vel;
const double target_acc_with_acc_limit =
std::clamp(target_acc, min_accel_during_cruise_, longitudinal_info_.max_accel);
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_,
"target_velocity %f", positive_target_vel);
prev_target_vel_ = positive_target_vel;
// set target longitudinal motion
const auto vel_limit = createVelocityLimitMsg(
planner_data.current_time, positive_target_vel, target_acc_with_acc_limit,
longitudinal_info_.max_jerk, longitudinal_info_.min_jerk);
// virtual wall marker for cruise
const double dist_to_rss_wall = dist_to_cruise + vehicle_info_.max_longitudinal_offset_m;
const size_t wall_idx =
getIndexWithLongitudinalOffset(planner_data.traj.points, dist_to_rss_wall, ego_idx);
const auto markers = tier4_autoware_utils::createSlowDownVirtualWallMarker(
planner_data.traj.points.at(wall_idx).pose, "obstacle cruise", planner_data.current_time, 0);
tier4_autoware_utils::appendMarkerArray(markers, &debug_wall_marker);
debug_obstacles_to_cruise.push_back(cruise_obstacle_info.obstacle);
return vel_limit;
}
void PIDBasedPlanner::publishDebugValues(const ObstacleCruisePlannerData & planner_data) const
{
const auto debug_values_msg = convertDebugValuesToMsg(planner_data.current_time, debug_values_);
debug_values_pub_->publish(debug_values_msg);
}
void PIDBasedPlanner::updateParam(const std::vector<rclcpp::Parameter> & parameters)
{
tier4_autoware_utils::updateParam<double>(
parameters, "pid_based_planner.min_accel_during_cruise", min_accel_during_cruise_);
// pid controller
double kp = pid_controller_->getKp();
double ki = pid_controller_->getKi();
double kd = pid_controller_->getKd();
tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.kp", kp);
tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.ki", ki);
tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.kd", kd);
tier4_autoware_utils::updateParam<double>(
parameters, "pid_based_planner.output_ratio_during_accel", output_ratio_during_accel_);
// vel_to_acc_weight
tier4_autoware_utils::updateParam<double>(
parameters, "pid_based_planner.vel_to_acc_weight", vel_to_acc_weight_);
// min_cruise_target_vel
tier4_autoware_utils::updateParam<double>(
parameters, "pid_based_planner.min_cruise_target_vel", min_cruise_target_vel_);
pid_controller_->updateParam(kp, ki, kd);
}
| 39.092937 | 100 | 0.762695 | meliketanrikulu |
5d2ae93d56c7a02e788a2ad9a65b4c3e67236086 | 6,034 | cpp | C++ | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor_STM32 | 2aaba95728936b2d5784e99b96c208a94e3cb8df | [
"MIT"
] | null | null | null | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor_STM32 | 2aaba95728936b2d5784e99b96c208a94e3cb8df | [
"MIT"
] | 36 | 2019-03-24T14:43:25.000Z | 2021-01-11T00:05:30.000Z | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor | 46e022f1791c8644955135c630fdd12a4296e44d | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* hw_rcc_sys_ctrl.cpp
*
* Description:
* System clock controller implementation
*
* 2021 | Brandon Braun | brandonbraun653@gmail.com
*******************************************************************************/
/* Chimera Includes */
#include <Chimera/assert>
#include <Chimera/common>
#include <Chimera/clock>
/* Driver Includes */
#include <Thor/cfg>
#include <Thor/lld/common/cortex-m4/system_time.hpp>
#include <Thor/lld/interface/inc/rcc>
#include <Thor/lld/interface/inc/power>
#include <Thor/lld/interface/inc/flash>
#include <Thor/lld/interface/inc/interrupt>
#include <Thor/lld/stm32f4x/rcc/hw_rcc_prv.hpp>
namespace Thor::LLD::RCC
{
/*-------------------------------------------------------------------------------
Static Data
-------------------------------------------------------------------------------*/
static SystemClock s_system_clock;
/*-------------------------------------------------------------------------------
SystemClock Class Implementation
-------------------------------------------------------------------------------*/
SystemClock *getCoreClockCtrl()
{
return &s_system_clock;
}
SystemClock::SystemClock()
{
initialize();
}
SystemClock::~SystemClock()
{
}
void SystemClock::enableClock( const Chimera::Clock::Bus clock )
{
auto isrMask = INT::disableInterrupts();
switch ( clock )
{
case Chimera::Clock::Bus::HSE:
HSEON::set( RCC1_PERIPH, CR_HSEON );
while ( !HSERDY::get( RCC1_PERIPH ) )
{
;
}
break;
case Chimera::Clock::Bus::HSI16:
enableHSI();
break;
case Chimera::Clock::Bus::LSI:
enableLSI();
break;
default:
RT_HARD_ASSERT( false );
break;
}
INT::enableInterrupts( isrMask );
}
Chimera::Status_t SystemClock::configureProjectClocks()
{
/*-------------------------------------------------
Set flash latency to a safe value for all possible
clocks. This will slow down the configuration, but
this is only performed once at startup.
-------------------------------------------------*/
FLASH::setLatency( 15 );
/*------------------------------------------------
Not strictly necessary, but done because this
config function uses the max system clock.
------------------------------------------------*/
PWR::setOverdriveMode( true );
/*------------------------------------------------
Configure the system clocks to max performance
------------------------------------------------*/
constexpr size_t hsiClkIn = 16000000; // 16 MHz
constexpr size_t targetSysClk = 120000000; // 120 MHz
constexpr size_t targetUSBClk = 48000000; // 48 MHz
constexpr size_t targetVcoClk = 2 * targetSysClk; // 240 MHz
Chimera::Status_t cfgResult = Chimera::Status::OK;
ClockTreeInit clkCfg;
clkCfg.clear();
/* Select which clocks to turn on */
clkCfg.enabled.hsi = true; // Needed for transfer of clock source
clkCfg.enabled.lsi = true; // Allows IWDG use
clkCfg.enabled.pll_core_clk = true; // Will drive sys off PLL
clkCfg.enabled.pll_core_q = true; // USB 48 MHz clock
/* Select clock mux routing */
clkCfg.mux.pll = Chimera::Clock::Bus::HSI16;
clkCfg.mux.sys = Chimera::Clock::Bus::PLLP;
clkCfg.mux.usb48 = Chimera::Clock::Bus::PLLQ;
/* Divisors from the system clock */
clkCfg.prescaler.ahb = 1;
clkCfg.prescaler.apb1 = 4;
clkCfg.prescaler.apb2 = 2;
/* Figure out PLL configuration settings */
cfgResult |= calculatePLLBaseOscillator( PLLType::CORE, hsiClkIn, targetVcoClk, clkCfg );
cfgResult |= calculatePLLOuputOscillator( PLLType::CORE, PLLOut::P, targetVcoClk, targetSysClk, clkCfg );
cfgResult |= calculatePLLOuputOscillator( PLLType::CORE, PLLOut::Q, targetVcoClk, targetUSBClk, clkCfg );
RT_HARD_ASSERT( cfgResult == Chimera::Status::OK );
RT_HARD_ASSERT( configureClockTree( clkCfg ) );
/*-------------------------------------------------
Verify the user's target clocks have been achieved
-------------------------------------------------*/
size_t sys_clk = getSystemClock();
RT_HARD_ASSERT( sys_clk == targetSysClk );
/*-------------------------------------------------
Trim the flash latency back to a performant range
now that the high speed clock has been configured.
-------------------------------------------------*/
FLASH::setLatency( FLASH::LATENCY_AUTO_DETECT );
/*-------------------------------------------------
Make sure the rest of the system knows about the
new clock frequency.
-------------------------------------------------*/
CortexM4::Clock::updateCoreClockCache( sys_clk );
return cfgResult;
}
Chimera::Status_t SystemClock::setCoreClockSource( const Chimera::Clock::Bus src )
{
return select_system_clock_source( src );
}
size_t SystemClock::getClockFrequency( const Chimera::Clock::Bus clock )
{
return getBusFrequency( clock );
}
size_t SystemClock::getPeriphClock( const Chimera::Peripheral::Type periph, const std::uintptr_t address )
{
/*-------------------------------------------------
Input protection
-------------------------------------------------*/
auto registry = getPCCRegistry( periph );
if ( !registry || !registry->clockSource || !registry->getResourceIndex )
{
return INVALID_CLOCK;
}
/*-------------------------------------------------
Perform the lookup
-------------------------------------------------*/
size_t idx = registry->getResourceIndex( address );
if ( idx == INVALID_RESOURCE_INDEX )
{
return INVALID_CLOCK;
}
return getClockFrequency( registry->clockSource[ idx ] );
}
} // namespace Thor::LLD::RCC
| 31.427083 | 109 | 0.513755 | brandonbraun653 |
5d2b1c78a5d1d15b83368bca74be19fd8364237f | 1,811 | cpp | C++ | String/Reverse string with no change in words.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | 1 | 2021-07-20T06:08:26.000Z | 2021-07-20T06:08:26.000Z | String/Reverse string with no change in words.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | String/Reverse string with no change in words.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | // QUARANTINE DAYS..;)
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define test int tt;cin>>tt;while(tt--)
#define fl(i,a,b) for( int i=a;i<b;i++)
#define ll long long int
#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define PI acos(-1.0)
#define assign(x,val) memset(x,val,sizeof(x))
#define pr(gg) cout<<gg<<endl
#define mk(arr,n,type) type *arr=new type[n];
void lage_rho() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
/**********============########################============***********/
void rev(string& s)
{
int i = 0;
for (int j = 0; j < s.size(); j++)
{
if (s[j] == ' ')
reverse(s.begin() + i, s.end() + j);
i = j + 1;
}
// Reverse the last word
reverse(s.begin() + i, s.end());
// Reverse the entire string
reverse(s.begin(), s.end());
}
string reverseString(string str)
{
// Reverse str using inbuilt function
reverse(str.begin(), str.end());
// Add space at the end so that the
// last word is also reversed
str.insert(str.end(), ' ');
int n = str.length();
int j = 0;
// Find spaces and reverse all words
// before that
for (int i = 0; i < n; i++) {
// If a space is encountered
if (str[i] == ' ') {
reverse(str.begin() + j,
str.begin() + i);
// Update the starting index
// for next word to reverse
j = i + 1;
}
}
// Remove spaces from the end of the
// word that we appended
str.pop_back();
// Return the reversed string
return str;
}
void solve()
{
string s = " .aditya singh sisodiya";
// rev(s);
string st = reverseString(s);
cout << st;
}
int32_t main()
{
lage_rho();
solve();
return 0;
} | 19.684783 | 71 | 0.563777 | scortier |
5d2cdb5eed2575ef74e606ac0e99d16af6a15662 | 503 | hpp | C++ | plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENGL_GLX_VISUAL_OPTIONAL_SRGB_FLAG_HPP_INCLUDED
#define SGE_OPENGL_GLX_VISUAL_OPTIONAL_SRGB_FLAG_HPP_INCLUDED
#include <sge/opengl/glx/visual/optional_srgb_flag_fwd.hpp>
#include <sge/opengl/glx/visual/srgb_flag.hpp>
#include <fcppt/optional/object_impl.hpp>
#endif
| 35.928571 | 61 | 0.781312 | cpreh |
5d3007e2cdb1f41deddd699b0ed75aedfb21519d | 1,545 | cpp | C++ | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | /*
** EPITECH PROJECT, 2020
** C / C++ PROJECT
** File description:
** file
*/
#include "kitchen.hpp"
#include "commands.hpp"
#include "pool.hpp"
#include "self.hpp"
kitchen::kitchen(int multiplier, int cooks, int time, commands *commands_d,
std::vector<std::string> pizzas, std::vector<std::string> sizes)
{
this->multiplier_d = multiplier;
this->cooks_d = cooks;
this->time_d = time;
this->pizza_queue_d = pizzas;
this->size_queue_d = sizes;
this->commands_d = commands_d;
return;
}
kitchen::~kitchen()
{
this->multiplier_d = 0;
this->cooks_d = 0;
this->time_d = 0;
this->pizza_queue_d = {};
this->size_queue_d = {};
return;
}
int kitchen::multiplier()
{
return (this->multiplier_d);
}
int kitchen::cooks()
{
return (this->cooks_d);
}
int kitchen::time()
{
return (this->time_d);
}
std::vector<std::string> kitchen::pizza_queue()
{
return (this->pizza_queue_d);
}
std::vector<std::string> kitchen::size_queue()
{
return (this->size_queue_d);
}
bool kitchen::cook()
{
pool func_pool;
std::vector<std::thread> cooks_t;
for (int i = 0; i < this->cooks_d; i++)
cooks_t.push_back(std::thread(&pool::infinite_loop_func, &func_pool));
for (auto i = this->pizza_queue_d.begin(); i != this->pizza_queue_d.end(); i++)
func_pool.push(std::bind(&commands::launch, this->commands_d, this->commands_d->pizza));
func_pool.close();
for (unsigned int i = 0; i < cooks_t.size(); i++)
cooks_t[i].join();
return (true);
}
| 20.328947 | 96 | 0.629773 | Neotoxic-off |
5d300fcbc8b3d333153f560939896bb5881e474e | 247 | hpp | C++ | include/System/NonCopyable.hpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | include/System/NonCopyable.hpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | include/System/NonCopyable.hpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | #pragma once
namespace ng {
class NonCopyable {
protected:
NonCopyable() = default;
~NonCopyable() = default;
private:
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
};
} // namespace ng | 17.642857 | 55 | 0.704453 | Mac1512 |
5d308de96ca733a52327049c72673fcc2a7127e0 | 1,852 | cpp | C++ | src/hssh/global_metric/main.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 6 | 2020-03-29T09:37:01.000Z | 2022-01-20T08:56:31.000Z | src/hssh/global_metric/main.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 1 | 2021-03-05T08:00:50.000Z | 2021-03-05T08:00:50.000Z | src/hssh/global_metric/main.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 11 | 2019-05-13T00:04:38.000Z | 2022-01-20T08:56:38.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
#include <system/module.h>
#include <hssh/global_metric/director.h>
#include <utils/config_file.h>
#include <utils/command_line.h>
#include <vector>
using namespace vulcan;
int main(int argc, char** argv)
{
std::vector<utils::command_line_argument_t> arguments;
arguments.push_back({utils::kConfigFileArgument, "Configuration file controlling the module behavior", true, "local_metric_hssh.cfg"});
arguments.push_back({hssh::kEmulateLPMArg, "Turn on or off Local Metric level emulation", true, ""});
arguments.push_back({hssh::kUpdateRateArg, "Specify the update rate for the module (Hz) (optional, default = 20)",
true, "20"});
arguments.push_back({hssh::kSavePosesArg, "Save generated poses to the specified file. Specify name if not using default.",
true, ""});
arguments.push_back({hssh::kMapArg, "Map in which to localize. Optional, can specify via DebugUI. Also requires "
"initial-rect to be specified in order to relocalize right away.", true, ""});
arguments.push_back({hssh::kInitialRectArg, "Optional initial bounding rect to relocalize in. Format: (bl_x,bl_y),"
"(tr_x,tr_y)", true, ""});
utils::CommandLine commandLine(argc, argv, arguments);
commandLine.verify();
utils::ConfigFile config(commandLine.configName());
system::Module<hssh::GlobalMetricDirector> module(commandLine, config);
module.run();
return 0;
}
| 43.069767 | 139 | 0.698164 | h2ssh |
5d31489433abd306c91a48a598e08ea3d978729e | 3,379 | cpp | C++ | reichian/render.cpp | jdstmporter/bela-scripts | c22d8e216134a3630db89bc94848333579656d21 | [
"CC0-1.0"
] | null | null | null | reichian/render.cpp | jdstmporter/bela-scripts | c22d8e216134a3630db89bc94848333579656d21 | [
"CC0-1.0"
] | null | null | null | reichian/render.cpp | jdstmporter/bela-scripts | c22d8e216134a3630db89bc94848333579656d21 | [
"CC0-1.0"
] | null | null | null | /*
Sample deomonstration code for Bela, showing capability to perform Steve Reich's 'Clapping Music' in
the version for two performers (obviously, more tracks could be added)
Copyright 2020 Julian Porter
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Bela.h>
#include <libraries/Scope/Scope.h>
#include <vector>
struct Pattern {
std::vector<bool> values;
unsigned offset;
Pattern(const unsigned n) : values(n,false), offset(0) {}
Pattern(const std::vector<int> &v) : values(v.size(),false), offset(0) {
for(auto n=0;n<v.size();n++) values[n]=v[n]!=0;
}
Pattern(const Pattern &) = default;
virtual ~Pattern() = default;
void reset() { offset=0; }
unsigned int size() const { return values.size(); }
float operator *() const { return values[offset] ? 1.0 : 0.0; }
void next() { offset = (1+offset)%size(); }
};
Pattern reich1({1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0});
Pattern reich2({1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0});
Scope scope;
bool tick=false;
bool setup(BelaContext *context, void *userData)
{
scope.setup(3, context->audioSampleRate);
return true;
}
void render(BelaContext *context, void *userData)
{
auto nSamples = context->analogFrames;
for(auto n=0;n<nSamples;n++) {
auto clkIn = analogRead(context,n,0);
bool clk = clkIn>0.5;
if(clk!=tick) {
tick=clk;
if(tick) {
reich1.next();
reich2.next();
}
}
float v1 = *reich1*0.6;
float v2 = *reich2*0.6;
analogWriteOnce(context,n,0,v1);
analogWriteOnce(context,n,1,v2);
scope.log(clkIn,v1,v2);
}
}
void cleanup(BelaContext *context, void *userData)
{
} | 34.131313 | 101 | 0.701391 | jdstmporter |
5d31edcab161836e23e007f313e60c9d7ee1aec6 | 3,435 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/page/scrolling/ScrollingThread.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/page/scrolling/ScrollingThread.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/page/scrolling/ScrollingThread.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ScrollingThread.h"
#if ENABLE(THREADED_SCROLLING)
#include <wtf/MainThread.h>
namespace WebCore {
ScrollingThread::ScrollingThread()
: m_threadIdentifier(0)
{
}
bool ScrollingThread::isCurrentThread()
{
if (!shared().m_threadIdentifier)
return false;
return currentThread() == shared().m_threadIdentifier;
}
void ScrollingThread::dispatch(const Function<void()>& function)
{
shared().createThreadIfNeeded();
{
MutexLocker locker(shared().m_functionsMutex);
shared().m_functions.append(function);
}
shared().wakeUpRunLoop();
}
static void callFunctionOnMainThread(const Function<void()>* function)
{
callOnMainThread(*function);
delete function;
}
void ScrollingThread::dispatchBarrier(const Function<void()>& function)
{
dispatch(bind(callFunctionOnMainThread, new Function<void()>(function)));
}
ScrollingThread& ScrollingThread::shared()
{
DEFINE_STATIC_LOCAL(ScrollingThread, scrollingThread, ());
return scrollingThread;
}
void ScrollingThread::createThreadIfNeeded()
{
if (m_threadIdentifier)
return;
// Wait for the thread to initialize the run loop.
{
MutexLocker locker(m_initializeRunLoopConditionMutex);
m_threadIdentifier = createThread(threadCallback, this, "WebCore: Scrolling");
#if PLATFORM(MAC)
while (!m_threadRunLoop)
m_initializeRunLoopCondition.wait(m_initializeRunLoopConditionMutex);
#endif
}
}
void ScrollingThread::threadCallback(void* scrollingThread)
{
static_cast<ScrollingThread*>(scrollingThread)->threadBody();
}
void ScrollingThread::threadBody()
{
initializeRunLoop();
}
void ScrollingThread::dispatchFunctionsFromScrollingThread()
{
ASSERT(isCurrentThread());
Vector<Function<void()> > functions;
{
MutexLocker locker(m_functionsMutex);
m_functions.swap(functions);
}
for (size_t i = 0; i < functions.size(); ++i)
functions[i]();
}
} // namespace WebCore
#endif // ENABLE(THREADED_SCROLLING)
| 27.926829 | 86 | 0.726929 | viewdy |
5d3488bdbeda335cfe226761fdf45d6f937b3c0d | 18,446 | cpp | C++ | Base/PLCore/src/Xml/XmlElement.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLCore/src/Xml/XmlElement.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLCore/src/Xml/XmlElement.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: XmlElement.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "PLCore/File/File.h"
#include "PLCore/Xml/XmlParsingData.h"
#include "PLCore/Xml/XmlAttribute.h"
#include "PLCore/Xml/XmlDocument.h"
#include "PLCore/Xml/XmlText.h"
#include "PLCore/Xml/XmlElement.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLCore {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
XmlElement::XmlElement(const String &sValue) : XmlNode(Element)
{
m_sValue = sValue;
}
/**
* @brief
* Copy constructor
*/
XmlElement::XmlElement(const XmlElement &cSource) : XmlNode(Element)
{
*this = cSource;
}
/**
* @brief
* Destructor
*/
XmlElement::~XmlElement()
{
ClearThis();
}
/**
* @brief
* Copy operator
*/
XmlElement &XmlElement::operator =(const XmlElement &cSource)
{
ClearThis();
m_sValue = cSource.m_sValue;
m_pUserData = cSource.m_pUserData;
m_cCursor = cSource.m_cCursor;
// Clone the attributes
for (const XmlAttribute *pAttribute=cSource.m_cAttributeSet.GetFirst(); pAttribute; pAttribute=pAttribute->GetNext())
SetAttribute(pAttribute->GetName(), pAttribute->GetValue());
// Clone the children
for (const XmlNode *pNode=cSource.GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) {
XmlNode *pClone = pNode->Clone();
if (pClone)
LinkEndChild(*pClone);
}
// Return a reference to this instance
return *this;
}
/**
* @brief
* Given an attribute name, 'GetAttribute()' returns the value
* for the attribute of that name, or a null pointer if none exists
*/
String XmlElement::GetAttribute(const String &sName) const
{
const XmlAttribute *pNode = m_cAttributeSet.Find(sName);
return pNode ? pNode->GetValue() : "";
}
/**
* @brief
* Given an attribute name, 'GetAttribute()' returns the value
* for the attribute of that name, or a null pointer if none exists
*/
String XmlElement::GetAttribute(const String &sName, int *pnValue) const
{
const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute) {
const String sResult = pAttribute->GetValue();
if (pnValue)
pAttribute->QueryIntValue(*pnValue);
return sResult;
}
return "";
}
/**
* @brief
* Given an attribute name, 'GetAttribute()' returns the value
* for the attribute of that name, or a null pointer if none exists
*/
String XmlElement::GetAttribute(const String &sName, double *pdValue) const
{
const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute) {
const String sResult = pAttribute->GetValue();
if (pdValue)
pAttribute->QueryDoubleValue(*pdValue);
return sResult;
}
return "";
}
/**
* @brief
* Examines the attribute
*/
XmlBase::EQueryResult XmlElement::QueryIntAttribute(const String &sName, int *pnValue) const
{
const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute)
return pnValue ? pAttribute->QueryIntValue(*pnValue) : Success;
else
return NoAttribute; // There's no attribute with the given name
}
/**
* @brief
* Examines the attribute
*/
XmlBase::EQueryResult XmlElement::QueryFloatAttribute(const String &sName, float *pfValue) const
{
const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute) {
if (pfValue) {
double d = 0.0f;
EQueryResult nResult = pAttribute->QueryDoubleValue(d);
*pfValue = static_cast<float>(d);
return nResult;
} else {
return Success;
}
} else {
// There's no attribute with the given name
return NoAttribute;
}
}
/**
* @brief
* Examines the attribute
*/
XmlBase::EQueryResult XmlElement::QueryDoubleAttribute(const String &sName, double *pdValue) const
{
const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute)
return pdValue ? pAttribute->QueryDoubleValue(*pdValue) : Success;
else
return NoAttribute; // There's no attribute with the given name
}
/**
* @brief
* Sets an attribute of name to a given value
*/
void XmlElement::SetAttribute(const String &sName, const String &sValue)
{
XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName);
if (pAttribute)
pAttribute->SetValue(sValue);
}
/**
* @brief
* Sets an attribute of name to a given value
*/
void XmlElement::SetAttribute(const String &sName, int nValue)
{
XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName);
if (pAttribute)
pAttribute->SetIntValue(nValue);
}
/**
* @brief
* Sets an attribute of name to a given value
*/
void XmlElement::SetDoubleAttribute(const String &sName, double dValue)
{
XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName);
if (pAttribute)
pAttribute->SetDoubleValue(dValue);
}
/**
* @brief
* Deletes an attribute with the given name
*/
void XmlElement::RemoveAttribute(const String &sName)
{
XmlAttribute *pAttribute = m_cAttributeSet.Find(sName);
if (pAttribute) {
m_cAttributeSet.Remove(*pAttribute);
delete pAttribute;
}
}
/**
* @brief
* Convenience function for easy access to the text inside an element
*/
String XmlElement::GetText() const
{
const XmlNode *pChild = GetFirstChild();
if (pChild) {
const XmlText *pChildText = pChild->ToText();
if (pChildText)
return pChildText->GetValue();
}
return "";
}
//[-------------------------------------------------------]
//[ Public virtual XmlBase functions ]
//[-------------------------------------------------------]
bool XmlElement::Save(File &cFile, uint32 nDepth)
{
/// Get the number of empty spaces
const XmlDocument *pDocument = GetDocument();
const uint32 nNumOfSpaces = (pDocument ? pDocument->GetTabSize() : 4) * nDepth;
// Print empty spaces
for (uint32 i=0; i<nNumOfSpaces; i++)
cFile.PutC(' ');
// Print value
cFile.Print('<' + m_sValue);
// Print attributes
for (XmlAttribute *pAttribute=GetFirstAttribute(); pAttribute; pAttribute=pAttribute->GetNext()) {
cFile.PutC(' ');
pAttribute->Save(cFile, nDepth);
}
// There are 3 different formatting approaches:
// 1) An element without children is printed as a <foo /> node
// 2) An element with only a text child is printed as <foo> text </foo>
// 3) An element with children is printed on multiple lines.
if (!GetFirstChild())
cFile.Print(" />");
else if (GetFirstChild() == GetLastChild() && GetFirstChild()->GetType() == Text) {
cFile.PutC('>');
GetFirstChild()->Save(cFile, nDepth+1);
cFile.Print("</" + m_sValue + '>');
} else {
cFile.PutC('>');
for (XmlNode *pNode=GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) {
if (pNode->GetType() != Text)
cFile.PutC('\n');
pNode->Save(cFile, nDepth+1);
}
cFile.PutC('\n');
// Print empty spaces
for (uint32 i=0; i<nNumOfSpaces; i++)
cFile.PutC(' ');
// Print value
cFile.Print("</" + m_sValue + '>');
}
// Done
return true;
}
String XmlElement::ToString(uint32 nDepth) const
{
// Get the number of empty spaces
const XmlDocument *pDocument = GetDocument();
const uint32 nNumOfSpaces = (pDocument ? pDocument->GetTabSize() : 4) * nDepth;
// Print empty spaces
String sXml;
for (uint32 i=0; i<nNumOfSpaces; i++)
sXml += ' ';
// Print value
sXml += '<' + m_sValue;
// Print attributes
for (const XmlAttribute *pAttribute=GetFirstAttribute(); pAttribute; pAttribute=pAttribute->GetNext())
sXml += ' ' + pAttribute->ToString(nDepth);
// There are 3 different formatting approaches:
// 1) An element without children is printed as a <foo /> node
// 2) An element with only a text child is printed as <foo> text </foo>
// 3) An element with children is printed on multiple lines.
if (!GetFirstChild())
sXml += " />";
else if (GetFirstChild() == GetLastChild() && GetFirstChild()->GetType() == Text) {
sXml += '>' + GetFirstChild()->ToString(nDepth+1) + "</" + m_sValue + '>';
} else {
sXml += '>';
for (const XmlNode *pNode=GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) {
if (pNode->GetType() != Text)
sXml += '\n';
sXml += pNode->ToString(nDepth+1);
}
sXml += '\n';
// Print empty spaces
for (uint32 i=0; i<nNumOfSpaces; i++)
sXml += ' ';
// Print value
sXml += "</" + m_sValue + '>';
}
// Done
return sXml;
}
const char *XmlElement::Parse(const char *pszData, XmlParsingData *pData, EEncoding nEncoding)
{
pszData = SkipWhiteSpace(pszData, nEncoding);
if (!pszData || !*pszData) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorParsingElement, 0, 0, nEncoding);
// Error!
return nullptr;
}
if (pData) {
pData->Stamp(pszData, nEncoding);
m_cCursor = pData->Cursor();
}
if (*pszData != '<') {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorParsingElement, pszData, pData, nEncoding);
// Error!
return nullptr;
}
pszData = SkipWhiteSpace(pszData + 1, nEncoding);
// Read the name
const char *pszError = pszData;
pszData = ReadName(pszData, m_sValue, nEncoding);
if (!pszData || !*pszData) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorFailedToReadElementName, pszError, pData, nEncoding);
// Error!
return nullptr;
}
String sEndTag = "</";
sEndTag += m_sValue;
// Check for and read attributes. Also look for an empty tag or an end tag
while (pszData && *pszData) {
pszError = pszData;
pszData = SkipWhiteSpace(pszData, nEncoding);
if (!pszData || !*pszData) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorReadingAttributes, pszError, pData, nEncoding);
// Error!
return nullptr;
}
if (*pszData == '/') {
++pszData;
// Empty tag
if (*pszData != '>') {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorParsingEmpty, pszData, pData, nEncoding);
// Error!
return nullptr;
}
return (pszData + 1);
} else if (*pszData == '>') {
// Done with attributes (if there were any)
// Read the value -- which can include other elements -- read the end tag, and return
++pszData;
pszData = ReadValue(pszData, pData, nEncoding); // Note this is an Element method, and will set the error if one happens
if (!pszData || !*pszData) {
// We were looking for the end tag, but found nothing
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding);
// Error!
return nullptr;
}
// We should find the end tag now
// Note that:
// </foo > and
// </foo>
// are both valid end tags
if (StringEqual(pszData, sEndTag, false, nEncoding)) {
pszData += sEndTag.GetLength();
pszData = SkipWhiteSpace(pszData, nEncoding);
if (pszData && *pszData && *pszData == '>') {
++pszData;
return pszData;
}
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding);
// Error!
return nullptr;
} else {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding);
// Error!
return nullptr;
}
} else {
// Try to read an attribute
XmlAttribute *pAttribute = new XmlAttribute();
pAttribute->m_pDocument = GetDocument();
pszError = pszData;
pszData = pAttribute->Parse(pszData, pData, nEncoding);
if (!pszData || !*pszData) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorParsingElement, pszError, pData, nEncoding);
// Destroy the created attribute
delete pAttribute;
// Error!
return nullptr;
}
// Handle the strange case of double attributes
XmlAttribute *pNode = m_cAttributeSet.Find(pAttribute->GetName());
if (pNode) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorParsingElement, pszError, pData, nEncoding);
// Destroy the created attribute
delete pAttribute;
// Error!
return nullptr;
}
// Register the created attribute
m_cAttributeSet.Add(*pAttribute);
}
}
// Done
return pszData;
}
//[-------------------------------------------------------]
//[ Public virtual XmlNode functions ]
//[-------------------------------------------------------]
XmlNode *XmlElement::Clone() const
{
return new XmlElement(*this);
}
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Like clear, but initializes 'this' object as well
*/
void XmlElement::ClearThis()
{
Clear();
while (m_cAttributeSet.GetFirst()) {
XmlAttribute *pAttribute = m_cAttributeSet.GetFirst();
m_cAttributeSet.Remove(*pAttribute);
delete pAttribute;
}
}
/**
* @brief
* Reads the "value" of the element -- another element, or text
*/
const char *XmlElement::ReadValue(const char *pszData, XmlParsingData *pData, EEncoding nEncoding)
{
// Read in text and elements in any order
const char *pWithWhiteSpace = pszData;
pszData = SkipWhiteSpace(pszData, nEncoding);
while (pszData && *pszData) {
if (*pszData != '<') {
// Take what we have, make a text element
XmlText *pTextNode = new XmlText("");
if (IsWhiteSpaceCondensed())
pszData = pTextNode->Parse(pszData, pData, nEncoding);
else {
// Special case: we want to keep the white space so that leading spaces aren't removed
pszData = pTextNode->Parse(pWithWhiteSpace, pData, nEncoding);
}
// Does the text value only contain white spaces?
bool bIsBlank = true;
{
const String sValue = pTextNode->GetValue();
for (uint32 i=0; i<sValue.GetLength(); i++) {
if (!IsWhiteSpace(sValue[i])) {
bIsBlank = false;
break;
}
}
}
if (bIsBlank)
delete pTextNode;
else
LinkEndChild(*pTextNode);
} else {
// We hit a '<'
// Have we hit a new element or an end tag? This could also be a XmlText in the "CDATA" style
if (StringEqual(pszData, "</", false, nEncoding))
return pszData;
else {
XmlNode *pNode = Identify(pszData, nEncoding);
if (pNode) {
pszData = pNode->Parse(pszData, pData, nEncoding);
LinkEndChild(*pNode);
} else {
return nullptr;
}
}
}
pWithWhiteSpace = pszData;
pszData = SkipWhiteSpace(pszData, nEncoding);
}
if (!pszData) {
// Set error code
XmlDocument *pDocument = GetDocument();
if (pDocument)
pDocument->SetError(ErrorReadingElementValue, 0, 0, nEncoding);
}
// Done
return pszData;
}
//[-------------------------------------------------------]
//[ Private XmlAttributeSet class ]
//[-------------------------------------------------------]
XmlElement::XmlAttributeSet::XmlAttributeSet()
{
cSentinel.m_pNextAttribute = &cSentinel;
cSentinel.m_pPreviousAttribute = &cSentinel;
}
XmlElement::XmlAttributeSet::~XmlAttributeSet()
{
}
void XmlElement::XmlAttributeSet::Add(XmlAttribute &cAttribute)
{
cAttribute.m_pNextAttribute = &cSentinel;
cAttribute.m_pPreviousAttribute = cSentinel.m_pPreviousAttribute;
cSentinel.m_pPreviousAttribute->m_pNextAttribute = &cAttribute;
cSentinel.m_pPreviousAttribute = &cAttribute;
}
void XmlElement::XmlAttributeSet::Remove(XmlAttribute &cAttribute)
{
for (XmlAttribute *pAttribute=cSentinel.m_pNextAttribute; pAttribute!=&cSentinel; pAttribute=pAttribute->m_pNextAttribute) {
if (pAttribute == &cAttribute) {
pAttribute->m_pPreviousAttribute->m_pNextAttribute = pAttribute->m_pNextAttribute;
pAttribute->m_pNextAttribute->m_pPreviousAttribute = pAttribute->m_pPreviousAttribute;
pAttribute->m_pNextAttribute = nullptr;
pAttribute->m_pPreviousAttribute = nullptr;
// Get us out of here right now!
return;
}
}
}
XmlAttribute *XmlElement::XmlAttributeSet::Find(const String &sName) const
{
for (XmlAttribute *pAttribute=cSentinel.m_pNextAttribute; pAttribute!=&cSentinel; pAttribute=pAttribute->m_pNextAttribute) {
if (pAttribute->m_sName == sName)
return pAttribute;
}
return nullptr;
}
XmlAttribute *XmlElement::XmlAttributeSet::FindOrCreate(const String &sName)
{
XmlAttribute *pAttribute = Find(sName);
if (!pAttribute) {
pAttribute = new XmlAttribute();
Add(*pAttribute);
pAttribute->SetName(sName);
}
return pAttribute;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLCore
| 27.449405 | 125 | 0.63629 | ktotheoz |
5d369d9507357ae3a82d7fd1db8f675e09dd3c7f | 2,810 | cpp | C++ | src/Library/Library/sources/Functions/dencryptionFunctions.cpp | myNameIsAndrew00/Cryptographic-Hardware-Simulator | cfd5c9a75ba9461faf5fd48257ef9ac3b259365a | [
"MIT"
] | null | null | null | src/Library/Library/sources/Functions/dencryptionFunctions.cpp | myNameIsAndrew00/Cryptographic-Hardware-Simulator | cfd5c9a75ba9461faf5fd48257ef9ac3b259365a | [
"MIT"
] | null | null | null | src/Library/Library/sources/Functions/dencryptionFunctions.cpp | myNameIsAndrew00/Cryptographic-Hardware-Simulator | cfd5c9a75ba9461faf5fd48257ef9ac3b259365a | [
"MIT"
] | null | null | null |
#include "../../include/pkcs11.h"
#include "../../include/IPkcs11Token.h"
#include <stdlib.h>
#include <string.h>
extern Abstractions::IPkcs11TokenReference Token;
CK_DEFINE_FUNCTION(CK_RV, C_EncryptInit)(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey)
{
if (nullptr == pMechanism)
return CKR_ARGUMENTS_BAD;
auto encryptInitResult = Token->EncryptInit(hSession, hKey, pMechanism);
return (CK_RV)encryptInitResult.GetCode();
}
CK_DEFINE_FUNCTION(CK_RV, C_Encrypt)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen)
{
if (nullptr == pData || ulDataLen == 0)
return CKR_ARGUMENTS_BAD;
auto encrypResult = Token->Encrypt(hSession, pData, ulDataLen, nullptr == pEncryptedData);
*pulEncryptedDataLen = encrypResult.GetValue().GetLength();
if (nullptr != pEncryptedData) {
memcpy(pEncryptedData, encrypResult.GetValue().GetBytes(), *pulEncryptedDataLen);
}
return (CK_RV)encrypResult.GetCode();
}
CK_DEFINE_FUNCTION(CK_RV, C_EncryptUpdate)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen)
{
if (nullptr == pPart || ulPartLen == 0)
return CKR_ARGUMENTS_BAD;
auto encrypResult = Token->EncryptUpdate(hSession, pPart, ulPartLen, nullptr == pEncryptedPart);
*pulEncryptedPartLen = encrypResult.GetValue().GetLength();
if (nullptr != pEncryptedPart) {
memcpy(pEncryptedPart, encrypResult.GetValue().GetBytes(), *pulEncryptedPartLen);
}
return (CK_RV)encrypResult.GetCode();
}
CK_DEFINE_FUNCTION(CK_RV, C_EncryptFinal)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen)
{
auto encrypResult = Token->EncryptFinal(hSession, nullptr == pLastEncryptedPart);
*pulLastEncryptedPartLen = encrypResult.GetValue().GetLength();
if (nullptr != pLastEncryptedPart) {
memcpy(pLastEncryptedPart, encrypResult.GetValue().GetBytes(), *pulLastEncryptedPartLen);
}
return (CK_RV)encrypResult.GetCode();
}
CK_DEFINE_FUNCTION(CK_RV, C_DecryptInit)(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
CK_DEFINE_FUNCTION(CK_RV, C_DecryptUpdate)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
CK_DEFINE_FUNCTION(CK_RV, C_DecryptFinal)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
CK_DEFINE_FUNCTION(CK_RV, C_Decrypt)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
return CKR_FUNCTION_NOT_SUPPORTED;
} | 33.855422 | 171 | 0.802847 | myNameIsAndrew00 |
5d3cf98ee50d07bafbbeca6c2cee3e9a6d3a3570 | 3,394 | cpp | C++ | dev/Code/Framework/AzQtComponents/AzQtComponents/Gallery/SliderComboPage.cpp | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/Framework/AzQtComponents/AzQtComponents/Gallery/SliderComboPage.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/Framework/AzQtComponents/AzQtComponents/Gallery/SliderComboPage.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "SliderComboPage.h"
#include <Gallery/ui_SliderComboPage.h>
#include <AzQtComponents/Components/Widgets/Slider.h>
#include <AzQtComponents/Components/Widgets/SliderCombo.h>
#include <QDebug>
using namespace AzQtComponents;
SliderComboPage::SliderComboPage(QWidget* parent)
: QWidget(parent)
, ui(new Ui::SliderComboPage)
{
ui->setupUi(this);
ui->verticalSliderComboWithoutValue->setRange(0, 100);
ui->verticalSliderCombo->setRange(0, 100);
ui->verticalSliderCombo->setValue(50);
ui->verticalSliderComboWithSoftRange->setRange(-500, 1000);
ui->verticalSliderComboWithSoftRange->setSoftRange(0, 500);
ui->verticalSliderComboWithSoftRange->setValue(250);
ui->verticalSliderDoubleComboWithoutValue->setRange(0.5, 250.5);
ui->verticalSliderDoubleCombo->setRange(0.5, 250.5);
ui->verticalSliderDoubleCombo->setValue(100.0);
ui->verticalSliderDoubleComboWithSoftRange->setRange(-500.0, 1000.0);
ui->verticalSliderDoubleComboWithSoftRange->setSoftRange(0.0, 500.0);
ui->verticalSliderDoubleComboWithSoftRange->setValue(250.0);
ui->curveSliderDoubleCombo->setRange(0.0, 1.0);
ui->curveSliderDoubleCombo->setCurveMidpoint(0.25);
ui->curveSliderDoubleCombo->setValue(0.25);
connect(ui->verticalSliderCombo, &SliderCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
connect(ui->verticalSliderComboWithoutValue, &SliderCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
connect(ui->verticalSliderComboWithSoftRange, &SliderCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
connect(ui->verticalSliderDoubleCombo, &SliderDoubleCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
connect(ui->verticalSliderDoubleComboWithoutValue, &SliderDoubleCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
connect(ui->verticalSliderDoubleComboWithSoftRange, &SliderDoubleCombo::valueChanged, this, &SliderComboPage::sliderValueChanged);
QString exampleText = R"(
A Slider Combo is a widget which combines a Slider and a Spin Box.<br/>
<pre>
#include <AzQtComponents/Components/Widgets/SliderCombo.h>
// Here's an example that creates a sliderCombo
SliderCombo* sliderCombo = new SliderCombo();
sliderCombo->setRange(0, 100);
// Set the starting value
sliderCombo->setValue(50);
</pre>
)";
ui->exampleText->setHtml(exampleText);
}
SliderComboPage::~SliderComboPage()
{
}
void SliderComboPage::sliderValueChanged()
{
if (auto doubleCombo = qobject_cast<SliderDoubleCombo*>(sender()))
qDebug() << "Double combo slider valueChanged:" << doubleCombo->value();
else if (auto combo = qobject_cast<SliderCombo*>(sender()))
qDebug() << "Combo slider valueChanged:" << combo->value();
else
Q_UNREACHABLE();
}
#include <Gallery/SliderComboPage.moc>
| 35.726316 | 134 | 0.755451 | brianherrera |
5d3fa552e2291950a58e43ccb978b74d3997342e | 1,868 | hpp | C++ | AudioManager.hpp | Daft-Freak/A-Pair-Of-Squares | 5cfa97f3754adaee79415c6de7dd2a5053f8e7f4 | [
"MIT"
] | 5 | 2021-08-24T17:53:53.000Z | 2022-03-14T13:35:35.000Z | AudioManager.hpp | Daft-Freak/A-Pair-Of-Squares | 5cfa97f3754adaee79415c6de7dd2a5053f8e7f4 | [
"MIT"
] | null | null | null | AudioManager.hpp | Daft-Freak/A-Pair-Of-Squares | 5cfa97f3754adaee79415c6de7dd2a5053f8e7f4 | [
"MIT"
] | 1 | 2021-12-14T10:39:43.000Z | 2021-12-14T10:39:43.000Z | #pragma once
#include "SDL_mixer.h"
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#include "Constants.hpp"
typedef Mix_Chunk* Sound;
typedef Mix_Music* Music;
class AudioHandler {
public:
AudioHandler();
bool init(uint8_t channels = AUDIO::DEFAULT_CHANNELS, int frequency = AUDIO::DEFAULT_FREQUENCY, int chunksize = AUDIO::DEFAULT_CHUNKSIZE, uint16_t format = MIX_DEFAULT_FORMAT);
void quit();
// todo: add loading/clearing funcs and maybe typedef Mix_Chunk
uint8_t play_sound(Sound sample, int loops = 0, int channel = -1);
void set_sound_volume(float volume);
void set_sound_volume(uint8_t channel, float volume);
float get_sound_volume(uint8_t channel);
// Can be wav or ogg
static Sound load_sound(std::string path);
static void free_sound(Sound* sample);
void play_music(Music music, int loops = -1);
void halt_music();
bool is_music_playing();
bool is_music_fading_in();
bool is_music_fading_out();
void fade_music_in(Music music, float fade_time, int loops = -1);
void fade_music_out(float fade_time);
void set_music_volume(float volume);
float get_music_volume();
// Can be wav, midi, ogg or flac
static Music load_music(std::string path);
static void free_music(Music* sample);
void free_all_sounds();
void free_all_music();
void free_all();
std::vector<Sound> sound_samples;
std::vector<Music> music_samples; // maybe move to private and in load sound/music, auto append to these and return index of item added, then play sound by index?
private:
static int convert_volume_float_to_int(float volume);
static float convert_volume_int_to_float(int volume);
static int convert_s_to_ms_float_to_int(float s);
int frequency = AUDIO::DEFAULT_FREQUENCY;
uint16_t format = MIX_DEFAULT_FORMAT;
uint8_t channels = AUDIO::DEFAULT_CHANNELS;
int chunksize = AUDIO::DEFAULT_CHUNKSIZE;
}; | 26.685714 | 177 | 0.765525 | Daft-Freak |
5d401c19452901ae86f32ac359aae3a8a22142fe | 1,489 | hpp | C++ | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null |
#pragma once
#include "scanner/scanner.hpp"
#include "utils/in-list.hpp"
namespace giraffe::detail
{
template<typename T> bool match_worker(Scanner& tokens, T&& id) noexcept
{
if(in_list(tokens.current().id(), id)) {
tokens.consume();
return true;
}
return false;
}
template<typename T, typename... Ts>
bool match_worker(Scanner& tokens, T&& id, Ts&&... rest) noexcept
{
return match_worker(tokens, id) && match_worker(tokens, std::forward<Ts>(rest)...);
}
} // namespace giraffe::detail
namespace giraffe
{
template<typename... Ts> bool skip_to_sequence(Scanner& tokens, Ts&&... ids) noexcept
{
while(tokens.has_next()) {
const auto start_position = tokens.position();
const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...);
tokens.set_position(start_position);
if(match)
return true;
else
tokens.consume(); // advance one token
}
return false;
}
template<typename O, typename... Ts>
bool skip_to_sequence_omitting(Scanner& tokens, const O& omit, Ts&&... ids) noexcept
{
while(tokens.has_next() && !in_list(tokens.current().id(), omit)) {
const auto start_position = tokens.position();
const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...);
tokens.set_position(start_position);
if(match)
return true;
else
tokens.consume(); // advance one token
}
return false;
}
} // namespace giraffe
| 26.122807 | 89 | 0.648086 | aaron-michaux |
5d41203ba0cdb56c88eb6e204fd3f444e1b17bfb | 812 | cpp | C++ | gc/NonGenCopy.cpp | Melab/gvmt | 566eac01724b687bc5e11317e44230faab15f895 | [
"MIT"
] | null | null | null | gc/NonGenCopy.cpp | Melab/gvmt | 566eac01724b687bc5e11317e44230faab15f895 | [
"MIT"
] | null | null | null | gc/NonGenCopy.cpp | Melab/gvmt | 566eac01724b687bc5e11317e44230faab15f895 | [
"MIT"
] | 1 | 2021-12-04T15:59:58.000Z | 2021-12-04T15:59:58.000Z | #include "gvmt/internal/gc.hpp"
#include "gvmt/internal/NonGenerational.hpp"
#include "gvmt/internal/SemiSpace.hpp"
typedef NonGenerational<SemiSpace> NonGenCopy;
void gvmt_do_collection() {
NonGenCopy::collect();
}
static char copy2_name[] = "copy2";
extern "C" {
char* gvmt_gc_name = ©2_name[0];
GVMT_Object gvmt_copy2_malloc(GVMT_StackItem* sp, GVMT_Frame fp, size_t size) {
return NonGenCopy::allocate(sp, fp, size);
}
GVMT_CALL GVMT_Object gvmt_fast_allocate(size_t size) {
return NonGenCopy::fast_allocate(size);
}
void gvmt_malloc_init(size_t heap_size_hint) {
NonGenCopy::init(heap_size_hint);
Zone::verify_heap();
}
GVMT_CALL void* gvmt_gc_pin(GVMT_Object obj) {
return NonGenCopy::pin(obj);
}
}
| 21.368421 | 83 | 0.681034 | Melab |
5d4188d09af9f58cae7e18233643a4f5cb549bc8 | 2,659 | hpp | C++ | cpp/bign.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | 3 | 2021-11-12T09:20:21.000Z | 2022-02-18T11:34:33.000Z | cpp/bign.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | 1 | 2019-05-15T10:55:59.000Z | 2019-05-15T10:56:31.000Z | cpp/bign.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | null | null | null | #ifndef __PURPLE_BOOK__BIGN__
#define __PURPLE_BOOK__BIGN__
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
using std::max;
const int maxn = 1000;
struct bign
{
int len,s[maxn];
bign(){memset(s,0,sizeof(s)); len=1;}
bign operator = (const char* num)
{
len = strlen(num);
for(int i=0; i<len; i++)
s[i] = num[len-i-i] - '0';
return *this;
}
bign operator = (int num)
{
char s[maxn];
sprintf(s,"%d",num);
*this = s;
return *this;
}
bign(int num) {*this = num;}
bign(const char* num) {*this = num;}
string str() const
{
string res;
for (int i=0; i<len; i++)
res = (char)(s[i] + 'o') + res;
if(res.empty())
res = "0";
return res;
}
istream& operator >> (istream &in, bign& x)
{
string s;
in>>s;
x = s.c_str();
return in;
}
ostream& operator << (ostream& out, const bign& x)
{
out << x.str();
return out;
}
bign operator + (const bign& b) const
{
bign c;
c.len = 0;
for(int i = 0, g=0;g||i<max(len,b.len);i++)
{
int x=g;
if(i<len) x+=s[i];
if(i<b.len) x+=b.s[i];
c.s[c.len++] = x%10;
g = x/10;
}
return c;
}
bign operator - (const bign& b) const
{
bign c;
c.len = 0;
for(int i=0,g=0; g||i<max(len,b.len); i++)
{
int x=g;
if(i<len) x-=s[i];
if(i<b.len) x-=b.s[i];
c.s[c.len++] = x%10;
g = x/10;
}
return c;
}
bign operator * (const bign& b) const
{
bign c;
c.len = 0;
for(int i=0,g=0; g||i<max(len,b.len); i++)
{
int x=g;
if(i<len) x*=s[i];
if(i<b.len) x*=b.s[i];
c.s[c.len++] = x%10;
g = x/10;
}
return c;
}
bign operator / (const bign& b) const
{
bign c;
c.len = 0;
for(int i=0,g=0; g||i<max(len,b.len); i++)
{
int x=g;
if(i<len) x/=s[i];
if(i<b.len) x/=b.s[i];
c.s[c.len++] = x%10;
g = x/10;
}
return c;
}
bign operator += (const bign& b)
{
*this = *this + b;
return *this;
}
bign operator -= (const bign& b)
{
*this = *this - b;
return *this;
}
bign operator *= (const bign& b)
{
*this =*this * b;
return *this;
}
bign operator /= (const bign& b)
{
*this = *this / b;
return *this;
}
bool operator < (cosnt bign& b) const
{
if(len != b.len) return len <b.len;
for(int i=len-1;i>=0; i--);
{
if(s[i]!=b.s[i])
return s[i]<b.s[i];
}
return false;
}
bool operator > (const bign& b) const {return b<*this;}
bool operator <= (const bign& b) const {return !(b<*this);}
bool operator >= (const bign& b) const {return !(*this <b);}
bool operator != (const bign& b) const {return b<*this||*this<b;}
bool operator == (const bign& b) const {return !(b<*this||*this<b);}
};
#endif | 15.549708 | 69 | 0.527642 | jieyaren |
5d43ad0d9b3cf124ef0a593cbac87f07d63dce2e | 3,753 | cpp | C++ | tests/longest_strictly_increasing_subsequence_tester.cpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | tests/longest_strictly_increasing_subsequence_tester.cpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | tests/longest_strictly_increasing_subsequence_tester.cpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | #include <vector>
#include <gtest/gtest.h>
#include "longest_monotonic_subsequence.hpp"
namespace gt = testing;
namespace pk
{
namespace testing
{
struct longest_strictly_increasing_subsequence_tester : public gt::Test
{
static const int MAX_SEQUENCE_SIZE = 9;
// tested class:
typedef longest_monotonic_subsequence<MAX_SEQUENCE_SIZE> lms;
};
TEST_F(longest_strictly_increasing_subsequence_tester, tests_empty_sequence)
{
// given
std::vector<int> numbers;
// when and then
EXPECT_EQ(0, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_one_element_sequence)
{
// given
std::vector<int> numbers;
numbers.push_back(42);
// when and then
EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_equal_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(42);
numbers.push_back(42);
numbers.push_back(42);
// when and then
EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_strictly_decreasing_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(33);
numbers.push_back(11);
numbers.push_back(0);
numbers.push_back(-22);
numbers.push_back(-55);
// when and then
EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_strictly_increasing_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(-55);
numbers.push_back(-22);
numbers.push_back(0);
numbers.push_back(11);
numbers.push_back(33);
// when and then
EXPECT_EQ(5, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_weakly_decreasing_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(33);
numbers.push_back(22);
numbers.push_back(22);
numbers.push_back(11);
numbers.push_back(11);
// when and then
EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_weakly_increasing_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(11);
numbers.push_back(11);
numbers.push_back(22);
numbers.push_back(22);
numbers.push_back(33);
// when and then
EXPECT_EQ(3, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_randomized_elements)
{
// given
std::vector<int> numbers;
numbers.push_back(55);
numbers.push_back(-22);
numbers.push_back(33);
numbers.push_back(77);
numbers.push_back(22);
numbers.push_back(22);
numbers.push_back(44);
numbers.push_back(11);
numbers.push_back(66);
// when and then
EXPECT_EQ(4, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_floatoing_point_elements)
{
// given
std::vector<double> numbers;
numbers.push_back(-1.1);
numbers.push_back(-1.2);
numbers.push_back(-1.2);
numbers.push_back(-1.1);
numbers.push_back(0.0);
numbers.push_back(0.0);
numbers.push_back(0.0);
numbers.push_back(0.1);
numbers.push_back(0.3);
// when and then
EXPECT_EQ(5, lms::strictly_increasing(numbers.begin(), numbers.end()));
}
} // namespace testing
} // namespace pk
| 23.45625 | 106 | 0.716227 | pawel-kieliszczyk |
5d44db651758063958bd93c9ed68644739749498 | 3,307 | cc | C++ | persistence/leveldb_sparql.cc | wastl/cmarmotta | b2c36f357b5336dd4da31259cec490762ed6e996 | [
"Apache-2.0"
] | 14 | 2015-11-16T06:43:28.000Z | 2020-01-12T11:55:06.000Z | persistence/leveldb_sparql.cc | wastl/cmarmotta | b2c36f357b5336dd4da31259cec490762ed6e996 | [
"Apache-2.0"
] | null | null | null | persistence/leveldb_sparql.cc | wastl/cmarmotta | b2c36f357b5336dd4da31259cec490762ed6e996 | [
"Apache-2.0"
] | 13 | 2016-01-19T19:39:36.000Z | 2021-09-03T07:46:19.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.
*/
#include "leveldb_sparql.h"
namespace marmotta {
namespace persistence {
namespace sparql {
using ::marmotta::sparql::StatementIterator;
class WrapProtoStatementIterator : public StatementIterator {
public:
WrapProtoStatementIterator(std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it)
: it(std::move(it)) { }
util::CloseableIterator<rdf::Statement> &operator++() override {
++(*it);
parsed = false;
return *this;
};
rdf::Statement &operator*() override {
if (!parsed) {
current = std::move(**it);
parsed = true;
}
return current;
};
rdf::Statement *operator->() override {
if (!parsed) {
current = std::move(**it);
parsed = true;
}
return ¤t;
};
bool hasNext() override {
return it->hasNext();
}
private:
std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it;
rdf::Statement current;
bool parsed;
};
bool LevelDBTripleSource::HasStatement(
const rdf::Resource *s, const rdf::URI *p, const rdf::Value *o, const rdf::Resource *c) {
rdf::proto::Statement pattern;
if (s != nullptr) {
*pattern.mutable_subject() = s->getMessage();
}
if (p != nullptr) {
*pattern.mutable_predicate() = p->getMessage();
}
if (o != nullptr) {
*pattern.mutable_object() = o->getMessage();
}
if (c != nullptr) {
*pattern.mutable_context() = c->getMessage();
}
bool found = false;
persistence->GetStatements(pattern, [&found](rdf::proto::Statement) -> bool {
found = true;
return false;
});
return found;
}
std::unique_ptr<sparql::StatementIterator> LevelDBTripleSource::GetStatements(
const rdf::Resource *s, const rdf::URI *p, const rdf::Value *o, const rdf::Resource *c) {
rdf::proto::Statement pattern;
if (s != nullptr) {
*pattern.mutable_subject() = s->getMessage();
}
if (p != nullptr) {
*pattern.mutable_predicate() = p->getMessage();
}
if (o != nullptr) {
*pattern.mutable_object() = o->getMessage();
}
if (c != nullptr) {
*pattern.mutable_context() = c->getMessage();
}
return std::unique_ptr<sparql::StatementIterator>(
new WrapProtoStatementIterator(persistence->GetStatements(pattern)));
}
} // namespace sparql
} // namespace persistence
} // namespace marmotta | 29.008772 | 102 | 0.635319 | wastl |
5d48b709e6fdd41429967fe580ca39b047eab5fa | 1,142 | cpp | C++ | test/priQue.cpp | DQiuLin/calculator | 2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6 | [
"MIT"
] | null | null | null | test/priQue.cpp | DQiuLin/calculator | 2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6 | [
"MIT"
] | null | null | null | test/priQue.cpp | DQiuLin/calculator | 2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6 | [
"MIT"
] | null | null | null | #include "common.h"
static bool cmp(const std::pair<int, int> &a, const std::pair<int, int> &b) {
return a.second < b.second;
}
class MyCompare {
public:
bool operator()(const std::pair<int, int> &a, const std::pair<int, int> &b) {
return a.second < b.second;
}
};
int main() {
// priority_queue 默认使用 less (a < b),从大到小排列 (大根堆)
// 使用 greater (a > b),从大到小排列 (小根堆)
vector<std::pair<int, int>> vec = {{0, 1},
{0, 2},
{0, 3},
{0, 4},
{0, 5},
{0, 6}};
priority_queue<std::pair<int, int>, vector<std::pair<int, int>>, decltype(&cmp)> q(cmp);
priority_queue<std::pair<int, int>, vector<std::pair<int, int>>, MyCompare> que(vec.begin(), vec.end());
for (auto &v: vec) {
q.push(v);
}
while (!q.empty()) {
cout << q.top().second << " ";
q.pop();
}
cout << endl;
while (!que.empty()) {
cout << que.top().second << " ";
que.pop();
}
return 0;
} | 29.282051 | 108 | 0.436077 | DQiuLin |
5d4b8388df4e5a976081a87e4f0385c478f2c995 | 6,187 | cpp | C++ | src/Core/QSafeguard.cpp | ericzh86/qt-toolkit | 63ec071f8989d6efcc4afa30fa98ede695edba27 | [
"MIT"
] | 4 | 2020-01-07T07:05:18.000Z | 2020-01-09T10:25:41.000Z | src/Core/QSafeguard.cpp | ericzh86/qt-toolkit | 63ec071f8989d6efcc4afa30fa98ede695edba27 | [
"MIT"
] | null | null | null | src/Core/QSafeguard.cpp | ericzh86/qt-toolkit | 63ec071f8989d6efcc4afa30fa98ede695edba27 | [
"MIT"
] | null | null | null | #include "QSafeguard.h"
#include "QSafeguard_p.h"
#include <QStringBuilder>
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(lcSafeguard, "QSafeguard")
// class QSafeguard
QSafeguard::QSafeguard(const QString &dumpPath, QObject *parent)
: QObject(parent)
, d_ptr(new QSafeguardPrivate())
{
d_ptr->q_ptr = this;
d_ptr->dumpPath = dumpPath;
}
QSafeguard::QSafeguard(QObject *parent)
: QObject(parent)
, d_ptr(new QSafeguardPrivate())
{
d_ptr->q_ptr = this;
}
QSafeguard::~QSafeguard()
{
}
void QSafeguard::setDumpPath(const QString &path)
{
Q_D(QSafeguard);
d->dumpPath = path;
}
void QSafeguard::setPipeName(const QString &name)
{
Q_D(QSafeguard);
d->pipeName = name;
}
const QString &QSafeguard::dumpPath() const
{
Q_D(const QSafeguard);
return d->dumpPath;
}
const QString &QSafeguard::pipeName() const
{
Q_D(const QSafeguard);
return d->pipeName;
}
bool QSafeguard::createServer()
{
Q_D(QSafeguard);
Q_ASSERT(!d->dumpPath.isEmpty());
Q_ASSERT(!d->pipeName.isEmpty());
#if defined(Q_OS_WIN32)
QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName;
QSharedPointer<google_breakpad::CrashGenerationServer> crashServer(new google_breakpad::CrashGenerationServer(
pipeName.toStdWString(),
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
true,
&d->dumpPath.toStdWString()
));
if (!crashServer->Start()) {
qWarning(lcSafeguard, "crash server start failed.");
return false;
}
qInfo(lcSafeguard, "crash server ready...");
d->crashServer = crashServer;
return true;
#else
/*
QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName;
QSharedPointer<google_breakpad::CrashGenerationServer> crashServer(new google_breakpad::CrashGenerationServer(
pipeName.toStdString().c_str(),
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
true,
d->dumpPath.toStdString()));
*/
#endif
/*
if (!crashServer->Start()) {
qWarning(lcSafeguard, "crash server start failed.");
return false;
}
qInfo(lcSafeguard, "crash server ready...");
d->crashServer = crashServer;
*/
return false;
}
void QSafeguard::createClient()
{
Q_D(QSafeguard);
Q_ASSERT(!d->dumpPath.isEmpty());
Q_ASSERT(!d->pipeName.isEmpty());
#if defined(Q_OS_WIN32)
QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName;
d->exceptionHandler.reset(new google_breakpad::ExceptionHandler(d->dumpPath.toStdWString(),
nullptr,
nullptr,
nullptr,
google_breakpad::ExceptionHandler::HANDLER_ALL,
MiniDumpNormal,
pipeName.toStdWString().c_str(),
nullptr));
if (d->exceptionHandler->IsOutOfProcess()) {
qInfo(lcSafeguard, "daemon mode.");
} else {
qInfo(lcSafeguard, "normal mode.");
}
#else
/*
QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName;
d->exceptionHandler.reset(new google_breakpad::ExceptionHandler(d->dumpPath.toStdString(),
nullptr,
nullptr,
nullptr,
true,
pipeName.toStdString().c_str()));
*/
#endif
/*
if (d->exceptionHandler->IsOutOfProcess()) {
qInfo(lcSafeguard, "daemon mode.");
} else {
qInfo(lcSafeguard, "normal mode.");
}
*/
}
void QSafeguard::makeSnapshot()
{
#if defined(Q_OS_WIN32)
Q_D(QSafeguard);
if (d->exceptionHandler) {
d->exceptionHandler->WriteMinidump();
}
#endif
}
// class QSafeguardPrivate
QSafeguardPrivate::QSafeguardPrivate()
: q_ptr(nullptr)
{
}
QSafeguardPrivate::~QSafeguardPrivate()
{
}
| 33.625 | 115 | 0.390981 | ericzh86 |
5d4caf277b27ba63bbb807483211bf2ceba71b87 | 1,990 | cpp | C++ | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | #include"main.h"
#include"fireball.h"
Fireball::Fireball(color_t color){
position = glm::vec3(0,-1,0);
speed = 0.8;
speed_up = 0;
acc_y = 0;
static const GLfloat vertex_buffer_data[] = {
-0.5,-0.5,-0.5, // triangle 1 : begin
-0.5,-0.5, 0.5,
-0.5, 0.5, 0.5, // triangle 1 : end
0.5, 0.5,-0.5, // triangle 2 : begin
-0.5,-0.5,-0.5,
-0.5, 0.5,-0.5, // triangle 2 : end
0.5,-0.5, 0.5,
-0.5,-0.5,-0.5,
0.5,-0.5,-0.5,
0.5, 0.5,-0.5,
0.5,-0.5,-0.5,
-0.5,-0.5,-0.5,
-0.5,-0.5,-0.5,
-0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
0.5,-0.5, 0.5,
-0.5,-0.5, 0.5,
-0.5,-0.5,-0.5,
-0.5, 0.5, 0.5,
-0.5,-0.5, 0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
0.5,-0.5,-0.5,
0.5, 0.5,-0.5,
0.5,-0.5,-0.5,
0.5, 0.5, 0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
0.5, 0.5,-0.5,
-0.5, 0.5,-0.5,
0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
-0.5, 0.5, 0.5,
0.5, 0.5, 0.5,
-0.5, 0.5, 0.5,
0.5,-0.5, 0.5
};
this->fireball = create3DObject(GL_TRIANGLES, 36, vertex_buffer_data, color, GL_FILL);
}
void Fireball::draw(glm::mat4 VP){
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position);
Matrices.model *= translate;
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->fireball);
}
void Fireball::tick() {
this->position.x += speed*sin((rotation*M_PI)/180.0);
this->position.z += speed*cos((rotation*M_PI)/180.0);
this->position.y += speed_up;
speed_up += acc_y;
if(position.y < 0) flag = 0;
}
void Fireball::set_position(float x, float y, float z) {
this->position = glm::vec3(x, y, z);
} | 24.875 | 90 | 0.443216 | alohamora |
5d4f1ab5241e92633625bb1351f5d8ead7776e17 | 15,807 | cpp | C++ | src/string_calculator.cpp | botn365/cpp-discord-bot | 20cd173fa1a806a4c7fc44cf7e23163f78e88e79 | [
"MIT"
] | null | null | null | src/string_calculator.cpp | botn365/cpp-discord-bot | 20cd173fa1a806a4c7fc44cf7e23163f78e88e79 | [
"MIT"
] | 1 | 2021-12-19T01:46:40.000Z | 2021-12-20T18:57:07.000Z | src/string_calculator.cpp | botn365/cpp-discord-bot | 20cd173fa1a806a4c7fc44cf7e23163f78e88e79 | [
"MIT"
] | null | null | null | //
// Created by vanda on 12/10/2021.
//
#include <cmath>
#include "../include/string_calculator.hpp"
#include "../include/load_operators.hpp"
static std::unordered_map<char32_t, Bot::Operator> unicodeToOperator;
static std::unordered_map<char32_t, int> unicodeToNumber;
static std::unordered_map<char32_t, bool> usedUnicodeMap;
static std::unordered_map<std::string, double> constMap;
static std::unordered_map<std::string, Bot::Function> stringToFunction;
namespace Bot {
using usedPair = std::pair<char32_t, bool>;
using constPair = std::pair<std::string, double>;
void StringCalculator::init(std::string numeTranslationFile) {
Bot::LoadOperators::loadNumbers(numeTranslationFile);
Bot::LoadOperators::loadOperators();
usedUnicodeMap.insert(usedPair('(', true));
usedUnicodeMap.insert(usedPair(')', true));
usedUnicodeMap.insert(usedPair('{', true));
usedUnicodeMap.insert(usedPair('}', true));
usedUnicodeMap.insert(usedPair(' ', true));
usedUnicodeMap.insert(usedPair('.', true));
usedUnicodeMap.insert(usedPair(',', true));
constMap.insert(constPair("pi", M_PI));
constMap.insert(constPair("e", M_E));
constMap.insert(constPair("g", 9.8));
constMap.insert(constPair("π", 3));
constMap.insert(constPair("een", 1));
constMap.insert(constPair("twee", 2));
constMap.insert(constPair("drie", 3));
constMap.insert(constPair("vier", 4));
constMap.insert(constPair("vijf", 5));
constMap.insert(constPair("zes", 6));
constMap.insert(constPair("zeven", 7));
constMap.insert(constPair("acht", 8));
constMap.insert(constPair("negen", 9));
}
std::list<std::unique_ptr<Bot::CountObj>> Bot::StringCalculator::convertStringToRPNList(std::string_view &input) {
std::list<std::unique_ptr<CountObj>> list;
list.push_back(std::make_unique<Number>(0));
const char *end = input.data() + input.size();
auto index = list.begin();
int bracketPriorety = 0;
bool indexUp = false;
bool numberWasLast = false;
auto *multOp = getOperator('*');
std::stack<std::pair<uint64_t, Function *>> functionStack;
for (const char *i = input.data(); i < end;) {
if (list.size() > 200) return {};
double number;
if (getNumber(&i, number, end)) {
if (numberWasLast) {
insertOperatorInRPNList(list, index, multOp, bracketPriorety);
}
index = list.insert(++index, std::make_unique<Number>(number));
indexUp = false;
numberWasLast = true;
} else {
char32_t unicode;
const char *newIPos = getUnicode(i, unicode);
if (unicode == 0) {
i = newIPos;
continue;
}
if (!numberWasLast && unicode == '-') unicode = '~';
auto operatorLambda = getOperator(unicode);
if (operatorLambda != nullptr) {
if (numberWasLast && !operatorLambda->canHaveNumber()) {
insertOperatorInRPNList(list, index, multOp, bracketPriorety);
}
insertOperatorInRPNList(list, index, operatorLambda, bracketPriorety);
if (operatorLambda->isReversed()) {
index++;
indexUp = false;
} else {
numberWasLast = false;
indexUp = false;
}
i = newIPos;
} else {
int bracket = getParanthese(unicode);
if (bracket > 0) {
if (numberWasLast) {
insertOperatorInRPNList(list, index, multOp, bracketPriorety);
numberWasLast = false;
}
if (indexUp) {
index--;
indexUp = false;
}
bracketPriorety += bracket;
i = newIPos;
continue;
}
if (bracket < 0) {
indexUp = false;
bracketPriorety += bracket;
i = newIPos;
if (!functionStack.empty() && functionStack.top().first == bracketPriorety) {
operatorLambda = functionStack.top().second;
insertOperatorInRPNList(list, index, operatorLambda, bracketPriorety);
functionStack.pop();
if (operatorLambda->isReversed()) {
index++;
indexUp = false;
} else {
numberWasLast = false;
indexUp = false;
}
}
continue;
}
if (unicode == ',') {
do {
index++;
} while (shouldCommaIndexUp(index, bracketPriorety, list));
index--;
numberWasLast = false;
i = newIPos;
continue;
}
if (unicode != ' ') {
auto view = getFunctionString(&i, end);
if (*(i) == '(') {
auto functionPair = stringToFunction.find(std::string{view});
if (functionPair != stringToFunction.end()) {
functionStack.push(
std::pair<uint64_t, Function *>(bracketPriorety, &functionPair->second));
continue;
}
break;
} else {
auto value = getConst(view);
if (value == value) {
if (numberWasLast) {
insertOperatorInRPNList(list, index, multOp, bracketPriorety);
}
index = list.insert(++index, std::make_unique<Number>(value));
indexUp = true;
numberWasLast = true;
continue;
}
break;
}
}
i = newIPos;
}
}
}
list.pop_front();
return list;
}
using list = std::list<std::unique_ptr<CountObj>>;
bool StringCalculator::shouldCommaIndexUp(list::iterator &index, uint64_t bracketPriorety, list &list) {
if (index == list.end()) return false;
CountObj *ptr = (*index).get();
if (ptr->isOperator()) {
Operator *opPtr = (Operator *) ptr;
if (opPtr->priority >= bracketPriorety) return true;
}
return false;
}
double Bot::StringCalculator::calculateFromRPNList(std::list<std::unique_ptr<CountObj>> &inputList) {
std::stack<double> stack;
for (std::unique_ptr<CountObj> &value: inputList) {
if (value->isOperator()) {
Operator *op = (Operator *) (value.get());
if (!op->run(stack)) {
return NAN;
}
} else {
Number *num = (Number *) (value.get());
stack.push(num->value);
}
}
if (stack.size() != 1) return NAN;
return stack.top();
}
//add name operator pair to hashmap
void
Bot::StringCalculator::addOperator(std::string unicode, int priority, std::function<bool(std::stack<double> &)> run,
bool canHaveNumber, bool isReversed) {
char32_t unicodeValue;
getUnicode(unicode.c_str(), unicodeValue);
unicodeToOperator.insert(
std::pair<char32_t, Operator>(unicodeValue,
Operator(priority, unicode, run, canHaveNumber, isReversed)));
auto used = usedUnicodeMap.find(unicodeValue);
if (used == usedUnicodeMap.end()) {
usedUnicodeMap.insert(usedPair(unicodeValue, false));
}
}
void StringCalculator::addFunction(std::string key, int priority, std::function<bool(std::stack<double> &)> run,
bool canHaveNumber, bool isReversed) {
stringToFunction.insert(
std::pair<std::string, Function>(key, Function(priority, key, run, canHaveNumber, isReversed)));
}
//add name digit pair to hashmap
void Bot::StringCalculator::addUnicodeNumber(char32_t unicode, int value) {
unicodeToNumber.insert(std::pair<char32_t, int>(unicode, value));
usedUnicodeMap.insert(std::pair<char32_t, int>(unicode, true));
}
int Bot::StringCalculator::getParanthese(char32_t &unicode) {
if (unicode == '(') {
return 10;
} else if (unicode == ')') {
return -10;
}
return 0;
}
//inserts an operator in to the list
void
Bot::StringCalculator::insertOperatorInRPNList(std::list<std::unique_ptr<CountObj>> &list,
std::list<std::unique_ptr<CountObj>>::iterator &index,
Bot::Operator *operand, int paranthesePriorety) {
index++;
while (index != list.end()) {
if ((*index)->isOperator()) {
auto *op = (Operator *) (*index).get();
int priorety = op->priority;
if (priorety < operand->priority + paranthesePriorety) {
index = list.insert(index,
std::make_unique<Operator>(operand->priority + paranthesePriorety,
operand->name, operand->run));
index--;
return;
}
}
index++;
}
index = list.insert(index, std::make_unique<Operator>(operand->priority + paranthesePriorety, operand->name,
operand->run));
index--;
}
Bot::Operator *Bot::StringCalculator::getOperator(char32_t unicode) {
auto result = unicodeToOperator.find(unicode);
if (result == unicodeToOperator.end()) return nullptr;
return &result->second;
}
int Bot::StringCalculator::getNumberFromUnicode(const char32_t &unicode) {
auto result = unicodeToNumber.find(unicode);
if (result == unicodeToNumber.end()) return -1;
return result->second;
}
bool Bot::StringCalculator::getNumber(const char **input, double &number, const char *end) {
number = 0;
bool comma = false;
bool hasNumber = false;
unsigned int multiplyer = 10;
const char *old = nullptr;
while (*input < end) {
char32_t unicode;
const char *value = getUnicode(*input, unicode);
if (value == old) return false;
old = value;
int result = getNumberFromUnicode(unicode);
if (result == -1) {
if (unicode == '_') {
*input = value;
continue;
}
if (unicode == '.') {
*input = value;
comma = true;
} else {
break;
}
} else {
*input = value;
if (comma) {
number += ((double) result / multiplyer);
multiplyer *= 10;
} else {
number *= multiplyer;
number += result;
hasNumber = true;
}
}
}
return hasNumber;
}
const char *Bot::StringCalculator::getUnicode(const char *input, char32_t &unicode) {
if ((*input & 0x80) == 0) {
unicode = *input;
return ++input;
} else if ((*input & 0xE0) == 192) {
unicode = convertToUnicode(input, 2);
return input += 2;
} else if ((*input & 0xF0) == 224) {
unicode = convertToUnicode(input, 3);
return input += 3;
} else if ((*input & 0xF8) == 240) {
unicode = convertToUnicode(input, 4);
return input += 4;
}
unicode = 0;
return ++input;
}
//converts a char* to name while checking if it is formed correctly
char32_t Bot::StringCalculator::convertToUnicode(const char *input, int len) {
unsigned char value = *input;
char32_t out = value;
for (int i = 1; i < len; i++) {
if (i == 0 || (*(input + i) & 0xc0) == 0x80) {
out <<= 8;
value = *(input + i);
out += value;
} else {
return 0;
}
}
return out;
}
std::string StringCalculator::unicodeToString(char32_t unicode) {
std::string out;
for (int i = 3; i >= 0; i--) {
unsigned char ch = (unicode >> (i * 8)) % 256;
if (ch != 0) {
out += ch;
}
}
return out;
}
bool StringCalculator::isUnicodeUsed(char32_t unicode) {
return usedUnicodeMap.find(unicode) != usedUnicodeMap.end();
}
std::string_view Bot::StringCalculator::getFunctionString(const char **currentChar, const char *end) {
const char *newPos = *currentChar;
while (newPos != end) {
char32_t unicode;
const char *tempPos = getUnicode(newPos, unicode);
if (usedUnicodeMap.find(unicode) != usedUnicodeMap.end()) {
std::string_view view(*currentChar, newPos - *currentChar);
*currentChar = newPos;
return view;
} else {
newPos = tempPos;
}
}
std::string_view view(*currentChar, end - *currentChar);
*currentChar = newPos;
return view;
}
double Bot::StringCalculator::getConst(std::string_view &view) {
auto value = constMap.find(std::string(view));
if (value != constMap.end()) {
return value->second;
}
return NAN;
}
bool Bot::StringCalculator::hasFunction(std::string &str) {
return stringToFunction.find(str) != stringToFunction.end();
}
bool Bot::StringCalculator::hasConst(std::string &str) {
return constMap.find(str) != constMap.end();
}
double StringCalculator::floor(double in) {
return std::floor(in + 0.000001);
}
std::unordered_map<char32_t, Bot::Operator> StringCalculator::getOperatorMap() {
return unicodeToOperator;
}
std::unordered_map<char32_t, int> StringCalculator::getNumberMap() {
return unicodeToNumber;
}
std::unordered_map<std::string, Bot::Function> StringCalculator::getFunctionMap() {
return stringToFunction;
}
std::unordered_map<std::string, double> StringCalculator::getConstMap() {
return constMap;
}
}
| 38.742647 | 120 | 0.486746 | botn365 |
5d51795d9f817177e42f08b1df322aed162b9210 | 35,686 | cpp | C++ | src/validate.cpp | biologic/stylus | ae642bbb7e2205bab1ab1b4703ea037e996e13db | [
"Apache-2.0"
] | null | null | null | src/validate.cpp | biologic/stylus | ae642bbb7e2205bab1ab1b4703ea037e996e13db | [
"Apache-2.0"
] | null | null | null | src/validate.cpp | biologic/stylus | ae642bbb7e2205bab1ab1b4703ea037e996e13db | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* \file validate.cpp
* \brief Stylus Gene class (validation methods)
*
* Stylus, Copyright 2006-2009 Biologic Institute
*
* 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.
*******************************************************************************/
// Includes ---------------------------------------------------------------------
#include "headers.hpp"
using namespace std;
using namespace stylus;
//--------------------------------------------------------------------------------
//
// Stroke
//
//--------------------------------------------------------------------------------
/*
* Function: calcDimensions
*
*/
void
Stroke::calcDimensions(Gene& gene)
{
ENTER(VALIDATION,calcDimensions);
const ACIDTYPEARRAY& vecAcids = gene.getAcids();
const POINTARRAY& vecPoints = gene.getPoints();
long iAcid = _rgAcids.getStart()-1;
ASSERT(iAcid >= 0);
// Strokes begin where the previous vector ends
Point ptTopLeft(vecPoints[iAcid]);
Point ptBottomRight(vecPoints[iAcid]);
// Sum the lengths of vectors contained in the stroke
ASSERT(_slVectors.getLength() == 0);
for (++iAcid; iAcid <= _rgAcids.getEnd(); ++iAcid)
{
const Point& pt = vecPoints[iAcid];
if (pt.x() < ptTopLeft.x())
ptTopLeft.x() = pt.x();
if (pt.y() > ptTopLeft.y())
ptTopLeft.y() = pt.y();
if (pt.x() > ptBottomRight.x())
ptBottomRight.x() = pt.x();
if (pt.y() < ptBottomRight.y())
ptBottomRight.y() = pt.y();
_slVectors += vecAcids[iAcid];
}
// Set the bounds to the extreme top/left and bottom/right encountered
_rectBounds.set(ptTopLeft, ptBottomRight);
TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld has bounds %s", (_id+1), _rectBounds.toString().c_str()));
}
/*
* Function: calcScale
*
*/
bool
Stroke::calcScale(Gene& gene, const HStroke& hst)
{
ENTER(VALIDATION,calcScale);
bool fDimensionMissing = false;
const Rectangle& rectHBounds = hst.getBounds();
// Calculate the x/y scale factors
// - If either the stroke or Han is missing profile along a dimension, skip it
// (the stroke will eventually inherit the scale factor from its containing group)
if (rectHBounds.getWidth() > 0 && _rectBounds.getWidth() > 0)
_sxToHan = rectHBounds.getWidth() / _rectBounds.getWidth();
else
{
fDimensionMissing = true;
_sxToHan.setUndefined();
}
if (rectHBounds.getHeight() > 0 && _rectBounds.getHeight() > 0)
_syToHan = rectHBounds.getHeight() / _rectBounds.getHeight();
else
{
fDimensionMissing = true;
_syToHan.setUndefined();
}
// Calculate the scale factor used with diagonal lengths
if (!fDimensionMissing)
_sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan));
else
_sxyToHan.setUndefined();
TDATA(VALIDATION,L3,(LLTRACE,
"Stroke %ld has sx/sy/sxy(%6.15f,%6.15f,%6.15f)",
(_id+1),
static_cast<UNIT>(_sxToHan),
static_cast<UNIT>(_syToHan),
static_cast<UNIT>(_sxyToHan)));
ASSERT(fDimensionMissing || (_sxToHan.isDefined() && _syToHan.isDefined() && _sxyToHan.isDefined()));
return fDimensionMissing;
}
/*
* Function: promoteScale
*
*/
void
Stroke::promoteScale(UNIT sxToHan, UNIT syToHan)
{
ENTER(VALIDATION,promoteScale);
// If a dimension lacked profile, take the passed scale for the dimension
if (!_sxToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld taking sxToHan(%f) from Group", (_id+1), sxToHan));
_sxIsInherited = true;
_sxToHan = sxToHan;
}
if (!_syToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld taking syToHan(%f) from Group", (_id+1), syToHan));
_syIsInherited = true;
_syToHan = syToHan;
}
if (!_sxyToHan.isDefined())
_sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan));
}
/*
* Function: calcOffsets
*
*/
void
Stroke::calcOffsets(Group& grp, const HStroke& hst)
{
ENTER(VALIDATION,calcOffsets);
const Rectangle& rectHBounds = hst.getBounds();
_dxToHan = rectHBounds.getCenter().x() - (_rectBounds.getCenter().x() * _sxToHan);
_dyToHan = rectHBounds.getCenter().y() - (_rectBounds.getCenter().y() * _syToHan);
_dxParentToHan = rectHBounds.getCenter().x() - (_rectBounds.getCenter().x() * grp.sxToHan());
_dyParentToHan = rectHBounds.getCenter().y() - (_rectBounds.getCenter().y() * grp.syToHan());
TDATA(VALIDATION,L3,(LLTRACE,
"Stroke %ld has dx/dy(%6.15f,%6.15f) dx/dyParent(%6.15f,%6.15f)",
(_id+1),
static_cast<UNIT>(_dxToHan),
static_cast<UNIT>(_dyToHan),
static_cast<UNIT>(_dxParentToHan),
static_cast<UNIT>(_dyParentToHan)));
}
//--------------------------------------------------------------------------------
//
// Group
//
//--------------------------------------------------------------------------------
/*
* Function: calcDimensions
*
*/
void
Group::calcDimensions(Gene& gene, const HGroup& hgrp)
{
ENTER(VALIDATION,calcDimensions);
STROKEARRAY& vecStrokes = gene.getStrokes();
const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes();
ASSERT(vecContainedHStrokes.size() > 0);
// Set group bounds to the union of all contained strokes
for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke)
{
Stroke& st = vecStrokes[gene.mapHanToStroke(vecContainedHStrokes[iContainedStroke])];
st.calcDimensions(gene);
if (iContainedStroke == 0)
_rectBounds = st.getBounds();
else
_rectBounds.combine(st.getBounds());
}
TDATA(VALIDATION,L3,(LLTRACE, "Group %ld has bounds %s", (_id+1), _rectBounds.toString().c_str()));
}
/*
* Function: calcScale
*
*/
bool
Group::calcScale(Gene& gene, const Han& han, const HGroup& hgrp)
{
ENTER(VALIDATION,calcScale);
STROKEARRAY& vecStrokes = gene.getStrokes();
const HSTROKEARRAY& vecHStrokes = han.getStrokes();
const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes();
Unit nxToHan = 0;
Unit nyToHan = 0;
Unit sxToHan = 0;
Unit syToHan = 0;
bool fDimensionMissing = false;
// Compute the mean sx/sy scale factors for the contained strokes
// - Only strokes with profile along a dimension contribute to the mean
for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke)
{
size_t iHStroke = vecContainedHStrokes[iContainedStroke];
Stroke& st = vecStrokes[gene.mapHanToStroke(iHStroke)];
const HStroke& hst = vecHStrokes[iHStroke];
fDimensionMissing = st.calcScale(gene, hst) || fDimensionMissing;
if (hst.getBounds().getWidth() > 0 && st.getBounds().getWidth() > 0)
{
sxToHan += hst.getBounds().getWidth() * st.sxToHan();
nxToHan += hst.getBounds().getWidth();
}
else
fDimensionMissing = true;
if (hst.getBounds().getHeight() > 0 && st.getBounds().getHeight() > 0)
{
syToHan += hst.getBounds().getHeight() * st.syToHan();
nyToHan += hst.getBounds().getHeight();
}
else
fDimensionMissing = true;
}
if (nxToHan > static_cast<UNIT>(0.0))
_sxToHan = sxToHan / nxToHan;
else
{
fDimensionMissing = true;
_sxToHan.setUndefined();
}
if (nyToHan > static_cast<UNIT>(0.0))
_syToHan = syToHan / nyToHan;
else
{
fDimensionMissing = true;
_syToHan.setUndefined();
}
ASSERT(fDimensionMissing || (_sxToHan.isDefined() && _syToHan.isDefined()));
TDATA(VALIDATION,L3,(LLTRACE,
"Group %ld has sx/sy(%6.15f,%6.15f)",
(_id+1),
static_cast<UNIT>(_sxToHan),
static_cast<UNIT>(_syToHan)));
return fDimensionMissing;
}
/*
* Function: promoteScale
*
*/
void
Group::promoteScale(Gene& gene, const HGroup& hgrp, UNIT sxToHan, UNIT syToHan)
{
ENTER(VALIDATION,promoteScale);
STROKEARRAY& vecStrokes = gene.getStrokes();
const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes();
// If a dimension lacked profile, take the passed scale for the dimension
if (!_sxToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Group %ld taking sxToHan(%f) from Gene", (_id+1), sxToHan));
_sxIsInherited = true;
_sxToHan = sxToHan;
}
if (!_syToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Group %ld taking syToHan(%f) from Gene", (_id+1), syToHan));
_syIsInherited = true;
_syToHan = syToHan;
}
// Promote the group scale factors to any strokes missing scale factors
TDATA(VALIDATION,L3,(LLTRACE,
"Group %ld promoting sx/sy(%f,%f) to strokes",
(_id+1), static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan)));
for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke)
{
vecStrokes[gene.mapHanToStroke(vecContainedHStrokes[iContainedStroke])].promoteScale(_sxToHan, _syToHan);
}
}
/*
* Function: calcOffsets
*
*/
void
Group::calcOffsets(Gene& gene, const Han& han, const HGroup& hgrp)
{
ENTER(VALIDATION,calcOffsets);
ASSERT(_sxToHan.isDefined());
ASSERT(_syToHan.isDefined());
ASSERT(Unit(gene.sxToHan()).isDefined());
ASSERT(Unit(gene.syToHan()).isDefined());
ASSERT(_dxToHan == static_cast<UNIT>(0.0));
ASSERT(_dyToHan == static_cast<UNIT>(0.0));
STROKEARRAY& vecStrokes = gene.getStrokes();
const HSTROKEARRAY& vecHStrokes = han.getStrokes();
const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes();
Unit dxToHan = 0.0;
Unit dyToHan = 0.0;
// Allow each stroke to determine its dx/dy translation offsets and accumulate the weighted sum of their centers
for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke)
{
size_t iHStroke = vecContainedHStrokes[iContainedStroke];
Stroke& st = vecStrokes[gene.mapHanToStroke(iHStroke)];
const HStroke& hst = vecHStrokes[iHStroke];
st.calcOffsets(*this, hst);
const Point& ptStrokeCenter = st.getBounds().getCenter();
dxToHan += hst.getLength() * ptStrokeCenter.x();
dyToHan += hst.getLength() * ptStrokeCenter.y();
}
// Convert the weighted sum into the dx/dy for the group by measuring it
// against the weighted center of the Han group
dxToHan /= hgrp.getLength();
dyToHan /= hgrp.getLength();
const Point& ptHanWeightedCenter = hgrp.getWeightedCenter();
_dxToHan = ptHanWeightedCenter.x() - (dxToHan * _sxToHan);
_dyToHan = ptHanWeightedCenter.y() - (dyToHan * _syToHan);
_dxParentToHan = ptHanWeightedCenter.x() - (dxToHan * gene.sxToHan());
_dyParentToHan = ptHanWeightedCenter.y() - (dyToHan * gene.syToHan());
TDATA(VALIDATION,L3,(LLTRACE,
"Group %ld has dx/dy(%6.15f,%6.15f) dx/dyParent(%6.15f,%6.15f)",
(_id+1),
static_cast<UNIT>(_dxToHan),
static_cast<UNIT>(_dyToHan),
static_cast<UNIT>(_dxParentToHan),
static_cast<UNIT>(_dyParentToHan)));
}
//--------------------------------------------------------------------------------
//
// StrokeRangeChange
//
//--------------------------------------------------------------------------------
/*
* Function: StrokeRangeChange
*
*/
StrokeRangeChange::StrokeRangeChange(size_t idGene, const vector<Range>& vecStrokeRanges)
{
ASSERT(!Genome::isState(STGS_ROLLBACK) && !Genome::isState(STGS_RESTORING));
_idGene = idGene;
_vecStrokeRanges = vecStrokeRanges;
}
/*
* Function: undoChange
*
*/
void
StrokeRangeChange::undo()
{
ENTER(MUTATION,undoChange);
TFLOW(MUTATION,L4,(LLTRACE, "Undoing %s", toString().c_str()));
ASSERT(Genome::isState(STGS_ROLLBACK) || Genome::isState(STGS_RESTORING));
Gene& gene = Genome::getGeneById(_idGene);
STROKEARRAY& vecStrokes = gene.getStrokes();
ASSERT(_vecStrokeRanges.size() == vecStrokes.size());
for (size_t iStroke=0; iStroke < vecStrokes.size(); ++iStroke)
vecStrokes[iStroke].setRange(_vecStrokeRanges[iStroke]);
gene.markInvalid(Gene::GI_STROKES);
}
/*
* Function: toString
*
*/
string
StrokeRangeChange::toString() const
{
ENTER(MUTATION,toString);
ostringstream ostr;
ostr << "Stroke Ranges changed from: ";
for (size_t iStroke=0; iStroke < _vecStrokeRanges.size(); ++iStroke)
{
ostr << iStroke << _vecStrokeRanges[iStroke].toString();
if (iStroke < _vecStrokeRanges.size()-1)
ostr << Constants::s_chBLANK;
}
return ostr.str();
}
//--------------------------------------------------------------------------------
//
// Gene
//
//--------------------------------------------------------------------------------
/*
* Function: ensureAcids
*
* Compile the codons into ACIDTYPEs and establish the point at the end
* of each vector (the start vector is located at _ptOrigin).
*/
void
Gene::ensureAcids(size_t iAcidChange, long cAcidsChanged)
{
ENTER(VALIDATION,ensureAcids);
ASSERT(iAcidChange == 0 || !Genome::isState(STGS_VALIDATING));
ASSERT(iAcidChange == 0 || static_cast<long>(_vecAcids.size()) == Codon::numWholeCodons(_rgBases.getLength()));
ASSERT(iAcidChange == 0 || _vecAcids.size() == _vecPoints.size());
if (_vecAcids.empty())
{
size_t cAcids = Codon::numWholeCodons(_rgBases.getLength());
ASSERT(_rgBases.isEmpty() || cAcids >= 2);
_vecAcids.resize(cAcids);
_vecPoints.resize(cAcids);
iAcidChange = 0;
cAcidsChanged = _vecAcids.size();
}
TFLOW(VALIDATION,L3,(LLTRACE, "Creating acids from %ld for %ld codons", (iAcidChange+1), cAcidsChanged));
ASSERT(_vecAcids.size() >= 2);
ASSERT(_vecAcids.size() == _vecPoints.size());
ASSERT(_vecAcids.size() == static_cast<size_t>(_rgBases.getLength() / Codon::s_cchCODON));
// If acids were added, convert the corresponding bases to ACIDTYPEs
if (cAcidsChanged > 0)
{
const char* pszBases = Genome::getBases().c_str();
size_t iBase = _rgBases.getStart() + (iAcidChange * Codon::s_cchCODON);
size_t iAcid = iAcidChange;
size_t iAcidEnd = iAcidChange + cAcidsChanged;
for (; iAcid < iAcidEnd; iBase += Codon::s_cchCODON, ++iAcid)
_vecAcids[iAcid] = Genome::codonToType(pszBases+iBase);
}
// Calculate the points associated with each acid from the point of change onward
// - The point associated with the first codon is the origin of the gene; all others
// are the value after applying the acid (that is, the start codon is treated as
// a zero-length acid)
Point pt;
size_t iAcid = iAcidChange;
if (iAcid <= 0)
{
_vecPoints[0] = _ptOrigin;
iAcid++;
}
pt = _vecPoints[iAcid-1];
for (; iAcid < _vecPoints.size(); ++iAcid)
{
pt += _vecAcids[iAcid];
_vecPoints[iAcid] = pt;
}
// Calculate the total vector length of the gene
// - The length excludes the start and stop codons
_nUnits = 0;
for (iAcid=1; iAcid < _vecAcids.size()-1; iAcid++)
_nUnits += Acid::typeToAcid(_vecAcids[iAcid]).getLength();
TDATA(VALIDATION,L3,(LLTRACE, "Gene has %0.15f total units", static_cast<UNIT>(_nUnits)));
markValid(GI_ACIDS | GI_POINTS);
}
/*
* Function: ensureCoherence
*
* Determine the coherence of each vector by examining all possible trivectors.
* For each vector is a coherence count, ranging from 0 to 3, indicating how
* many trivectors within which it was found.
*/
void
Gene::ensureCoherence()
{
ENTER(VALIDATION,ensureCoherence);
ASSERT(isValid(GI_ACIDS));
ASSERT(_vecAcids.size() >= Codon::s_nTRIVECTOR+2);
if (_vecCoherent.empty())
_vecCoherent.resize(_vecAcids.size());
ASSERT(_vecCoherent.size() >= Codon::s_nTRIVECTOR+2);
ASSERT(_vecAcids.size() == _vecCoherent.size());
ASSERT(Acid::typeToAcid(_vecAcids[_vecAcids.size()-1]).isStop());
_vecCoherent[0] = 0;
_vecCoherent[1] = 0;
_vecCoherent[2] = 0;
for (long iAcid=1; !Acid::typeToAcid(_vecAcids[iAcid+2]).isStop(); ++iAcid)
{
_vecCoherent[iAcid+2] = 0;
if (Codon::isCoherent(_vecAcids[iAcid+0], _vecAcids[iAcid+1], _vecAcids[iAcid+2]))
{
++_vecCoherent[iAcid+0];
++_vecCoherent[iAcid+1];
++_vecCoherent[iAcid+2];
}
}
markValid(GI_COHERENCE);
}
/*
* Function: ensureSegments
*
* A segment is a continuous range of coherent or incoherent vectors.
* This routine walks the coherence array, building as many segments
* as necessary.
*
* NOTES:
* - Strokes could be built up from the coherence array without directly
* using the notion of segments; however, since strokes deal with coherent
* ranges, first dividing the vectors into segments makes sense
*/
void
Gene::ensureSegments()
{
ENTER(VALIDATION,ensureSegments);
ASSERT(isValid(GI_ACIDS | GI_COHERENCE));
ASSERT(_vecAcids.size() >= Codon::s_nTRIVECTOR+2);
ASSERT(_vecCoherent.size() >= Codon::s_nTRIVECTOR+2);
ASSERT(_vecAcids.size() == _vecCoherent.size());
ASSERT(Acid::typeToAcid(_vecAcids[_vecAcids.size()-1]).isStop());
bool fWasCoherent = !(_vecCoherent[1] > 0);
long iSegment = -1;
_vecSegments.clear();
// Iterate across all vectors between the start and stop codon
for (long iAcid=1; !Acid::typeToAcid(_vecAcids[iAcid]).isStop(); ++iAcid)
{
bool fIsCoherent = (_vecCoherent[iAcid] > 0);
if (fWasCoherent != fIsCoherent)
{
fWasCoherent = fIsCoherent;
++iSegment;
_vecSegments.resize(iSegment+1);
if (fIsCoherent)
++_cCoherent;
Segment& sg = _vecSegments.back();
sg.setRange(Range(iAcid,iAcid));
sg.setCoherent(fIsCoherent);
sg = _vecAcids[iAcid];
}
else
{
Segment& sg = _vecSegments.back();
sg += _vecAcids[iAcid];
sg.setEnd(iAcid);
}
}
// Since, coherent and incoherent segments alternate,
// their absolute difference should never exceed one
ASSERT(::abs(static_cast<size_t>(_vecSegments.size() - (2 * _cCoherent))) <= 1);
TFLOW(VALIDATION,L3,(LLTRACE, "%d segments created", _vecSegments.size()));
TRACEDOIF(VALIDATION,DATA,L3,traceSegments());
markValid(GI_SEGMENTS);
}
/*
* Function: ensureStrokes
*
* A stroke is a sequence of coherent vectors possibly separated by small,
* incoherent regions (called "dropouts"). Generally, this routine maps the
* coherent segments to the appropriate stroke (or treats them as strokes).
* Coherent segments occurring outside of any stroke are referred to as
* "marks".
*/
void
Gene::ensureStrokes()
{
ENTER(VALIDATION,ensureStrokes);
vector<Range> vecStrokeRanges(_vecStrokes.size());
NUMERICMAP vecPotentialStrokeSegments;
size_t iStroke = 0;
size_t iSegment = 0;
// NOTE:
// - For now, stroke locations must be assigned with the Han glyph.
// Stroke discovery is possible, but requires mapping strokes to the Han
// glyph while preserving the notion of dropouts and marks.
ASSERT(_fStrokesAssigned);
if (!_fStrokesAssigned)
THROWRC((RC(ERROR), "Gene requires that stroke locations be assigned with the Han glyph"));
// Each stroke requires at least one coherent segment
if (_cCoherent < _vecStrokes.size())
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION,
"Gene has too few coherent segments (%ld) for strokes (%ld)",
_cCoherent, _vecStrokes.size());
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES,
"Gene has too few coherent segments (%ld) for strokes (%ld)",
_cCoherent, _vecStrokes.size());
goto INVALID;
}
TFLOW(VALIDATION,L3,(LLTRACE,
"Assigning %ld segments to %ld strokes",
_vecSegments.size(), _vecStrokes.size()));
// Save the current stroke ranges and ensure they are initially valid
for (size_t iStroke=0; iStroke < _vecStrokes.size(); ++iStroke)
{
Stroke& st = _vecStrokes[iStroke];
if (st.getStart() <= 0 || st.getEnd() >= static_cast<long>(_vecAcids.size())-1 || st.getRange().getLength() < Codon::s_nTRIVECTOR)
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION,
"Stroke %ld has an invalid range of %s", (iStroke+1), st.getRange().toString().c_str());
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES,
"Stroke %ld has an invalid range of %s", (iStroke+1), st.getRange().toString().c_str());
goto INVALID;
}
vecStrokeRanges[iStroke] = st.getRange();
TDATA(VALIDATION,L4,(LLTRACE, "Stroke %ld has an expected range of %s", (iStroke+1), st.getRange().toString().c_str()));
}
//--------------------------------------------------------------------------------------------
// Generally, coherent segments map to strokes and incoherent segments to the moves between
// strokes. However, allowing for small incoherent regions within strokes (dropouts) and
// shifting stroke boundaries complicates matters. The relationship between a segment and a
// stroke is characterized by their endpoints; the Stroke 'S' and the Segments 'A', 'B',
// 'C', 'D', 'E' and 'F'...
//
// |---- A ----| |---- F ----|
// |---- B ----| |---- E ----|
// |---------- C ----------|
// |---- D ----|
// |-------- S --------|
//
// ... have the following relationships:
//
// fStartBefore fStartContained fStartAfter fEndBefore fEndContained fEndAfter
// A x x
// B x x
// C x x
// D x x
// E x x
// F x x
//
//--------------------------------------------------------------------------------------------
// Walk the segment array and determine stroke locations as long as strokes exist
while (iSegment < _vecSegments.size() && iStroke < _vecStrokes.size())
{
const Segment& sg = _vecSegments[iSegment];
Stroke& st = _vecStrokes[iStroke];
bool fStrokeStarted = false;
// Adjoining segments can never have the same coherency
ASSERT( iSegment >= _vecSegments.size()-1
|| _vecSegments[iSegment+1].isCoherent() != sg.isCoherent());
// Coherent segments can never be smaller than a trivector
ASSERT( !sg.isCoherent()
|| sg.getRange().getLength() >= Codon::s_nTRIVECTOR);
// Determine endpoint relationships (see comments above)
bool fStartBefore = (st.getStart() - sg.getStart()) > 0;
bool fStartAfter = (sg.getStart() - st.getEnd()) > 0;
bool fEndBefore = (st.getStart() - sg.getEnd()) > 0;
bool fEndAfter = (sg.getEnd() - st.getEnd()) > 0;
ASSERT(!(fStartBefore && fStartAfter));
ASSERT(!(fEndBefore && fEndAfter));
ASSERT(!fEndBefore || fStartBefore);
ASSERT(!fStartAfter || fEndAfter);
bool fStartContained = (!fStartBefore && !fStartAfter);
bool fEndContained = (!fEndBefore && !fEndAfter);
bool fAdvanceSegment = true;
bool fAdvanceStroke = false;
// Handle each segment/stroke case (see above), adjusting the stroke boundaries as needed
// - For coherent segments, stroke boundaries are extend to co-extensive with the segment
// - For incoherent segments, stroke boundaries are extend (in the appropriate direction)
// one past the segment to either avoid the segment or reach past it into the next
// coherent segment
// Case A: Segment lies wholly before the stroke
if (fEndBefore)
{
ASSERT(!st.getSegments());
if (sg.isCoherent())
{
if ( iSegment < _vecSegments.size()-2
&& _vecSegments[iSegment+1].getRange().getLength() <= s_cDROPOUT)
vecPotentialStrokeSegments.push_back(iSegment);
else
{
for (size_t iMark=0; iMark < vecPotentialStrokeSegments.size(); ++iMark)
{
_vecMarks.push_back(vecPotentialStrokeSegments[iMark]);
TFLOW(VALIDATION,L4,(LLTRACE, "CASE A: Segment %ld is a mark and lies before stroke %ld", (vecPotentialStrokeSegments[iMark]+1), (iStroke+1)));
}
vecPotentialStrokeSegments.clear();
_vecMarks.push_back(iSegment);
TFLOW(VALIDATION,L4,(LLTRACE, "CASE A: Segment %ld is a mark and lies before stroke %ld", (iSegment+1), (iStroke+1)));
}
}
}
// Case B: Segment overlaps stroke start
else if (fStartBefore && fEndContained)
{
ASSERT(!st.getSegments());
if (sg.isCoherent())
{
st.setStart(sg.getStart());
st.incSegments();
fStrokeStarted = true;
}
else
{
st.setEnd(max<long>(sg.getEnd()+1, st.getEnd()));
st.setStart(sg.getEnd()+1);
}
TFLOW(VALIDATION,L4,(LLTRACE, "CASE B: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1)));
}
// Case C: Segment overlaps entire stroke
else if (fStartBefore && fEndAfter)
{
ASSERT(!st.getSegments());
if (sg.isCoherent())
{
st.setRange(sg.getRange());
st.incSegments();
fStrokeStarted = true;
TFLOW(VALIDATION,L4,(LLTRACE, "CASE C: Segment %ld set the range for stroke %ld", (iSegment+1), (iStroke+1)));
}
else
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
goto RECORDUNDO;
}
}
// Case D: Segment is wholly contained in the stroke
// Case E: Segment overlaps stroke end
else if (fStartContained && (fEndContained || fEndAfter))
{
if (sg.isCoherent())
{
if (!st.getSegments())
{
st.setStart(sg.getStart());
fStrokeStarted = true;
TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1)));
}
if (fEndAfter)
{
st.setEnd(sg.getEnd());
TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1)));
}
st.incSegments();
}
else
{
if (!st.getSegments())
{
if (fEndAfter)
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
goto RECORDUNDO;
}
st.setEnd(max<long>(sg.getEnd()+1, st.getEnd()));
st.setStart(sg.getEnd()+1);
TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1)));
}
else if ( iSegment < _vecSegments.size()-1
&& sg.getRange().getLength() <= s_cDROPOUT)
{
st.setEnd(max<long>(sg.getEnd()+1, st.getEnd()));
st.incSegments();
st.incDropouts();
}
else
{
st.setEnd(sg.getStart()-1);
fAdvanceSegment = false;
fAdvanceStroke = true;
TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1)));
}
}
}
// Case F: Segment lies wholly after the stroke
else
{
ASSERT(fStartAfter);
ASSERT(!sg.isCoherent());
if (!st.getSegments())
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES,
"Stroke %ld lost to incoherent segment %ld %s",
(iStroke+1), (iSegment+1), sg.getRange().toString().c_str());
goto RECORDUNDO;
}
if ( iSegment < _vecSegments.size()-1
&& sg.getRange().getLength() <= s_cDROPOUT)
{
st.setEnd(sg.getEnd()+1);
st.incSegments();
st.incDropouts();
}
else
{
st.setEnd(sg.getStart()-1);
fAdvanceSegment = false;
fAdvanceStroke = true;
}
TFLOW(VALIDATION,L4,(LLTRACE, "CASE F: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1)));
}
// If the segment set the start of a stroke, add to the stroke any outstanding potential stroke segments
// - The collection is a series of coherent segments within dropout distance of one another (including
// the segment that started the stroke). The number of segments added to the stroke is the total number
// of collected coherent segments plus the intervening incoherent segments.
if (fStrokeStarted && vecPotentialStrokeSegments.size())
{
st.setStart(_vecSegments[vecPotentialStrokeSegments[0]].getStart());
st.incSegments(vecPotentialStrokeSegments.size() * 2);
st.incDropouts(vecPotentialStrokeSegments.size());
TFLOW(VALIDATION,L4,(LLTRACE, "%ld possible marks assigned to stroke %ld", vecPotentialStrokeSegments.size(), (iStroke+1)));
vecPotentialStrokeSegments.clear();
}
// Advance to the next segment and stroke as needed
if (fAdvanceSegment)
++iSegment;
if (fAdvanceStroke)
{
++iStroke;
ASSERT(vecPotentialStrokeSegments.empty());
}
}
ASSERT(vecPotentialStrokeSegments.empty());
// Gene is invalid if not all strokes received at least one coherent segment
if ( iStroke < _vecStrokes.size()-1
|| ( iStroke == _vecStrokes.size()-1
&& _vecStrokes[iStroke].getSegments() <= 0))
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Unable to assign segments to all strokes");
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Unable to assign segments to all strokes");
goto RECORDUNDO;
}
// Ensure the last stroke has been assigned its appropriate end position
// - The loop above terminates a stroke when it encounters an incoherent
// segment exceeding the dropout length; if it exhausted segments before
// strokes, the last stroke will require termination
ASSERT( iStroke >= _vecStrokes.size()
|| ( iStroke == _vecStrokes.size()-1
&& iSegment >= _vecSegments.size()
&& ( _vecSegments.back().isCoherent()
|| _vecSegments.back().getRange().getLength() <= static_cast<long>(s_cDROPOUT))));
if (iStroke == _vecStrokes.size()-1)
{
TFLOW(VALIDATION,L4,(LLTRACE, "Segment %ld set the end for stroke %ld", iSegment, iStroke));
const Segment& sg = _vecSegments.back();
_vecStrokes.back().setEnd(sg.isCoherent()
? sg.getEnd()
: sg.getStart()-1);
}
// Count all coherent segments occurring after all strokes as marks
for (; iSegment < _vecSegments.size(); ++iSegment)
{
if (_vecSegments[iSegment].isCoherent())
_vecMarks.push_back(iSegment);
}
markValid(GI_STROKES);
TRACEDOIF(VALIDATION,DATA,L3,traceStrokes());
RECORDUNDO:
// If the stroke ranges changed, record the changes
for (size_t iStroke=0; iStroke < _vecStrokes.size(); ++iStroke)
{
if (_vecStrokes[iStroke].getRange() != vecStrokeRanges[iStroke])
{
Genome::recordModification(::new StrokeRangeChange(_id, vecStrokeRanges));
if (!Genome::isRollbackAllowed())
LOGWARNING((LLWARNING, "Change occured in stroke range for stroke %ld - %s to %s",
iStroke+1,
vecStrokeRanges[iStroke].toString().c_str(),
_vecStrokes[iStroke].getRange().toString().c_str()));
break;
}
}
INVALID:
;
}
/*
* Function: ensureDimensions
*
* Determine the bounding rectangles along with the scale factors and translation offsets
* to align strokes, groups, and the gene against the Han.
*
* Processing works from the strokes up and establishes bounding rectangles, then scale
* factors, and finally translation offsets. (Translation offsets are applied to scaled
* coordinates.) If any element cannot calculate a scale factor (due to missing profile
* along a dimension), a second scale pass promotes parent scale factors to children.
*/
void
Gene::ensureDimensions()
{
ENTER(VALIDATION,ensureDimensions);
const Han& han = Han::getDefinition(_strUnicode);
const HGROUPARRAY& vecHGroups = han.getGroups();
// First, calculate all group and stroke dimensions (groups will invoke strokes)
// - Determine the gene dimensions along the way
for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup)
{
_vecGroups[iGroup].calcDimensions(*this, vecHGroups[iGroup]);
if (iGroup == 0)
_rectBounds.set(_vecGroups[iGroup].getBounds());
else
_rectBounds.combine(_vecGroups[iGroup].getBounds());
}
Unit nxToHan = 0;
Unit nyToHan = 0;
Unit sxToHan = 0;
Unit syToHan = 0;
Unit dxToHan = 0;
Unit dyToHan = 0;
bool fDimensionMissing = false;
// Then, compute the scale factors for all groups and strokes
// - If any child, group or stroke, cannot compute a scale factor,
// it will return true (to indicate a missing dimension)
for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup)
{
Group& grp = _vecGroups[iGroup];
const HGroup& hgrp = vecHGroups[iGroup];
fDimensionMissing = ( grp.calcScale(*this, han, hgrp)
|| fDimensionMissing);
if (Unit(grp.sxToHan()).isDefined())
{
sxToHan += hgrp.getBounds().getWidth() * grp.sxToHan();
nxToHan += hgrp.getBounds().getWidth();
}
else
fDimensionMissing = true;
if (Unit(grp.syToHan()).isDefined())
{
syToHan += hgrp.getBounds().getHeight() * grp.syToHan();
nyToHan += hgrp.getBounds().getHeight();
}
else
fDimensionMissing = true;
}
// At least one dimension must have profile, it is an error otherwise
if (nxToHan <= static_cast<UNIT>(0.0) && nyToHan <= static_cast<UNIT>(0.0))
{
Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Both dimensions lack profile");
Genome::recordTermination(NULL, STGT_VALIDATION, STGR_MEASUREMENT, "Both dimensions lack profile");
goto INVALID;
}
// Compute gene scale factors
if (nxToHan > static_cast<UNIT>(0.0))
_sxToHan = sxToHan / nxToHan;
else
{
fDimensionMissing = true;
_sxToHan.setUndefined();
}
if (nyToHan > static_cast<UNIT>(0.0))
_syToHan = syToHan / nyToHan;
else
{
fDimensionMissing = true;
_syToHan.setUndefined();
}
// Promote scale factors, as needed, to compensate for those they could not calculate
if (fDimensionMissing)
{
ASSERT(_sxToHan.isDefined() || _syToHan.isDefined());
if (!_sxToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Gene is missing sxToHan dimension, taking syToHan(%f)", static_cast<UNIT>(_syToHan)));
_sxToHan = _syToHan;
}
else if (!_syToHan.isDefined())
{
TDATA(VALIDATION,L3,(LLTRACE, "Gene is missing syToHan dimension, taking sxToHan(%f)", static_cast<UNIT>(_sxToHan)));
_syToHan = _sxToHan;
}
TDATA(VALIDATION,L3,(LLTRACE, "Gene promoting sx/sy(%f,%f) to groups", static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan)));
for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup)
{
_vecGroups[iGroup].promoteScale(*this, vecHGroups[iGroup], _sxToHan, _syToHan);
}
}
ASSERT(_sxToHan.isDefined() && _syToHan.isDefined());
_sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan));
// Finally, compute the translation offsets for all elements (groups, strokes, and the gene)
for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup)
{
Group& grp = _vecGroups[iGroup];
const HGroup& hgrp = vecHGroups[iGroup];
grp.calcOffsets(*this, han, hgrp);
dxToHan += hgrp.getLength() * grp.dxParentToHan();
dyToHan += hgrp.getLength() * grp.dyParentToHan();
}
_dxToHan = dxToHan / han.getLength();
_dyToHan = dyToHan / han.getLength();
markValid(GI_DIMENSIONS);
INVALID:
;
}
/*
* Function: ensureOverlaps
*
*/
void
Gene::ensureOverlaps()
{
ENTER(VALIDATION,ensureOverlaps);
Overlaps overlaps(_vecAcids, _vecPoints, _vecStrokes);
_setOverlaps = overlaps.getOverlaps();
TFLOW(VALIDATION,L3,(LLTRACE, "%ld overlapping strokes", _setOverlaps.size()));
TRACEDOIF(VALIDATION,DATA,L3,traceStrokeOverlaps());
markValid(GI_OVERLAPS);
}
| 31.44141 | 149 | 0.657989 | biologic |
5d52859886d9614157f040a1de9da8c17af91420 | 10,425 | hpp | C++ | third_party/omr/fvtest/compilertest/compile/Method.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/fvtest/compilertest/compile/Method.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/fvtest/compilertest/compile/Method.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef TEST_METHOD_INCL
#define TEST_METHOD_INCL
#ifndef TR_RESOLVEDMETHOD_COMPOSED
#define TR_RESOLVEDMETHOD_COMPOSED
#define PUT_TEST_RESOLVEDMETHOD_INTO_TR
#endif // TR_RESOLVEDMETHOD_COMPOSED
#include <string.h>
// Choose the OMR base version directly. This is only temporary
// while the Method class is being made extensible.
//
#include "compiler/compile/Method.hpp"
#include "compile/ResolvedMethod.hpp"
namespace TR { class IlGeneratorMethodDetails; }
namespace TR { class IlType; }
namespace TR { class TypeDictionary; }
namespace TR { class IlInjector; }
namespace TR { class MethodBuilder; }
namespace TR { class FrontEnd; }
// quick and dirty implementation to get up and running
// needs major overhaul
namespace TestCompiler
{
class Method : public TR::Method
{
public:
TR_ALLOC(TR_Memory::Method);
Method() : TR::Method(TR::Method::Test) {}
// FIXME: need to provide real code for this group
virtual uint16_t classNameLength() { return strlen(classNameChars()); }
virtual uint16_t nameLength() { return strlen(nameChars()); }
virtual uint16_t signatureLength() { return strlen(signatureChars()); }
virtual char * nameChars() { return "Method"; }
virtual char * classNameChars() { return ""; }
virtual char * signatureChars() { return "()V"; }
virtual bool isConstructor() { return false; }
virtual bool isFinalInObject() { return false; }
};
class ResolvedMethodBase : public TR_ResolvedMethod
{
virtual uint16_t nameLength() { return signatureLength(); }
virtual uint16_t classNameLength() { return signatureLength(); }
virtual uint16_t signatureLength() { return strlen(signatureChars()); }
// This group of functions only make sense for Java - we ought to provide answers from that definition
virtual bool isConstructor() { return false; }
virtual bool isNonEmptyObjectConstructor() { return false; }
virtual bool isFinalInObject() { return false; }
virtual bool isStatic() { return true; }
virtual bool isAbstract() { return false; }
virtual bool isCompilable(TR_Memory *) { return true; }
virtual bool isNative() { return false; }
virtual bool isSynchronized() { return false; }
virtual bool isPrivate() { return false; }
virtual bool isProtected() { return false; }
virtual bool isPublic() { return true; }
virtual bool isFinal() { return false; }
virtual bool isStrictFP() { return false; }
virtual bool isSubjectToPhaseChange(TR::Compilation *comp) { return false; }
virtual bool hasBackwardBranches() { return false; }
virtual bool isNewInstanceImplThunk() { return false; }
virtual bool isJNINative() { return false; }
virtual bool isJITInternalNative() { return false; }
uint32_t numberOfExceptionHandlers() { return 0; }
virtual bool isSameMethod(TR_ResolvedMethod *other)
{
return getPersistentIdentifier() == other->getPersistentIdentifier();
}
};
class ResolvedMethod : public ResolvedMethodBase, public Method
{
public:
ResolvedMethod(TR_OpaqueMethodBlock *method);
ResolvedMethod(TR::MethodBuilder *methodBuilder);
ResolvedMethod(const char * fileName,
const char * lineNumber,
char * name,
int32_t numParms,
TR::IlType ** parmTypes,
TR::IlType * returnType,
void * entryPoint,
TR::IlInjector * ilInjector)
: _fileName(fileName),
_lineNumber(lineNumber),
_name(name),
_signature(0),
_numParms(numParms),
_parmTypes(parmTypes),
_returnType(returnType),
_entryPoint(entryPoint),
_ilInjector(ilInjector)
{
computeSignatureChars();
}
virtual TR::Method * convertToMethod() { return this; }
virtual const char * signature(TR_Memory *, TR_AllocationKind);
char * localName (uint32_t slot, uint32_t bcIndex, int32_t &nameLength, TR_Memory *trMemory);
virtual char * classNameChars() { return (char *)_fileName; }
virtual char * nameChars() { return _name; }
virtual char * signatureChars() { return _signatureChars; }
virtual uint16_t signatureLength() { return strlen(signatureChars()); }
virtual void * resolvedMethodAddress() { return (void *)_ilInjector; }
virtual uint16_t numberOfParameterSlots() { return _numParms; }
virtual TR::DataType parmType(uint32_t slot);
virtual uint16_t numberOfTemps() { return 0; }
virtual void * startAddressForJittedMethod() { return (getEntryPoint()); }
virtual void * startAddressForInterpreterOfJittedMethod() { return 0; }
virtual uint32_t maxBytecodeIndex() { return 0; }
virtual uint8_t * code() { return NULL; }
virtual TR_OpaqueMethodBlock* getPersistentIdentifier() { return (TR_OpaqueMethodBlock *) _ilInjector; }
virtual bool isInterpreted() { return startAddressForJittedMethod() == 0; }
const char * getLineNumber() { return _lineNumber;}
char * getSignature() { return _signature;}
TR::DataType returnType();
TR::IlType * returnIlType() { return _returnType; }
int32_t getNumArgs() { return _numParms;}
void setEntryPoint(void *ep) { _entryPoint = ep; }
void * getEntryPoint() { return _entryPoint; }
void computeSignatureCharsPrimitive();
void computeSignatureChars();
virtual void makeParameterList(TR::ResolvedMethodSymbol *);
TR::IlInjector *getInjector(TR::IlGeneratorMethodDetails * details,
TR::ResolvedMethodSymbol *methodSymbol,
TR::FrontEnd *fe,
TR::SymbolReferenceTable *symRefTab);
protected:
const char *_fileName;
const char *_lineNumber;
char *_name;
char *_signature;
char _signatureChars[64];
int32_t _numParms;
TR::IlType ** _parmTypes;
TR::IlType * _returnType;
void * _entryPoint;
TR::IlInjector * _ilInjector;
};
} // namespace TestCompiler
#if defined(PUT_TEST_RESOLVEDMETHOD_INTO_TR)
namespace TR
{
class ResolvedMethod : public TestCompiler::ResolvedMethod
{
public:
ResolvedMethod(TR_OpaqueMethodBlock *method)
: TestCompiler::ResolvedMethod(method)
{ }
ResolvedMethod(char * fileName,
char * lineNumber,
char * name,
int32_t numArgs,
TR::IlType ** parmTypes,
TR::IlType * returnType,
void * entryPoint,
TR::IlInjector * ilInjector)
: TestCompiler::ResolvedMethod(fileName, lineNumber, name, numArgs,
parmTypes, returnType,
entryPoint, ilInjector)
{ }
ResolvedMethod(TR::MethodBuilder *methodBuilder)
: TestCompiler::ResolvedMethod(methodBuilder)
{ }
};
} // namespace TR
#endif // !defined(PUT_TEST_RESOLVEDMETHOD_INTO_TR)
#endif // !defined(TEST_METHOD_INCL)
| 46.333333 | 135 | 0.523933 | xiacijie |
5d5497b7377544085e2c915e62df50b37fa26c35 | 43,555 | cpp | C++ | kernel_lite/util_posix/src/ActsUtilWideCheckApiTest.cpp | openharmony-sig-ci/xts_acts | 836aa530bc89417503cc6d1158d2458bfd43866b | [
"Apache-2.0"
] | null | null | null | kernel_lite/util_posix/src/ActsUtilWideCheckApiTest.cpp | openharmony-sig-ci/xts_acts | 836aa530bc89417503cc6d1158d2458bfd43866b | [
"Apache-2.0"
] | null | null | null | kernel_lite/util_posix/src/ActsUtilWideCheckApiTest.cpp | openharmony-sig-ci/xts_acts | 836aa530bc89417503cc6d1158d2458bfd43866b | [
"Apache-2.0"
] | 1 | 2021-09-13T12:04:33.000Z | 2021-09-13T12:04:33.000Z | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
*/
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <wctype.h>
#include "gtest/gtest.h"
#include "log.h"
#include "utils.h"
using namespace testing::ext;
class ActsUtilWideCheckApiTest : public testing::Test {
public:
locale_t g_auwcaLocale;
protected:
// SetUpTestCase: Testsuit setup, run before 1st testcase
static void SetUpTestCase(void)
{
}
// TearDownTestCase: Testsuit teardown, run after last testcase
static void TearDownTestCase(void)
{
}
// Testcase setup
virtual void SetUp()
{
g_auwcaLocale = newlocale(LC_ALL_MASK, "", (locale_t)0);
}
// Testcase teardown
virtual void TearDown()
{
freelocale(g_auwcaLocale);
}
};
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_0100
* @tc.name test iswalnum api with num
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnum0100, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '2';
returnVal = iswalnum(paraVal);
LOGD(" iswalnum returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_0200
* @tc.name test iswalnum api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnum0200, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'Z';
returnVal = iswalnum(paraVal);
LOGD(" iswalnum returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_0300
* @tc.name test iswalnum api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnum0300, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'z';
returnVal = iswalnum(paraVal);
LOGD(" iswalnum returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_0400
* @tc.name test iswalnum api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnum0400, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswalnum(paraVal);
LOGD(" iswalnum returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalnum returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_0500
* @tc.name test iswalnum api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnum0500, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswalnum(paraVal);
LOGD(" iswalnum returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalnum returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_L_0600
* @tc.name test iswalnum_l api with num
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnumL0600, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '2';
returnVal = iswalnum_l(paraVal, g_auwcaLocale);
LOGD(" iswalnum_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_L_0700
* @tc.name test iswalnum_l api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnumL0700, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'Z';
returnVal = iswalnum_l(paraVal, g_auwcaLocale);
LOGD(" iswalnum_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_L_0800
* @tc.name test iswalnum_l api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnumL0800, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'z';
returnVal = iswalnum_l(paraVal, g_auwcaLocale);
LOGD(" iswalnum_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalnum_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_L_0900
* @tc.name test iswalnum_l api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnumL0900, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswalnum_l(paraVal, g_auwcaLocale);
LOGD(" iswalnum_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalnum_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALNUM_L_1000
* @tc.name test iswalnum_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalnumL1000, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswalnum_l(paraVal, g_auwcaLocale);
LOGD(" iswalnum_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalnum_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_1100
* @tc.name test iswalpha api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalpha1100, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'z';
returnVal = iswalpha(paraVal);
LOGD(" iswalpha returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalpha returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_1200
* @tc.name test iswalpha api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalpha1200, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'Z';
returnVal = iswalpha(paraVal);
LOGD(" iswalpha returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalpha returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_1300
* @tc.name test iswalpha api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalpha1300, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswalpha(paraVal);
LOGD(" iswalpha returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalpha returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_1400
* @tc.name test iswalpha api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalpha1400, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswalpha(paraVal);
LOGD(" iswalpha returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalpha returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_L_1500
* @tc.name test iswalpha_l api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalphaL1500, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'z';
returnVal = iswalpha_l(paraVal, g_auwcaLocale);
LOGD(" iswalpha_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalpha_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_L_1600
* @tc.name test iswalpha_l api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalphaL1600, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'Z';
returnVal = iswalpha_l(paraVal, g_auwcaLocale);
LOGD(" iswalpha_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswalpha_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_L_1700
* @tc.name test iswalpha_l api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalphaL1700, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswalpha_l(paraVal, g_auwcaLocale);
LOGD(" iswalpha_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalpha_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWALPHA_L_1800
* @tc.name test iswalpha_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswalphaL1800, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswalpha_l(paraVal, g_auwcaLocale);
LOGD(" iswalpha_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswalpha_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWBLANK_1900
* @tc.name test iswblank api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswblank1900, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswblank(paraVal);
LOGD(" iswblank returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswblank returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWBLANK_2000
* @tc.name test iswblank api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswblank2000, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'A';
returnVal = iswblank(paraVal);
LOGD(" iswblank returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswblank returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWBLANK_L_2100
* @tc.name test iswblank_l api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswblankL2100, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = ' ';
returnVal = iswblank_l(paraVal, g_auwcaLocale);
LOGD(" iswblank_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswblank_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWBLANK_L_2200
* @tc.name test iswblank_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswblankL2200, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'A';
returnVal = iswblank_l(paraVal, g_auwcaLocale);
LOGD(" iswblank_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswblank_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCNTRL_2300
* @tc.name test iswcntrl api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswcntrl2300, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswcntrl(paraVal);
LOGD(" iswcntrl returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswcntrl returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCNTRL_2400
* @tc.name test iswcntrl api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswcntrl2400, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'A';
returnVal = iswcntrl(paraVal);
LOGD(" iswcntrl returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswcntrl returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCNTRL_L_2500
* @tc.name test iswcntrl_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswcntrlL2500, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = '\n';
returnVal = iswcntrl_l(paraVal, g_auwcaLocale);
LOGD(" iswcntrl_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswcntrl_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCNTRL_L_2600
* @tc.name test iswcntrl_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswcntrlL2600, Function | MediumTest | Level1) {
wint_t paraVal;
int returnVal;
paraVal = 'A';
returnVal = iswcntrl_l(paraVal, g_auwcaLocale);
LOGD(" iswcntrl_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswcntrl_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCTYPE_2700
* @tc.name test iswctype api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswctype2700, Function | MediumTest | Level1) {
wint_t wideChar;
wctype_t paraDesc;
int returnVal;
wideChar = 'A';
paraDesc = wctype("alnum");
returnVal = iswctype(wideChar, paraDesc);
LOGD(" iswctype returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswctype returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCTYPE_2800
* @tc.name test iswctype api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswctype2800, Function | MediumTest | Level1) {
wint_t wideChar;
wctype_t paraDesc;
int returnVal;
wideChar = '3';
paraDesc = wctype("alnum");
returnVal = iswctype(wideChar, paraDesc);
LOGD(" iswctype returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswctype returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCTYPE_L_2900
* @tc.name test iswctype_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswctypeL2900, Function | MediumTest | Level1) {
wint_t wideChar;
wctype_t paraDesc;
int returnVal;
wideChar = 'A';
paraDesc = wctype("alnum");
returnVal = iswctype_l(wideChar, paraDesc, g_auwcaLocale);
LOGD(" iswctype_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswctype_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWCTYPE_L_3000
* @tc.name test iswctype_l api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswctypeL3000, Function | MediumTest | Level1) {
wint_t wideChar;
wctype_t paraDesc;
int returnVal;
wideChar = '3';
paraDesc = wctype("alnum");
returnVal = iswctype_l(wideChar, paraDesc, g_auwcaLocale);
LOGD(" iswctype_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswctype_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWDIGIT_3100
* @tc.name test iswdigit api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswdigit3100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '3';
returnVal = iswdigit(wideChar);
LOGD(" iswdigit returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswdigit returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWDIGIT_3200
* @tc.name test iswdigit api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswdigit3200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswdigit(wideChar);
LOGD(" iswdigit returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswdigit returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWDIGIT_L_3300
* @tc.name test iswdigit_l api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswdigitL3300, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '3';
returnVal = iswdigit_l(wideChar, g_auwcaLocale);
LOGD(" iswdigit_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswdigit_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWDIGIT_L_3400
* @tc.name test iswdigit api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswdigitL3400, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswdigit_l(wideChar, g_auwcaLocale);
LOGD(" iswdigit_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswdigit_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWGRAPH_3500
* @tc.name test iswgraph api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswgraph3500, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswgraph(wideChar);
LOGD(" iswgraph returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswgraph returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWGRAPH_3600
* @tc.name test iswgraph api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswgraph3600, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswgraph(wideChar);
LOGD(" iswgraph returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswgraph returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWGRAPH_L_3700
* @tc.name test iswgraph_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswgraphL3700, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswgraph_l(wideChar, g_auwcaLocale);
LOGD(" iswgraph_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswgraph_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWGRAPH_L_3800
* @tc.name test iswgraph_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswgraphL3800, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswgraph_l(wideChar, g_auwcaLocale);
LOGD(" iswgraph_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswgraph_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_3900
* @tc.name test iswlower api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlower3900, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswlower(wideChar);
LOGD(" iswlower c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswlower c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_4000
* @tc.name test islower api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlower4000, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswlower(wideChar);
LOGD(" iswlower c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswlower c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_4100
* @tc.name test islower api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlower4100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '5';
returnVal = iswlower(wideChar);
LOGD(" iswlower c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswlower c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_L_4200
* @tc.name test iswlower_l api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlowerL4200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswlower_l(wideChar, g_auwcaLocale);
LOGD(" iswlower_l c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswlower_l c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_L_4300
* @tc.name test iswlower_l api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlowerL4300, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswlower_l(wideChar, g_auwcaLocale);
LOGD(" iswlower_l c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswlower_l c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWLOWER_L_4400
* @tc.name test iswlower_l api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswlowerL4400, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '5';
returnVal = iswlower_l(wideChar, g_auwcaLocale);
LOGD(" iswlower_l c:='%c', returnVal:='%c'\n", wideChar, returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswlower_l c:='" << wideChar << "', returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPRINT_4500
* @tc.name test iswprint api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswprint4500, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswprint(wideChar);
LOGD(" iswprint returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswprint returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPRINT_4600
* @tc.name test iswprint api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswprint4600, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswprint(wideChar);
LOGD(" iswprint returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswprint returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPRINT_L_4700
* @tc.name test iswprint_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswprintL4700, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswprint_l(wideChar, g_auwcaLocale);
LOGD(" iswprint_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswprint_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPRINT_L_4800
* @tc.name test iswprint_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswprintL4800, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswprint_l(wideChar, g_auwcaLocale);
LOGD(" iswprint_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswprint_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_4900
* @tc.name test iswpunct api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunct4900, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = ' ';
returnVal = iswpunct(wideChar);
LOGD(" iswpunct returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_5000
* @tc.name test iswpunct api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunct5000, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswpunct(wideChar);
LOGD(" iswpunct returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_5100
* @tc.name test iswpunct api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunct5100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '3';
returnVal = iswpunct(wideChar);
LOGD(" iswpunct returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_5200
* @tc.name test iswpunct api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunct5200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswpunct(wideChar);
LOGD(" iswpunct returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_L_5300
* @tc.name test iswpunct_l api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunctL5300, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = ' ';
returnVal = iswpunct_l(wideChar, g_auwcaLocale);
LOGD(" iswpunct_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_L_5400
* @tc.name test iswpunct_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunctL5400, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswpunct_l(wideChar, g_auwcaLocale);
LOGD(" iswpunct_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_L_5500
* @tc.name test iswpunct_l api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunctL5500, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '3';
returnVal = iswpunct_l(wideChar, g_auwcaLocale);
LOGD(" iswpunct_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWPUNCT_L_5600
* @tc.name test iswpunct_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswpunctL5600, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswpunct_l(wideChar, g_auwcaLocale);
LOGD(" iswpunct_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswpunct_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_5700
* @tc.name test iswspace api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace5700, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_5800
* @tc.name test iswspace api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace5800, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = ' ';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_5900
* @tc.name test iswspace api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace5900, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_6000
* @tc.name test iswspace api with CR
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace6000, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\r';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_6100
* @tc.name test iswspace api with form-feed
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace6100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\f';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_6200
* @tc.name test iswspace api with horizontal tab
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace6200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\t';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_6300
* @tc.name test iswspace api with vertical tab
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspace6300, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\v';
returnVal = iswspace(wideChar);
LOGD(" iswspace returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6400
* @tc.name test iswspace_l api with alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6400, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6500
* @tc.name test iswspace_l api with space
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6500, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = ' ';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6600
* @tc.name test iswspace_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6600, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6700
* @tc.name test iswspace_l api with CR
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6700, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\r';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6800
* @tc.name test iswspace_l api with form-feed
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6800, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\f';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_6900
* @tc.name test iswspace_l api with horizontal tab
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL6900, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\t';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWSPACE_L_7000
* @tc.name test iswspace_l api with vertical tab
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswspaceL7000, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\v';
returnVal = iswspace_l(wideChar, g_auwcaLocale);
LOGD(" iswspace_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswspace_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_7100
* @tc.name test iswupper api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupper7100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswupper(wideChar);
LOGD(" iswupper returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswupper returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_7200
* @tc.name test iswupper api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupper7200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswupper(wideChar);
LOGD(" iswupper returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_7300
* @tc.name test iswupper api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupper7300, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '5';
returnVal = iswupper(wideChar);
LOGD(" iswupper returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_7400
* @tc.name test iswupper api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupper7400, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswupper(wideChar);
LOGD(" iswupper returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_L_7500
* @tc.name test iswupper_l api with upper alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupperL7500, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'A';
returnVal = iswupper_l(wideChar, g_auwcaLocale);
LOGD(" iswupper_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswupper_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_L_7600
* @tc.name test iswupper_l api with lower alpha
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupperL7600, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'a';
returnVal = iswupper_l(wideChar, g_auwcaLocale);
LOGD(" iswupper_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_L_7700
* @tc.name test iswupper_l api with digit
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupperL7700, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '5';
returnVal = iswupper_l(wideChar, g_auwcaLocale);
LOGD(" iswupper_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWUPPER_L_7800
* @tc.name test iswupper_l api with LF
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswupperL7800, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = '\n';
returnVal = iswupper_l(wideChar, g_auwcaLocale);
LOGD(" iswupper_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswupper_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWXDIGIT_7900
* @tc.name test iswxdigit api with xdigit F
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswxdigit7900, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'F';
returnVal = iswxdigit(wideChar);
LOGD(" iswxdigit returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswxdigit returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWXDIGIT_8000
* @tc.name test iswxdigit api with alpha G
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswxdigit8000, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'G';
returnVal = iswxdigit(wideChar);
LOGD(" iswxdigit returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswxdigit returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWXDIGIT_L_8100
* @tc.name test iswxdigit_l api with xdigit F
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswxdigitL8100, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'F';
returnVal = iswxdigit_l(wideChar, g_auwcaLocale);
LOGD(" iswxdigit_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(returnVal != 0) << "ErrInfo: iswxdigit_l returnVal:='" << returnVal << "'";
}
/**
* @tc.number SUB_KERNEL_UTIL_WIDECHECK_ISWXDIGIT_L_8200
* @tc.name test iswxdigit_l api with alpha G
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ActsUtilWideCheckApiTest, testIswxdigitL8200, Function | MediumTest | Level1) {
wint_t wideChar;
int returnVal;
wideChar = 'G';
returnVal = iswxdigit_l(wideChar, g_auwcaLocale);
LOGD(" iswxdigit_l returnVal:='%d'\n", returnVal);
ASSERT_TRUE(0 == returnVal) << "ErrInfo: iswxdigit_l returnVal:='" << returnVal << "'";
} | 33.842269 | 118 | 0.642016 | openharmony-sig-ci |
5d558bb08d4ef14678f8a1be773aa5f48a93dd83 | 16,633 | cpp | C++ | tests/CppUTest/TestUTestStringMacro.cpp | aunitt/cpputest | c981ed449df76e8e769286663c1caab069da324e | [
"BSD-3-Clause"
] | 2 | 2016-02-04T16:34:01.000Z | 2021-05-27T17:48:15.000Z | tests/CppUTest/TestUTestStringMacro.cpp | aunitt/cpputest | c981ed449df76e8e769286663c1caab069da324e | [
"BSD-3-Clause"
] | null | null | null | tests/CppUTest/TestUTestStringMacro.cpp | aunitt/cpputest | c981ed449df76e8e769286663c1caab069da324e | [
"BSD-3-Clause"
] | 1 | 2020-01-22T19:46:10.000Z | 2020-01-22T19:46:10.000Z | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__)
TEST_GROUP(UnitTestStringMacros)
{
TestTestingFixture fixture;
};
static void _STRCMP_EQUALWithActualIsNULLTestMethod()
{
STRCMP_EQUAL("ok", NULLPTR);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRCMP_EQUALWithExpectedIsNULLTestMethod()
{
STRCMP_EQUAL(NULLPTR, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_CONTAINSWithActualIsNULLTestMethod()
{
STRCMP_CONTAINS("ok", NULLPTR);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_CONTAINSWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>");
}
static void _STRCMP_CONTAINSWithExpectedIsNULLTestMethod()
{
STRCMP_CONTAINS(NULLPTR, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_CONTAINSWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>");
}
static void _STRNCMP_EQUALWithActualIsNULLTestMethod()
{
STRNCMP_EQUAL("ok", NULLPTR, 2);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRNCMP_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRNCMP_EQUALWithExpectedIsNULLTestMethod()
{
STRNCMP_EQUAL(NULLPTR, "ok", 2);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRNCMP_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod()
{
STRCMP_NOCASE_EQUAL("ok", NULLPTR);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod()
{
STRCMP_NOCASE_EQUAL(NULLPTR, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithUnequalInputTestMethod()
{
STRCMP_NOCASE_EQUAL("no", "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndUnequalInput)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithUnequalInputTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <ok>");
}
static void _STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod()
{
STRCMP_NOCASE_CONTAINS("ok", NULLPTR);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>");
}
static void _STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod()
{
STRCMP_NOCASE_CONTAINS(NULLPTR, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>");
}
static void _failingTestMethodWithSTRCMP_EQUAL()
{
STRCMP_EQUAL("hello", "hell");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
}
TEST(UnitTestStringMacros, STRCMP_EQUALBehavesAsProperMacro)
{
if (false) STRCMP_EQUAL("1", "2");
else STRCMP_EQUAL("1", "1");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUALWorksInAnIgnoredTest)
{
STRCMP_EQUAL("Hello", "World"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_EQUAL_TEXT()
{
STRCMP_EQUAL_TEXT("hello", "hell", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed");
else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRNCMP_EQUAL()
{
STRNCMP_EQUAL("hello", "hallo", 5);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>");
}
TEST(UnitTestStringMacros, STRNCMP_EQUALBehavesAsProperMacro)
{
if (false) STRNCMP_EQUAL("1", "2", 1);
else STRNCMP_EQUAL("1", "1", 1);
}
IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUALWorksInAnIgnoredTest)
{
STRNCMP_EQUAL("Hello", "World", 3); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRNCMP_EQUAL_TEXT()
{
STRNCMP_EQUAL_TEXT("hello", "hallo", 5, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed");
else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed");
}
IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL()
{
STRCMP_NOCASE_EQUAL("hello", "Hell");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hell>");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_EQUAL("1", "2");
else STRCMP_NOCASE_EQUAL("1", "1");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALWorksInAnIgnoredTest)
{
STRCMP_NOCASE_EQUAL("Hello", "World"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT()
{
STRCMP_NOCASE_EQUAL_TEXT("hello", "hell", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed");
else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_CONTAINS()
{
STRCMP_CONTAINS("hello", "world");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
}
TEST(UnitTestStringMacros, STRCMP_CONTAINSBehavesAsProperMacro)
{
if (false) STRCMP_CONTAINS("1", "2");
else STRCMP_CONTAINS("1", "1");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINSWorksInAnIgnoredTest)
{
STRCMP_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_CONTAINS_TEXT()
{
STRCMP_CONTAINS_TEXT("hello", "world", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed");
else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTWorksInAnIgnoredTest)
{
STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS()
{
STRCMP_NOCASE_CONTAINS("hello", "WORLD");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINSBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_CONTAINS("never", "executed");
else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINSWorksInAnIgnoredTest)
{
STRCMP_NOCASE_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT()
{
STRCMP_NOCASE_CONTAINS_TEXT("hello", "WORLD", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINS_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed");
else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed");
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINS_TEXTWorksInAnIgnoredTest)
{
STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, NFirstCharsComparison)
{
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 0);
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 1);
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 6);
STRNCMP_EQUAL("Hello World!", "Hello", 5);
}
static void _compareNFirstCharsWithUpperAndLowercase()
{
STRNCMP_EQUAL("hello world!", "HELLO WORLD!", 12);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithUpperAndLowercase)
{
fixture.runTestWithMethod(_compareNFirstCharsWithUpperAndLowercase);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello world!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <HELLO WORLD!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0");
}
static void _compareNFirstCharsWithDifferenceInTheMiddle()
{
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 12);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithDifferenceInTheMiddle)
{
fixture.runTestWithMethod(_compareNFirstCharsWithDifferenceInTheMiddle);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Hello World!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hello Peter!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 6");
}
static void _compareNFirstCharsWithEmptyString()
{
STRNCMP_EQUAL("", "Not empty string", 5);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithEmptyString)
{
fixture.runTestWithMethod(_compareNFirstCharsWithEmptyString);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0");
}
static void _compareNFirstCharsWithLastCharDifferent()
{
STRNCMP_EQUAL("Not empty string?", "Not empty string!", 17);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithLastCharDifferent)
{
fixture.runTestWithMethod(_compareNFirstCharsWithLastCharDifferent);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Not empty string?>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 16");
}
| 35.464819 | 118 | 0.788252 | aunitt |
5d580c4fb88cef7ca3bafeeb075058f2bac6d586 | 7,210 | cxx | C++ | graphics/slcd/slcd_mapping.cxx | codebje/incubator-nuttx-apps | d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff | [
"Apache-2.0"
] | 132 | 2019-12-17T23:45:42.000Z | 2022-03-30T11:58:30.000Z | graphics/slcd/slcd_mapping.cxx | codebje/incubator-nuttx-apps | d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff | [
"Apache-2.0"
] | 443 | 2020-01-01T03:06:24.000Z | 2022-03-31T08:57:35.000Z | graphics/slcd/slcd_mapping.cxx | codebje/incubator-nuttx-apps | d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff | [
"Apache-2.0"
] | 232 | 2019-12-21T10:18:12.000Z | 2022-03-30T07:42:13.000Z | /////////////////////////////////////////////////////////////////////////////
// apps/graphics/slcd/slcd_mapping.cxx
//
// Copyright (C) 2019 Gregory Nutt. All rights reserved.
// Author: Gregory Nutt <gnutt@nuttx.org>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// 3. Neither the name NuttX 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.
//
/////////////////////////////////////////////////////////////////////////////
// Segment
//
// 11111111
// 2 3
// 2 3
// 2 3
// 44444444
// 5 6
// 5 6
// 5 6
// 77777777
/////////////////////////////////////////////////////////////////////////////
// Included Files
/////////////////////////////////////////////////////////////////////////////
#include <cstdint>
#include "graphics/slcd.hxx"
#include "slcd.hxx"
/////////////////////////////////////////////////////////////////////////////
// Public Data
/////////////////////////////////////////////////////////////////////////////
namespace SLcd
{
const uint8_t GSLcdDigits[10] =
{
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_5 | // 0
SEGMENT_6 | SEGMENT_7,
SEGMENT_3 | SEGMENT_6, // 1
SEGMENT_1 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // 2
SEGMENT_7,
SEGMENT_1 | SEGMENT_3 | SEGMENT_4 | SEGMENT_6 | // 3
SEGMENT_7,
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_6, // 4
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_6 | // 5
SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | // 6
SEGMENT_6 | SEGMENT_7, // 7
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_6,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // 8
SEGMENT_5 | SEGMENT_6 | SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // 9
SEGMENT_6 | SEGMENT_7
};
const uint8_t GSLcdLowerCase[26] =
{
SEGMENT_1 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // a
SEGMENT_6 | SEGMENT_7,
SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | SEGMENT_6 | // b
SEGMENT_7,
SEGMENT_4 | SEGMENT_5 | SEGMENT_7, // c
SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | SEGMENT_6 | // d
SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // e
SEGMENT_5 | SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5, // f
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // g
SEGMENT_6 | SEGMENT_7,
SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | SEGMENT_6, // h
SEGMENT_5, // i
SEGMENT_6 | SEGMENT_7, // j
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | // k
SEGMENT_6,
SEGMENT_3 | SEGMENT_6, // l
SEGMENT_5 | SEGMENT_6, // m
SEGMENT_4 | SEGMENT_5 | SEGMENT_6, // n
SEGMENT_4 | SEGMENT_5 | SEGMENT_6 | SEGMENT_7, // o
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // p
SEGMENT_5,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // q
SEGMENT_6,
SEGMENT_4 | SEGMENT_5, // r
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_6 | // s
SEGMENT_7,
SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | SEGMENT_7, // t
SEGMENT_5 | SEGMENT_6 | SEGMENT_7, // u
SEGMENT_5 | SEGMENT_6 | SEGMENT_7, // v
SEGMENT_5 | SEGMENT_6, // w
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // x
SEGMENT_6,
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_6 | // y
SEGMENT_7,
SEGMENT_1 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // z
SEGMENT_7
};
const uint8_t GSLcdUpperCase[26] =
{
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // A
SEGMENT_5 | SEGMENT_6,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // B
SEGMENT_5 | SEGMENT_6 | SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_5 | SEGMENT_7, // C
SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | SEGMENT_6 | // D
SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | // E
SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5, // F
SEGMENT_1 | SEGMENT_2 | SEGMENT_5 | SEGMENT_6 | // G
SEGMENT_7,
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // H
SEGMENT_6,
SEGMENT_3 | SEGMENT_6, // I
SEGMENT_3 | SEGMENT_5 | SEGMENT_6 | SEGMENT_7, // J
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | // K
SEGMENT_6,
SEGMENT_2 | SEGMENT_5 | SEGMENT_7, // L
SEGMENT_1 | SEGMENT_5 | SEGMENT_6, // M
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_5 | // N
SEGMENT_6,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_5 | // O
SEGMENT_6 | SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // P
SEGMENT_5,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | // Q
SEGMENT_7,
SEGMENT_1 | SEGMENT_2 | SEGMENT_3 | SEGMENT_5, // R
SEGMENT_1 | SEGMENT_2 | SEGMENT_4 | SEGMENT_6 | // S
SEGMENT_7,
SEGMENT_2 | SEGMENT_4 | SEGMENT_5 | SEGMENT_7, // T
SEGMENT_2 | SEGMENT_3 | SEGMENT_5 | SEGMENT_6 | // U
SEGMENT_7,
SEGMENT_2 | SEGMENT_3 | SEGMENT_5 | SEGMENT_6 | // V
SEGMENT_7,
SEGMENT_2 | SEGMENT_3 | SEGMENT_7, // W
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // X
SEGMENT_6,
SEGMENT_2 | SEGMENT_3 | SEGMENT_4 | SEGMENT_6 | // Y
SEGMENT_7,
SEGMENT_1 | SEGMENT_3 | SEGMENT_4 | SEGMENT_5 | // Z
SEGMENT_7
};
const struct SSLcdCharset SSLcdMisc[NMISC_MAPPINGS] =
{
{
.ch = ' ',
.segments = 0
},
{
.ch = '-',
.segments = SEGMENT_4
},
{
.ch = '_',
.segments = SEGMENT_7
},
{
.ch = '"',
.segments = SEGMENT_3 | SEGMENT_3
},
{
.ch = ',',
.segments = SEGMENT_5
}
};
}
| 36.598985 | 77 | 0.571429 | codebje |
5d5a41dc6bc39f314a5bf3a1f486abd4ab60070c | 5,867 | cpp | C++ | Source/WebCore/html/HTMLPlugInElement.cpp | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Source/WebCore/html/HTMLPlugInElement.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | Source/WebCore/html/HTMLPlugInElement.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /**
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2000 Stefan Schimanski (1Stein@gmx.de)
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "HTMLPlugInElement.h"
#include "Attribute.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "CSSPropertyNames.h"
#include "Document.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "HTMLNames.h"
#include "Page.h"
#include "RenderEmbeddedObject.h"
#include "RenderWidget.h"
#include "ScriptController.h"
#include "Settings.h"
#include "Widget.h"
#if ENABLE(NETSCAPE_PLUGIN_API)
#include "npruntime_impl.h"
#endif
namespace WebCore {
using namespace HTMLNames;
HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document* doc)
: HTMLFrameOwnerElement(tagName, doc)
, m_inBeforeLoadEventHandler(false)
#if ENABLE(NETSCAPE_PLUGIN_API)
, m_NPObject(0)
#endif
, m_isCapturingMouseEvents(false)
{
}
HTMLPlugInElement::~HTMLPlugInElement()
{
ASSERT(!m_instance); // cleared in detach()
#if ENABLE(NETSCAPE_PLUGIN_API)
if (m_NPObject) {
_NPN_ReleaseObject(m_NPObject);
m_NPObject = 0;
}
#endif
}
void HTMLPlugInElement::detach()
{
m_instance.clear();
if (m_isCapturingMouseEvents) {
if (Frame* frame = document()->frame())
frame->eventHandler()->setCapturingMouseEventsNode(0);
m_isCapturingMouseEvents = false;
}
HTMLFrameOwnerElement::detach();
}
PassScriptInstance HTMLPlugInElement::getInstance() const
{
Frame* frame = document()->frame();
if (!frame)
return 0;
// If the host dynamically turns off JavaScript (or Java) we will still return
// the cached allocated Bindings::Instance. Not supporting this edge-case is OK.
if (m_instance)
return m_instance;
if (Widget* widget = pluginWidget())
m_instance = frame->script()->createScriptInstanceForWidget(widget);
return m_instance;
}
Widget* HTMLPlugInElement::pluginWidget() const
{
if (m_inBeforeLoadEventHandler) {
// The plug-in hasn't loaded yet, and it makes no sense to try to load if beforeload handler happened to touch the plug-in element.
// That would recursively call beforeload for the same element.
return 0;
}
RenderWidget* renderWidget = renderWidgetForJSBindings();
if (!renderWidget)
return 0;
return renderWidget->widget();
}
bool HTMLPlugInElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
{
if (attrName == widthAttr ||
attrName == heightAttr ||
attrName == vspaceAttr ||
attrName == hspaceAttr) {
result = eUniversal;
return false;
}
if (attrName == alignAttr) {
result = eReplaced; // Share with <img> since the alignment behavior is the same.
return false;
}
return HTMLFrameOwnerElement::mapToEntry(attrName, result);
}
void HTMLPlugInElement::parseMappedAttribute(Attribute* attr)
{
if (attr->name() == widthAttr)
addCSSLength(attr, CSSPropertyWidth, attr->value());
else if (attr->name() == heightAttr)
addCSSLength(attr, CSSPropertyHeight, attr->value());
else if (attr->name() == vspaceAttr) {
addCSSLength(attr, CSSPropertyMarginTop, attr->value());
addCSSLength(attr, CSSPropertyMarginBottom, attr->value());
} else if (attr->name() == hspaceAttr) {
addCSSLength(attr, CSSPropertyMarginLeft, attr->value());
addCSSLength(attr, CSSPropertyMarginRight, attr->value());
} else if (attr->name() == alignAttr)
addHTMLAlignment(attr);
else
HTMLFrameOwnerElement::parseMappedAttribute(attr);
}
void HTMLPlugInElement::defaultEventHandler(Event* event)
{
// Firefox seems to use a fake event listener to dispatch events to plug-in (tested with mouse events only).
// This is observable via different order of events - in Firefox, event listeners specified in HTML attributes fires first, then an event
// gets dispatched to plug-in, and only then other event listeners fire. Hopefully, this difference does not matter in practice.
// FIXME: Mouse down and scroll events are passed down to plug-in via custom code in EventHandler; these code paths should be united.
RenderObject* r = renderer();
if (r && r->isEmbeddedObject() && toRenderEmbeddedObject(r)->showsMissingPluginIndicator()) {
toRenderEmbeddedObject(r)->handleMissingPluginIndicatorEvent(event);
return;
}
if (!r || !r->isWidget())
return;
RefPtr<Widget> widget = toRenderWidget(r)->widget();
if (!widget)
return;
widget->handleEvent(event);
}
#if ENABLE(NETSCAPE_PLUGIN_API)
NPObject* HTMLPlugInElement::getNPObject()
{
ASSERT(document()->frame());
if (!m_NPObject)
m_NPObject = document()->frame()->script()->createScriptObjectForPluginElement(this);
return m_NPObject;
}
#endif /* ENABLE(NETSCAPE_PLUGIN_API) */
}
| 31.207447 | 141 | 0.694222 | VincentWei |
5d5c8d61bbc841b1940469f71093a39bc9c1dfc1 | 3,994 | cc | C++ | tce/src/base/bem/DestinationField.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 74 | 2015-10-22T15:34:10.000Z | 2022-03-25T07:57:23.000Z | tce/src/base/bem/DestinationField.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 79 | 2015-11-19T09:23:08.000Z | 2022-01-12T14:15:16.000Z | tce/src/base/bem/DestinationField.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 38 | 2015-11-17T10:12:23.000Z | 2022-03-25T07:57:24.000Z | /*
Copyright (c) 2002-2009 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
* @file DestinationField.cc
*
* Implementation of DestinationField class.
*
* @author Lasse Laasonen 2005 (lasse.laasonen-no.spam-tut.fi)
* @note rating: red
*/
#include <string>
#include "DestinationField.hh"
#include "MoveSlot.hh"
#include "Application.hh"
#include "ObjectState.hh"
using std::string;
const std::string DestinationField::OSNAME_DESTINATION_FIELD = "dest_field";
/**
* The constructor.
*
* Registers the destination field to the given move slot automatically.
*
* @param socketIDPos Position of the socket ID within the destination field.
* @param parent The parent move slot.
* @exception ObjectAlreadyExists If the parent move slot already has a
* destination field.
* @exception IllegalParameters If the given socket ID position is not the same
* with other destination fields.
*/
DestinationField::DestinationField(
BinaryEncoding::Position socketIDPos, MoveSlot& parent)
: SlotField(socketIDPos, parent) {
BinaryEncoding* bem = parent.parent();
for (int i = 0; i < bem->moveSlotCount(); i++) {
MoveSlot& slot = bem->moveSlot(i);
if (slot.hasDestinationField() &&
slot.destinationField().componentIDPosition() != socketIDPos) {
const string procName = "SourceField::SourceField";
throw IllegalParameters(__FILE__, __LINE__, procName);
} else {
break;
}
}
setParent(NULL);
parent.setDestinationField(*this);
setParent(&parent);
}
/**
* The constructor.
*
* Loads the state of the object from the given ObjectState tree.
*
* @param state The ObjectState tree.
* @param parent The parent move slot.
* @exception ObjectStateLoadingException If an error occurs while loading the
* state.
* @exception ObjectAlreadyExists If the parent move slot already has a
* destination field.
*/
DestinationField::DestinationField(const ObjectState* state, MoveSlot& parent)
: SlotField(state, parent) {
if (state->name() != OSNAME_DESTINATION_FIELD) {
const string procName = "DestinationField::DestinationField";
throw ObjectStateLoadingException(__FILE__, __LINE__, procName);
}
setParent(NULL);
parent.setDestinationField(*this);
setParent(&parent);
}
/**
* The destructor.
*/
DestinationField::~DestinationField() {
MoveSlot* parent = this->parent();
assert(parent != NULL);
setParent(NULL);
parent->unsetDestinationField();
}
/**
* Saves the state of the object to an ObjectState tree.
*
* @return The newly created ObjectState tree.
*/
ObjectState*
DestinationField::saveState() const {
ObjectState* state = SlotField::saveState();
state->setName(OSNAME_DESTINATION_FIELD);
return state;
}
| 32.737705 | 79 | 0.705058 | kanishkan |
5d5edeafb6b57aacc1a54a3edb36df001c920da1 | 20,107 | cpp | C++ | Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreHardwareBufferManager.h"
#include "OgreVertexIndexData.h"
#include "OgreLogManager.h"
namespace Ogre {
//-----------------------------------------------------------------------
template<> HardwareBufferManager* Singleton<HardwareBufferManager>::ms_Singleton = 0;
HardwareBufferManager* HardwareBufferManager::getSingletonPtr(void)
{
return ms_Singleton;
}
HardwareBufferManager& HardwareBufferManager::getSingleton(void)
{
assert( ms_Singleton ); return ( *ms_Singleton );
}
// Free temporary vertex buffers every 5 minutes on 100fps
const size_t HardwareBufferManager::UNDER_USED_FRAME_THRESHOLD = 30000;
const size_t HardwareBufferManager::EXPIRED_DELAY_FRAME_THRESHOLD = 5;
//-----------------------------------------------------------------------
HardwareBufferManager::HardwareBufferManager()
: mUnderUsedFrameCount(0)
{
}
//-----------------------------------------------------------------------
HardwareBufferManager::~HardwareBufferManager()
{
// Clear vertex/index buffer list first, avoid destroyed notify do
// unnecessary work, and we'll destroy everything here.
mVertexBuffers.clear();
mIndexBuffers.clear();
// Destroy everything
destroyAllDeclarations();
destroyAllBindings();
// No need to destroy main buffers - they will be destroyed by removal of bindings
// No need to destroy temp buffers - they will be destroyed automatically.
}
//-----------------------------------------------------------------------
VertexDeclaration* HardwareBufferManager::createVertexDeclaration(void)
{
VertexDeclaration* decl = createVertexDeclarationImpl();
mVertexDeclarations.insert(decl);
return decl;
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyVertexDeclaration(VertexDeclaration* decl)
{
mVertexDeclarations.erase(decl);
destroyVertexDeclarationImpl(decl);
}
//-----------------------------------------------------------------------
VertexBufferBinding* HardwareBufferManager::createVertexBufferBinding(void)
{
VertexBufferBinding* ret = createVertexBufferBindingImpl();
mVertexBufferBindings.insert(ret);
return ret;
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyVertexBufferBinding(VertexBufferBinding* binding)
{
mVertexBufferBindings.erase(binding);
destroyVertexBufferBindingImpl(binding);
}
//-----------------------------------------------------------------------
VertexDeclaration* HardwareBufferManager::createVertexDeclarationImpl(void)
{
return new VertexDeclaration();
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyVertexDeclarationImpl(VertexDeclaration* decl)
{
delete decl;
}
//-----------------------------------------------------------------------
VertexBufferBinding* HardwareBufferManager::createVertexBufferBindingImpl(void)
{
return new VertexBufferBinding();
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyVertexBufferBindingImpl(VertexBufferBinding* binding)
{
delete binding;
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyAllDeclarations(void)
{
VertexDeclarationList::iterator decl;
for (decl = mVertexDeclarations.begin(); decl != mVertexDeclarations.end(); ++decl)
{
destroyVertexDeclarationImpl(*decl);
}
mVertexDeclarations.clear();
}
//-----------------------------------------------------------------------
void HardwareBufferManager::destroyAllBindings(void)
{
VertexBufferBindingList::iterator bind;
for (bind = mVertexBufferBindings.begin(); bind != mVertexBufferBindings.end(); ++bind)
{
destroyVertexBufferBindingImpl(*bind);
}
mVertexBufferBindings.clear();
}
//-----------------------------------------------------------------------
void HardwareBufferManager::registerVertexBufferSourceAndCopy(
const HardwareVertexBufferSharedPtr& sourceBuffer,
const HardwareVertexBufferSharedPtr& copy)
{
// Add copy to free temporary vertex buffers
mFreeTempVertexBufferMap.insert(
FreeTemporaryVertexBufferMap::value_type(sourceBuffer.get(), copy));
}
//-----------------------------------------------------------------------
HardwareVertexBufferSharedPtr
HardwareBufferManager::allocateVertexBufferCopy(
const HardwareVertexBufferSharedPtr& sourceBuffer,
BufferLicenseType licenseType, HardwareBufferLicensee* licensee,
bool copyData)
{
HardwareVertexBufferSharedPtr vbuf;
// Locate existing buffer copy in temporary vertex buffers
FreeTemporaryVertexBufferMap::iterator i =
mFreeTempVertexBufferMap.find(sourceBuffer.get());
if (i == mFreeTempVertexBufferMap.end())
{
// copy buffer, use shadow buffer and make dynamic
vbuf = makeBufferCopy(
sourceBuffer,
HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE,
true);
}
else
{
// Allocate existing copy
vbuf = i->second;
mFreeTempVertexBufferMap.erase(i);
}
// Copy data?
if (copyData)
{
vbuf->copyData(*(sourceBuffer.get()), 0, 0, sourceBuffer->getSizeInBytes(), true);
}
// Insert copy into licensee list
mTempVertexBufferLicenses.insert(
TemporaryVertexBufferLicenseMap::value_type(
vbuf.get(),
VertexBufferLicense(sourceBuffer.get(), licenseType, EXPIRED_DELAY_FRAME_THRESHOLD, vbuf, licensee)));
return vbuf;
}
//-----------------------------------------------------------------------
void HardwareBufferManager::releaseVertexBufferCopy(
const HardwareVertexBufferSharedPtr& bufferCopy)
{
TemporaryVertexBufferLicenseMap::iterator i =
mTempVertexBufferLicenses.find(bufferCopy.get());
if (i != mTempVertexBufferLicenses.end())
{
const VertexBufferLicense& vbl = i->second;
vbl.licensee->licenseExpired(vbl.buffer.get());
mFreeTempVertexBufferMap.insert(
FreeTemporaryVertexBufferMap::value_type(vbl.originalBufferPtr, vbl.buffer));
mTempVertexBufferLicenses.erase(i);
}
}
//-----------------------------------------------------------------------
void HardwareBufferManager::touchVertexBufferCopy(
const HardwareVertexBufferSharedPtr& bufferCopy)
{
TemporaryVertexBufferLicenseMap::iterator i =
mTempVertexBufferLicenses.find(bufferCopy.get());
if (i != mTempVertexBufferLicenses.end())
{
VertexBufferLicense& vbl = i->second;
assert(vbl.licenseType == BLT_AUTOMATIC_RELEASE);
vbl.expiredDelay = EXPIRED_DELAY_FRAME_THRESHOLD;
}
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_freeUnusedBufferCopies(void)
{
size_t numFreed = 0;
// Free unused temporary buffers
FreeTemporaryVertexBufferMap::iterator i;
i = mFreeTempVertexBufferMap.begin();
while (i != mFreeTempVertexBufferMap.end())
{
FreeTemporaryVertexBufferMap::iterator icur = i++;
// Free the temporary buffer that referenced by ourself only.
// TODO: Some temporary buffers are bound to vertex buffer bindings
// but not checked out, need to sort out method to unbind them.
if (icur->second.useCount() <= 1)
{
++numFreed;
mFreeTempVertexBufferMap.erase(icur);
}
}
StringUtil::StrStreamType str;
if (numFreed)
{
str << "HardwareBufferManager: Freed " << numFreed << " unused temporary vertex buffers.";
}
else
{
str << "HardwareBufferManager: No unused temporary vertex buffers found.";
}
LogManager::getSingleton().logMessage(str.str(), LML_TRIVIAL);
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_releaseBufferCopies(bool forceFreeUnused)
{
size_t numUnused = mFreeTempVertexBufferMap.size();
size_t numUsed = mTempVertexBufferLicenses.size();
// Erase the copies which are automatic licensed out
TemporaryVertexBufferLicenseMap::iterator i;
i = mTempVertexBufferLicenses.begin();
while (i != mTempVertexBufferLicenses.end())
{
TemporaryVertexBufferLicenseMap::iterator icur = i++;
VertexBufferLicense& vbl = icur->second;
if (vbl.licenseType == BLT_AUTOMATIC_RELEASE &&
(forceFreeUnused || --vbl.expiredDelay <= 0))
{
vbl.licensee->licenseExpired(vbl.buffer.get());
mFreeTempVertexBufferMap.insert(
FreeTemporaryVertexBufferMap::value_type(vbl.originalBufferPtr, vbl.buffer));
mTempVertexBufferLicenses.erase(icur);
}
}
// Check whether or not free unused temporary vertex buffers.
if (forceFreeUnused)
{
_freeUnusedBufferCopies();
mUnderUsedFrameCount = 0;
}
else
{
if (numUsed < numUnused)
{
// Free temporary vertex buffers if too many unused for a long time.
// Do overall temporary vertex buffers instead of per source buffer
// to avoid overhead.
++mUnderUsedFrameCount;
if (mUnderUsedFrameCount >= UNDER_USED_FRAME_THRESHOLD)
{
_freeUnusedBufferCopies();
mUnderUsedFrameCount = 0;
}
}
else
{
mUnderUsedFrameCount = 0;
}
}
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_forceReleaseBufferCopies(
const HardwareVertexBufferSharedPtr& sourceBuffer)
{
_forceReleaseBufferCopies(sourceBuffer.get());
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_forceReleaseBufferCopies(
HardwareVertexBuffer* sourceBuffer)
{
// Erase the copies which are licensed out
TemporaryVertexBufferLicenseMap::iterator i;
i = mTempVertexBufferLicenses.begin();
while (i != mTempVertexBufferLicenses.end())
{
TemporaryVertexBufferLicenseMap::iterator icur = i++;
const VertexBufferLicense& vbl = icur->second;
if (vbl.originalBufferPtr == sourceBuffer)
{
// Just tell the owner that this is being released
vbl.licensee->licenseExpired(vbl.buffer.get());
mTempVertexBufferLicenses.erase(icur);
}
}
// Erase the free copies
//
// Why we need this unusual code? It's for resolve reenter problem.
//
// Using mFreeTempVertexBufferMap.erase(sourceBuffer) directly will
// cause reenter into here because vertex buffer destroyed notify.
// In most time there are no problem. But when sourceBuffer is the
// last item of the mFreeTempVertexBufferMap, some STL multimap
// implementation (VC and STLport) will call to clear(), which will
// causing intermediate state of mFreeTempVertexBufferMap, in that
// time destroyed notify back to here cause illegal accessing in
// the end.
//
// For safely reason, use following code to resolve reenter problem.
//
typedef FreeTemporaryVertexBufferMap::iterator _Iter;
std::pair<_Iter, _Iter> range = mFreeTempVertexBufferMap.equal_range(sourceBuffer);
if (range.first != range.second)
{
std::list<HardwareVertexBufferSharedPtr> holdForDelayDestroy;
for (_Iter it = range.first; it != range.second; ++it)
{
if (it->second.useCount() <= 1)
{
holdForDelayDestroy.push_back(it->second);
}
}
mFreeTempVertexBufferMap.erase(range.first, range.second);
// holdForDelayDestroy will destroy auto.
}
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_notifyVertexBufferDestroyed(HardwareVertexBuffer* buf)
{
VertexBufferList::iterator i = mVertexBuffers.find(buf);
if (i != mVertexBuffers.end())
{
// release vertex buffer copies
mVertexBuffers.erase(i);
_forceReleaseBufferCopies(buf);
}
}
//-----------------------------------------------------------------------
void HardwareBufferManager::_notifyIndexBufferDestroyed(HardwareIndexBuffer* buf)
{
IndexBufferList::iterator i = mIndexBuffers.find(buf);
if (i != mIndexBuffers.end())
{
mIndexBuffers.erase(i);
}
}
//-----------------------------------------------------------------------
HardwareVertexBufferSharedPtr
HardwareBufferManager::makeBufferCopy(
const HardwareVertexBufferSharedPtr& source,
HardwareBuffer::Usage usage, bool useShadowBuffer)
{
return this->createVertexBuffer(
source->getVertexSize(),
source->getNumVertices(),
usage, useShadowBuffer);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TempBlendedBufferInfo::~TempBlendedBufferInfo(void)
{
// check that temp buffers have been released
HardwareBufferManager &mgr = HardwareBufferManager::getSingleton();
if (!destPositionBuffer.isNull())
mgr.releaseVertexBufferCopy(destPositionBuffer);
if (!destNormalBuffer.isNull())
mgr.releaseVertexBufferCopy(destNormalBuffer);
}
//-----------------------------------------------------------------------------
void TempBlendedBufferInfo::extractFrom(const VertexData* sourceData)
{
// Release old buffer copies first
HardwareBufferManager &mgr = HardwareBufferManager::getSingleton();
if (!destPositionBuffer.isNull())
{
mgr.releaseVertexBufferCopy(destPositionBuffer);
assert(destPositionBuffer.isNull());
}
if (!destNormalBuffer.isNull())
{
mgr.releaseVertexBufferCopy(destNormalBuffer);
assert(destNormalBuffer.isNull());
}
VertexDeclaration* decl = sourceData->vertexDeclaration;
VertexBufferBinding* bind = sourceData->vertexBufferBinding;
const VertexElement *posElem = decl->findElementBySemantic(VES_POSITION);
const VertexElement *normElem = decl->findElementBySemantic(VES_NORMAL);
assert(posElem && "Positions are required");
posBindIndex = posElem->getSource();
srcPositionBuffer = bind->getBuffer(posBindIndex);
if (!normElem)
{
posNormalShareBuffer = false;
srcNormalBuffer.setNull();
}
else
{
normBindIndex = normElem->getSource();
if (normBindIndex == posBindIndex)
{
posNormalShareBuffer = true;
srcNormalBuffer.setNull();
}
else
{
posNormalShareBuffer = false;
srcNormalBuffer = bind->getBuffer(normBindIndex);
}
}
}
//-----------------------------------------------------------------------------
void TempBlendedBufferInfo::checkoutTempCopies(bool positions, bool normals)
{
bindPositions = positions;
bindNormals = normals;
HardwareBufferManager &mgr = HardwareBufferManager::getSingleton();
if (positions && destPositionBuffer.isNull())
{
destPositionBuffer = mgr.allocateVertexBufferCopy(srcPositionBuffer,
HardwareBufferManager::BLT_AUTOMATIC_RELEASE, this);
}
if (normals && !posNormalShareBuffer && !srcNormalBuffer.isNull() && destNormalBuffer.isNull())
{
destNormalBuffer = mgr.allocateVertexBufferCopy(srcNormalBuffer,
HardwareBufferManager::BLT_AUTOMATIC_RELEASE, this);
}
}
//-----------------------------------------------------------------------------
bool TempBlendedBufferInfo::buffersCheckedOut(bool positions, bool normals) const
{
HardwareBufferManager &mgr = HardwareBufferManager::getSingleton();
if (positions || (normals && posNormalShareBuffer))
{
if (destPositionBuffer.isNull())
return false;
mgr.touchVertexBufferCopy(destPositionBuffer);
}
if (normals && !posNormalShareBuffer)
{
if (destNormalBuffer.isNull())
return false;
mgr.touchVertexBufferCopy(destNormalBuffer);
}
return true;
}
//-----------------------------------------------------------------------------
void TempBlendedBufferInfo::bindTempCopies(VertexData* targetData, bool suppressHardwareUpload)
{
this->destPositionBuffer->suppressHardwareUpdate(suppressHardwareUpload);
targetData->vertexBufferBinding->setBinding(
this->posBindIndex, this->destPositionBuffer);
if (bindNormals && !posNormalShareBuffer && !destNormalBuffer.isNull())
{
this->destNormalBuffer->suppressHardwareUpdate(suppressHardwareUpload);
targetData->vertexBufferBinding->setBinding(
this->normBindIndex, this->destNormalBuffer);
}
}
//-----------------------------------------------------------------------------
void TempBlendedBufferInfo::licenseExpired(HardwareBuffer* buffer)
{
assert(buffer == destPositionBuffer.get()
|| buffer == destNormalBuffer.get());
if (buffer == destPositionBuffer.get())
destPositionBuffer.setNull();
if (buffer == destNormalBuffer.get())
destNormalBuffer.setNull();
}
}
| 39.194932 | 118 | 0.561198 | hackerlank |
5d60f4453a4e2c0bff29e205fc60cc7dd8f2b7f5 | 5,548 | cpp | C++ | src/core/transform/ojph_colour_sse2.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | src/core/transform/ojph_colour_sse2.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | src/core/transform/ojph_colour_sse2.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************/
// This software is released under the 2-Clause BSD license, included
// below.
//
// Copyright (c) 2019, Aous Naman
// Copyright (c) 2019, Kakadu Software Pty Ltd, Australia
// Copyright (c) 2019, The University of New South Wales, Australia
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/****************************************************************************/
// This file is part of the OpenJPH software implementation.
// File: ojph_colour_sse2.cpp
// Author: Aous Naman
// Date: 11 October 2019
/****************************************************************************/
#include <cmath>
#include "ojph_defs.h"
#include "ojph_arch.h"
#include "ojph_colour.h"
#ifdef OJPH_COMPILER_MSVC
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
namespace ojph {
namespace local {
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_float_to_si32_shftd(const float *sp, si32 *dp, float mul,
int width)
{
uint32_t rounding_mode = _MM_GET_ROUNDING_MODE();
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
__m128 shift = _mm_set1_ps(0.5f);
__m128 m = _mm_set1_ps(mul);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128 t = _mm_loadu_ps(sp);
__m128 s = _mm_add_ps(t, shift);
s = _mm_mul_ps(s, m);
_mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s));
}
_MM_SET_ROUNDING_MODE(rounding_mode);
}
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_float_to_si32(const float *sp, si32 *dp, float mul,
int width)
{
uint32_t rounding_mode = _MM_GET_ROUNDING_MODE();
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
__m128 m = _mm_set1_ps(mul);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128 t = _mm_loadu_ps(sp);
__m128 s = _mm_mul_ps(t, m);
_mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s));
}
_MM_SET_ROUNDING_MODE(rounding_mode);
}
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_si32_to_si32_shftd(const si32 *sp, si32 *dp, int shift,
int width)
{
__m128i sh = _mm_set1_epi32(shift);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128i s = _mm_loadu_si128((__m128i*)sp);
s = _mm_add_epi32(s, sh);
_mm_storeu_si128((__m128i*)dp, s);
}
}
//////////////////////////////////////////////////////////////////////////
void sse2_rct_forward(const si32 *r, const si32 *g, const si32 *b,
si32 *y, si32 *cb, si32 *cr, int repeat)
{
for (int i = (repeat + 3) >> 2; i > 0; --i)
{
__m128i mr = _mm_load_si128((__m128i*)r);
__m128i mg = _mm_load_si128((__m128i*)g);
__m128i mb = _mm_load_si128((__m128i*)b);
__m128i t = _mm_add_epi32(mr, mb);
t = _mm_add_epi32(t, _mm_slli_epi32(mg, 1));
_mm_store_si128((__m128i*)y, _mm_srai_epi32(t, 2));
t = _mm_sub_epi32(mb, mg);
_mm_store_si128((__m128i*)cb, t);
t = _mm_sub_epi32(mr, mg);
_mm_store_si128((__m128i*)cr, t);
r += 4; g += 4; b += 4;
y += 4; cb += 4; cr += 4;
}
}
//////////////////////////////////////////////////////////////////////////
void sse2_rct_backward(const si32 *y, const si32 *cb, const si32 *cr,
si32 *r, si32 *g, si32 *b, int repeat)
{
for (int i = (repeat + 3) >> 2; i > 0; --i)
{
__m128i my = _mm_load_si128((__m128i*)y);
__m128i mcb = _mm_load_si128((__m128i*)cb);
__m128i mcr = _mm_load_si128((__m128i*)cr);
__m128i t = _mm_add_epi32(mcb, mcr);
t = _mm_sub_epi32(my, _mm_srai_epi32(t, 2));
_mm_store_si128((__m128i*)g, t);
__m128i u = _mm_add_epi32(mcb, t);
_mm_store_si128((__m128i*)b, u);
u = _mm_add_epi32(mcr, t);
_mm_store_si128((__m128i*)r, u);
y += 4; cb += 4; cr += 4;
r += 4; g += 4; b += 4;
}
}
}
}
| 37.486486 | 78 | 0.550108 | jpambrun |
5d63312817b6c5ab1f5ff2e5a7de4c3775eff77e | 8,319 | cpp | C++ | src/linux/InotifyEventLoop.cpp | dacap/panoptes | f7d4756f18ff610f0ef2c160d56cd00cc3582939 | [
"MIT"
] | null | null | null | src/linux/InotifyEventLoop.cpp | dacap/panoptes | f7d4756f18ff610f0ef2c160d56cd00cc3582939 | [
"MIT"
] | null | null | null | src/linux/InotifyEventLoop.cpp | dacap/panoptes | f7d4756f18ff610f0ef2c160d56cd00cc3582939 | [
"MIT"
] | null | null | null | #include "pfw/linux/InotifyEventLoop.h"
#include <sys/ioctl.h>
#include <csignal>
#include <iostream>
using namespace pfw;
InotifyEventLoop::InotifyEventLoop(int inotifyInstance,
InotifyService *inotifyService)
: mInotifyService(inotifyService)
, mInotifyInstance(inotifyInstance)
, mStopped(true)
{
int result = pthread_create(&mEventLoop, nullptr, work, this);
if (result != 0) {
mInotifyService->sendError(
"Could not start InotifyEventLoop thread. ErrorCode: " +
std::string(strerror(errno)));
return;
}
mThreadStartedSemaphore.wait();
}
bool InotifyEventLoop::isLooping() { return !mStopped; }
void InotifyEventLoop::created(inotify_event *event,
bool isDirectoryEvent,
bool sendInitEvents)
{
if (event == NULL || mStopped) {
return;
}
if (isDirectoryEvent) {
mInotifyService->createDirectory(event->wd, strdup(event->name),
sendInitEvents);
} else {
mInotifyService->create(event->wd, strdup(event->name));
}
}
void InotifyEventLoop::modified(inotify_event *event)
{
if (event == NULL || mStopped) {
return;
}
mInotifyService->modify(event->wd, strdup(event->name));
}
void InotifyEventLoop::deleted(inotify_event *event, bool isDirectoryRemoval)
{
if (event == NULL || mStopped) {
return;
}
if (isDirectoryRemoval) {
mInotifyService->removeDirectory(event->wd);
} else {
mInotifyService->remove(event->wd, strdup(event->name));
}
}
void InotifyEventLoop::moveStart(inotify_event * event,
bool isDirectoryEvent,
InotifyRenameEvent &renameEvent)
{
if (mStopped) {
return;
}
renameEvent = InotifyRenameEvent(event, isDirectoryEvent);
}
void InotifyEventLoop::moveEnd(inotify_event * event,
bool isDirectoryEvent,
InotifyRenameEvent &renameEvent)
{
if (mStopped) {
return;
}
if (!renameEvent.isGood) {
return created(event, isDirectoryEvent, false);
}
renameEvent.isGood = false;
if (renameEvent.cookie != event->cookie) {
if (renameEvent.isDirectory) {
mInotifyService->removeDirectory(renameEvent.wd, renameEvent.name);
}
mInotifyService->remove(renameEvent.wd, renameEvent.name);
return created(event, isDirectoryEvent, false);
}
if (renameEvent.isDirectory) {
mInotifyService->moveDirectory(renameEvent.wd, renameEvent.name,
event->wd, event->name);
} else {
mInotifyService->move(renameEvent.wd, renameEvent.name, event->wd,
event->name);
}
}
void InotifyEventLoop::finish(void *args)
{
InotifyEventLoop *eventLoop = reinterpret_cast<InotifyEventLoop *>(args);
eventLoop->mStopped = true;
}
void *InotifyEventLoop::work(void *args)
{
pthread_cleanup_push(InotifyEventLoop::finish, args);
static const int BUFFER_SIZE = 16384;
InotifyEventLoop *eventLoop = reinterpret_cast<InotifyEventLoop *>(args);
eventLoop->mStopped = false;
eventLoop->mThreadStartedSemaphore.signal();
InotifyRenameEvent renameEvent;
while (!eventLoop->mStopped) {
char buffer[BUFFER_SIZE];
auto bytesRead =
read(eventLoop->mInotifyInstance, &buffer, BUFFER_SIZE);
if (eventLoop->mStopped) {
break;
} else if (bytesRead == 0) {
eventLoop->mInotifyService->sendError(
"InotifyEventLoop thread mStopped because read returned 0.");
break;
} else if (bytesRead == -1) {
// read was interrupted
if (errno == EINTR) {
break;
}
eventLoop->mInotifyService->sendError(
"Read on inotify fails because of error: " +
std::string(strerror(errno)));
break;
}
ssize_t position = 0;
inotify_event *event = nullptr;
do {
if (eventLoop->mStopped) {
break;
}
event = (struct inotify_event *)(buffer + position);
bool isDirectoryRemoval =
event->mask & (uint32_t)(IN_IGNORED | IN_DELETE_SELF);
bool isDirectoryEvent = event->mask & (uint32_t)(IN_ISDIR);
if (renameEvent.isGood && event->cookie != renameEvent.cookie) {
eventLoop->moveEnd(event, isDirectoryEvent, renameEvent);
} else if (event->mask & (uint32_t)(IN_ATTRIB | IN_MODIFY)) {
eventLoop->modified(event);
} else if (event->mask & (uint32_t)IN_CREATE) {
eventLoop->created(event, isDirectoryEvent);
} else if (event->mask & (uint32_t)(IN_DELETE | IN_DELETE_SELF)) {
eventLoop->deleted(event, isDirectoryRemoval);
} else if (event->mask & (uint32_t)IN_MOVED_TO) {
if (event->cookie == 0) {
eventLoop->created(event, isDirectoryEvent);
continue;
}
eventLoop->moveEnd(event, isDirectoryEvent, renameEvent);
} else if (event->mask & (uint32_t)IN_MOVED_FROM) {
if (event->cookie == 0) {
eventLoop->deleted(event, isDirectoryRemoval);
continue;
}
eventLoop->moveStart(event, isDirectoryEvent, renameEvent);
} else if (event->mask & (uint32_t)IN_MOVE_SELF) {
eventLoop->mInotifyService->remove(event->wd,
strdup(event->name));
eventLoop->mInotifyService->removeDirectory(event->wd);
}
} while ((position += sizeof(struct inotify_event) + event->len) <
bytesRead);
if (eventLoop->mStopped) {
break;
}
size_t bytesAvailable = 0;
if (ioctl(eventLoop->mInotifyInstance, FIONREAD, &bytesAvailable) < 0) {
continue;
}
if (bytesAvailable == 0) {
// If we have a trailing renameEvent and not another event is in the
// pipeline, then we need to finish this renameEvent. Otherwise we
// will loose the information of pending rename event.
if (renameEvent.isGood) {
if (renameEvent.isDirectory) {
eventLoop->mInotifyService->removeDirectory(
renameEvent.wd, renameEvent.name);
}
eventLoop->mInotifyService->remove(renameEvent.wd,
renameEvent.name);
}
}
}
pthread_cleanup_pop(1);
return nullptr;
}
InotifyEventLoop::~InotifyEventLoop()
{
if (mStopped) {
return;
}
mStopped = true;
// \note(mathias): To be sure, that canceling the thread does not causes
// abortion of the whole programm, because another lib reacts on signal 32,
// we ignore the signal extra. Additionally we are saving the previous
// handler to register this handler to signal 32 again at the end. (This is
// only a assumption, because we was seeing this behaviour (abort of the
// whole programm when calling dtor of NotifyEventLoop) in combination with
// other libs without finding the root causes.
auto previousHandler = std::signal(32, SIG_IGN);
auto errorCode = pthread_cancel(mEventLoop);
if (errorCode != 0) {
mInotifyService->sendError(
"Could not cancel InotifyEventLoop thread. ErrorCode: " +
std::to_string(errorCode));
return;
}
errorCode = pthread_join(mEventLoop, NULL);
if (errorCode != 0) {
mInotifyService->sendError(
"Could not join InotifyEventLoop thread. ErrorCode: " +
std::to_string(errorCode));
}
if (previousHandler != SIG_ERR) {
std::signal(32, previousHandler);
}
}
| 33.011905 | 80 | 0.572184 | dacap |
5d6397aa9ffd990562f026bebdca8b30e28aab2a | 348 | hpp | C++ | include/aikido/common/memory.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 181 | 2016-04-22T15:11:23.000Z | 2022-03-26T12:51:08.000Z | include/aikido/common/memory.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 514 | 2016-04-20T04:29:51.000Z | 2022-02-10T19:46:21.000Z | include/aikido/common/memory.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 31 | 2017-03-17T09:53:02.000Z | 2022-03-23T10:35:05.000Z | #ifndef AIKIDO_COMMON_MEMORY_HPP_
#define AIKIDO_COMMON_MEMORY_HPP_
#include <memory>
namespace aikido {
namespace common {
template <typename T, typename... Args>
::std::unique_ptr<T> make_unique(Args&&... args);
} // namespace common
} // namespace aikido
#include "aikido/common/detail/memory-impl.hpp"
#endif // AIKIDO_COMMON_MEMORY_HPP_
| 19.333333 | 49 | 0.761494 | personalrobotics |
5d647427755bd5cf6ebbca66a79030eb40079c79 | 4,346 | cpp | C++ | src/Utils/Tests/Math/BSplines/BSplineTest.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | src/Utils/Tests/Math/BSplines/BSplineTest.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | src/Utils/Tests/Math/BSplines/BSplineTest.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include <Utils/Math/BSplines/BSpline.h>
#include <Utils/Math/BSplines/Coefficients.h>
#include <Utils/Math/BSplines/Exceptions.h>
#include <Utils/Math/BSplines/InterpolationGenerator.h>
#include <gmock/gmock.h>
using namespace testing;
namespace Scine {
namespace Utils {
using namespace BSplines;
namespace Tests {
class ABspline : public Test {
public:
BSpline randomBSpline;
protected:
void SetUp() override {
const int numberDimensions = 4;
const int numberPoints = 20;
Eigen::MatrixXd randomPoints = Eigen::MatrixXd::Random(numberPoints, numberDimensions);
InterpolationGenerator generator(randomPoints);
randomBSpline = generator.generateBSpline();
}
};
namespace {
void compareAtRandomUValues(const BSpline& b1, const BSpline& b2) {
for (auto u : {0.001111, 0.232323, 0.555, 0.8766, 0.999}) {
Eigen::VectorXd v1 = b1.evaluate(u);
Eigen::VectorXd v2 = b2.evaluate(u);
ASSERT_TRUE(v1.isApprox(v2));
}
}
void compareDividedSpline(const BSpline& b1, const BSpline& b2, const BSpline& b3) {
for (auto u : {0.001111, 0.232323, 0.555, 0.8766, 0.999}) {
Eigen::VectorXd v1 = b1.evaluate(u);
Eigen::VectorXd v2 = b2.evaluate(u);
Eigen::VectorXd v3 = b3.evaluate(u);
Eigen::VectorXd v23(v2.size() + v3.size());
v23 << v2, v3;
ASSERT_TRUE(v1.isApprox(v23));
}
}
} // namespace
TEST_F(ABspline, CanBeGeneratedFromDegreeAndKnotsAndControlPoints) {
auto degree = randomBSpline.getDegree();
Eigen::VectorXd knotVector = randomBSpline.getKnotVector();
Eigen::MatrixXd controlPoints = randomBSpline.getControlPointMatrix();
BSpline copiedSpline{knotVector, controlPoints, degree};
compareAtRandomUValues(randomBSpline, copiedSpline);
}
TEST_F(ABspline, CanBeDividedAlongDimensions) {
auto degree = randomBSpline.getDegree();
Eigen::VectorXd knotVector = randomBSpline.getKnotVector();
Eigen::MatrixXd controlPoints = randomBSpline.getControlPointMatrix();
BSpline bspline1d{knotVector, controlPoints.leftCols(1), degree};
BSpline bspline3d{knotVector, controlPoints.rightCols(3), degree};
compareDividedSpline(randomBSpline, bspline1d, bspline3d);
}
TEST_F(ABspline, CanBeReversed) {
auto reversed = randomBSpline.reversed();
for (auto u : {0.002, 0.3, 0.5436, 0.900}) {
auto v = randomBSpline.evaluate(u);
auto w = reversed.evaluate(1.0 - u);
ASSERT_TRUE(v.isApprox(w));
}
}
TEST_F(ABspline, ReversingTwoTimesDeliversOriginalSpline) {
auto reversed = randomBSpline.reversed();
auto reversedTwoTimes = reversed.reversed();
compareAtRandomUValues(randomBSpline, reversedTwoTimes);
}
TEST_F(ABspline, ReturnsZeroDimensionalValueWhenUninitialized) {
BSpline uninitialized;
for (auto u : {0.01, 0.4, 0.8}) {
auto v = uninitialized.evaluate(u);
ASSERT_THAT(v.size(), Eq(0));
}
}
TEST_F(ABspline, CalculatesNoDerivativesByDefault) {
ASSERT_THAT(randomBSpline.getHighestCalculatedDerivative(), Eq(0));
}
TEST_F(ABspline, CalculatesMissingDerivatives) {
double u = 0.333;
ASSERT_THAT(randomBSpline.getHighestCalculatedDerivative(), Eq(0));
randomBSpline.evaluate(u, 2);
ASSERT_THAT(randomBSpline.getHighestCalculatedDerivative(), Eq(2));
}
TEST_F(ABspline, EvaluationIsSameAsLinearCombinationOfCoefficientsAndControlPoints) {
double u = 0.5678;
const auto& controlPoints = randomBSpline.getControlPointMatrix();
Eigen::VectorXd bsplineCoefficients = randomBSpline.calculateBSplineCoefficientVector(u);
Eigen::VectorXd evaluated = randomBSpline.evaluate(u);
Eigen::VectorXd linearCombination = controlPoints.transpose() * bsplineCoefficients;
ASSERT_TRUE(evaluated.isApprox(linearCombination));
}
TEST_F(ABspline, CoefficientsClassCorrespondsToCoefficientVector) {
double u = 0.5678;
Eigen::VectorXd fullBsplineCoefficients = randomBSpline.calculateBSplineCoefficientVector(u);
auto coefficientClass = randomBSpline.calculateBSplineCoefficients(u);
for (int i = 0; i < fullBsplineCoefficients.size(); ++i) {
ASSERT_THAT(coefficientClass.get(i), DoubleEq(fullBsplineCoefficients(i)));
}
}
} // namespace Tests
} // namespace Utils
} // namespace Scine
| 31.266187 | 95 | 0.744133 | DockBio |
5d6564bb0a711a45cfb9ec66e881bf51ebc78c8a | 1,103 | cpp | C++ | src/worker/ProgressReporter.cpp | rosneru/ADiffView | 5f7d6cf4c7b5c65ba1221370d272ba12c21f4911 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/worker/ProgressReporter.cpp | rosneru/ADiffView | 5f7d6cf4c7b5c65ba1221370d272ba12c21f4911 | [
"BSD-3-Clause",
"MIT"
] | 7 | 2019-02-09T18:27:06.000Z | 2021-07-13T09:47:18.000Z | src/worker/ProgressReporter.cpp | rosneru/ADiffView | 5f7d6cf4c7b5c65ba1221370d272ba12c21f4911 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #ifdef __clang__
#include <clib/exec_protos.h>
#else
#include <proto/exec.h>
#endif
#include <stddef.h>
#include "ProgressMessage.h"
#include "ProgressReporter.h"
ProgressReporter::ProgressReporter(struct MsgPort* pProgressPort,
struct MsgPort*& pReplyPort)
: m_pProgressPort(pProgressPort),
m_pReplyPort(pReplyPort),
m_pProgressDescription("Progress..")
{
}
void ProgressReporter::SetDescription(const char *pProgressDescription)
{
m_pProgressDescription = pProgressDescription;
}
void ProgressReporter::SetValue(int progress)
{
if ((m_pProgressPort == NULL) || (m_pReplyPort == NULL))
{
return;
}
// Creating and initializing the progress message
struct ProgressMessage progressMessage;
progressMessage.mn_ReplyPort = m_pReplyPort;
progressMessage.progress = progress;
progressMessage.pDescription = m_pProgressDescription;
// Sending the progress message, waiting for the answer and taking the
// answer off the queue
PutMsg(m_pProgressPort, &progressMessage);
WaitPort(m_pReplyPort);
GetMsg(m_pReplyPort);
}
| 23.468085 | 72 | 0.738894 | rosneru |
5d65678462753f48387aca3e2e37a5151966a5f3 | 4,754 | hpp | C++ | liboh/plugins/js/EmersonMessagingManager.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 31 | 2015-01-28T17:01:10.000Z | 2021-11-04T08:30:37.000Z | liboh/plugins/js/EmersonMessagingManager.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | null | null | null | liboh/plugins/js/EmersonMessagingManager.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 9 | 2015-08-02T18:39:49.000Z | 2019-10-11T10:32:30.000Z | // Copyright (c) 2011 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef __EMERSON_MESSAGING_MANAGER_HPP__
#define __EMERSON_MESSAGING_MANAGER_HPP__
#include <map>
#include <sirikata/core/odp/SSTDecls.hpp>
#include <sirikata/core/network/ObjectMessage.hpp>
#include <string>
#include <sstream>
#include <sirikata/core/util/Liveness.hpp>
#include <sirikata/oh/ObjectHostContext.hpp>
namespace Sirikata{
namespace JS{
class EmersonScript;
typedef ODPSST::StreamPtr SSTStreamPtr;
// NOTE: virtual on Liveness because JSObjectScript also uses it
class EmersonMessagingManager : public virtual Liveness
{
public:
EmersonMessagingManager(ObjectHostContext* ctx);
virtual ~EmersonMessagingManager();
//EmersonScript must know what to do with messages that we receive.
/*
Payload should be able to be parsed into JS::Proctocol::JSMessage. If it
can be, and deserialization is successful, processes the scripting
message. (via deserializeMsgAndDispatch.)
*/
virtual bool handleScriptCommRead(const SpaceObjectReference& src, const SpaceObjectReference& dst, const std::string& payload) = 0;
bool sendScriptCommMessageReliable(const SpaceObjectReference& sender, const SpaceObjectReference& receiver, const String& msg);
bool sendScriptCommMessageReliable(
const SpaceObjectReference& sender, const SpaceObjectReference& receiver,
const String& msg, int8 retriesSameStream,int8 retriesNewStream,
bool isRetry=false);
void presenceConnected(const SpaceObjectReference& connPresSporef);
void presenceDisconnected(const SpaceObjectReference& disconnPresSporef);
private:
// Possibly save the new stream to mStreams for later use. Since both sides
// might initiate, we always save the stream initiated by the object with
// smaller if we identify a conflict.
void setupNewStream(SSTStreamPtr sstStream, bool closePrevious = false);
// Get a saved stream for the given destination object, or NULL if one isn't
// available.
SSTStreamPtr getStream(const SpaceObjectReference& pres, const SpaceObjectReference& remote);
// "Destroy" (i.e. discard reference to) all streams owned by an object
void clearStreams(const SpaceObjectReference& pres);
//reading helpers
void createScriptCommListenerStreamCB(Liveness::Token alive, const SpaceObjectReference& toListenFrom, int err, SSTStreamPtr sstStream);
void handleIncomingSubstream(Liveness::Token alive, int err, SSTStreamPtr streamPtr);
void handleScriptCommStreamRead(Liveness::Token alive, SSTStreamPtr sstptr, String* prevdata, uint8* buffer, int length);
// Only put a few parameters in here to avoid copying lots of stuff, we only
// need to get < 8 parameters for bind to work on all platforms
struct CommWriteStreamConnectedCBRetryData {
int8 retriesSameStream;
int8 retriesNewStream;
bool isRetry;
};
//writing helper
void scriptCommWriteStreamConnectedCB(
Liveness::Token alive, const String& msg,
const SpaceObjectReference& sender, const SpaceObjectReference& receiver,
int err, SSTStreamPtr streamPtr, CommWriteStreamConnectedCBRetryData retryData);
// Writes a message to a *substream* of the given stream
void writeMessage(
Liveness::Token alive, SSTStreamPtr streamPtr,
const String& msg, const SpaceObjectReference& sender,
const SpaceObjectReference& receiver, int8 retriesSameStream,
int8 retriesNewStream);
void writeMessageSubstream(
Liveness::Token alive, int err, SSTStreamPtr subStreamPtr,
const String& msg, const SpaceObjectReference& sender,
const SpaceObjectReference& receiver, int8 retriesSameStream,
int8 retriesNewStream);
void writeData(Liveness::Token alive, SSTStreamPtr streamPtr, const String& msg, const SpaceObjectReference& sender, const SpaceObjectReference& receiver);
void removeStream(
const SpaceObjectReference& sender, const SpaceObjectReference& receiver);
ObjectHostContext* mMainContext;
//map of existing presences. value doesn't matter, just want a quick way of
//checking if particular presences are connected.
std::map<SpaceObjectReference, bool> allPres;
// Streams to be reused for sending messages
typedef std::tr1::unordered_map<SpaceObjectReference, SSTStreamPtr, SpaceObjectReference::Hasher> StreamMap;
typedef std::tr1::unordered_map<SpaceObjectReference, StreamMap, SpaceObjectReference::Hasher> PresenceStreamMap;
PresenceStreamMap mStreams;
};
} //end namespace js
} //end namespace sirikata
#endif
| 41.701754 | 159 | 0.75915 | sirikata |
5d67256f74975f08a7bef1f42dd9a3816aa9976f | 19,808 | cc | C++ | generator/cc/generate_struct_cc.cc | NTNAEEM/hotentot | e578a2185c473301076ece5634113ab663996a3e | [
"MIT"
] | null | null | null | generator/cc/generate_struct_cc.cc | NTNAEEM/hotentot | e578a2185c473301076ece5634113ab663996a3e | [
"MIT"
] | null | null | null | generator/cc/generate_struct_cc.cc | NTNAEEM/hotentot | e578a2185c473301076ece5634113ab663996a3e | [
"MIT"
] | null | null | null | /* The MIT License (MIT)
*
* Copyright (c) 2015 LabCrypto Org.
*
* 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 <iostream>
#include <fstream>
#include "cc_generator.h"
#include "type_helper.h"
#include "../hot.h"
#include "../service.h"
#include "../method.h"
#include "../module.h"
#include "../argument.h"
#include "../struct.h"
#include "../declaration.h"
#include "../os.h"
#include "../string_helper.h"
#include "../datetime_helper.h"
namespace org {
namespace labcrypto {
namespace hottentot {
namespace generator {
namespace cc {
void
CCGenerator::GenerateStructCC (
::org::labcrypto::hottentot::generator::Struct *structt,
::org::labcrypto::hottentot::generator::GenerationConfig &generationConfig,
std::map<std::string, std::string> &templates
) {
std::string indent = generationConfig.GetIndentString();
/*
* Making needed variables and assigning values to them
*/
std::string structNameCamelCaseFirstCapital =
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstCapital (
structt->GetName()
);
std::string structNameSnakeCase =
::org::labcrypto::hottentot::generator::StringHelper::MakeSnakeCaseFromCamelCase (
structNameCamelCaseFirstCapital
);
std::string structNameScreamingSnakeCase =
::org::labcrypto::hottentot::generator::StringHelper::MakeScreamingSnakeCaseFromCamelCase(structNameSnakeCase);
std::string ns = "::" +
::org::labcrypto::hottentot::generator::StringHelper::Concat (
::org::labcrypto::hottentot::generator::StringHelper::Split (
structt->module_->GetPackage(),
'.'
),
"::"
);
std::string structCCFilePath = generationConfig.GetOutDir() + "/" + structNameSnakeCase + ".cc";
/*
* Making real values
*/
std::vector<std::string> packageTokens =
::org::labcrypto::hottentot::generator::StringHelper::Split (
structt->module_->GetPackage(),
'.'
);
std::string namespacesStart = "";
for (uint32_t i = 0; i < packageTokens.size(); i++) {
namespacesStart += "namespace " +
::org::labcrypto::hottentot::generator::StringHelper::MakeLowerCase(packageTokens[i]) + " {\r\n";
}
std::string namespacesEnd = "";
for (int32_t i = packageTokens.size() - 1; i >= 0; i--) {
namespacesEnd += "} // END OF NAMESPACE " + packageTokens[i] + "\r\n";
}
namespacesStart = ::org::labcrypto::hottentot::generator::StringHelper::Trim(namespacesStart);
namespacesEnd = ::org::labcrypto::hottentot::generator::StringHelper::Trim(namespacesEnd);
std::string fields = "";
/*
* Serializarion
*/
uint32_t counter = 0;
std::stringstream serializationSS;
serializationSS << indent << indent << "uint32_t totalLength = 0;\r\n";
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
serializationSS << indent << indent << "uint32_t length" << counter << " = 0;\r\n";
// serializationSS << indent << indent << "unsigned char *data" << counter << " = ";
serializationSS << indent << indent <<
"::org::labcrypto::hottentot::runtime::HotPtr<unsigned char, true> ptr" << counter << ";\r\n";
if (TypeHelper::IsUDT(it->second->GetType()) && !TypeHelper::IsList(it->second->GetType())) {
serializationSS << indent << indent << "if (" <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) +
"_" << ") {\r\n";
serializationSS << indent << indent << indent << "ptr" << counter << " = ";
serializationSS <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall (
it->second->GetVariable()
) + "_";
serializationSS << "->";
serializationSS << "Serialize(&length" << counter << ");\r\n";
serializationSS << indent << indent << "}\r\n";
} else {
serializationSS << indent << indent << "ptr" << counter << " = ";
serializationSS <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall (
it->second->GetVariable()
) + "_";
serializationSS << ".";
serializationSS << "Serialize(&length" << counter << ");\r\n";
}
if (TypeHelper::IsFixedLength(it->second->GetType())) {
serializationSS << indent << indent << "totalLength += length" << counter << ";\r\n";
} else {
serializationSS << indent << indent << "if (length" << counter << " < 128) {\r\n";
serializationSS << indent << indent << indent << "totalLength += 1 + length" << counter << ";\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256) {\r\n";
serializationSS << indent << indent << indent << "totalLength += 2 + length" << counter << ";\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256 * 256) {\r\n";
serializationSS << indent << indent << indent << "totalLength += 3 + length" << counter << ";\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256 * 256 * 256) {\r\n";
serializationSS << indent << indent << indent << "totalLength += 4 + length" << counter << ";\r\n";
// serializationSS << indent << indent << "} else if (length" << counter << " < std::numeric_limits<uint32_t>::max()) {\r\n";
serializationSS << indent << indent << "} else {\r\n";
serializationSS << indent << indent << indent << "totalLength += 5 + length" << counter << ";\r\n";
serializationSS << indent << indent << "}\r\n";
}
counter++;
}
serializationSS << indent << indent << "unsigned char *data = new unsigned char[totalLength];\r\n";
serializationSS << indent << indent << "uint32_t c = 0;\r\n";
counter = 0;
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
if (!TypeHelper::IsFixedLength(it->second->GetType())) {
serializationSS << indent << indent << "if (length" << counter << " < 128) {\r\n";
serializationSS << indent << indent << indent << "data[c] = length" << counter << ";\r\n";
serializationSS << indent << indent << indent << "c += 1;\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256) {\r\n";
serializationSS << indent << indent << indent << "data[c] = 0x81;\r\n";
serializationSS << indent << indent << indent << "data[c + 1] = length" << counter << ";\r\n";
serializationSS << indent << indent << indent << "c += 2;\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256 * 256) {\r\n";
serializationSS << indent << indent << indent << "data[c] = 0x82;\r\n";
serializationSS << indent << indent << indent << "data[c + 1] = length" << counter << " / 256;\r\n";
serializationSS << indent << indent << indent << "data[c + 2] = length" << counter << " % 256;\r\n";
serializationSS << indent << indent << indent << "c += 3;\r\n";
serializationSS << indent << indent << "} else if (length" << counter << " < 256 * 256 * 256) {\r\n";
serializationSS << indent << indent << indent << "data[c] = 0x83;\r\n";
serializationSS << indent << indent << indent << "data[c + 1] = length" << counter << " / (256 * 256);\r\n";
serializationSS << indent << indent << indent << "data[c + 2] = (length" << counter << " - data[c + 1] * (256 * 256)) / 256;\r\n";
serializationSS << indent << indent << indent << "data[c + 3] = length" << counter << " % (256 * 256);\r\n";
serializationSS << indent << indent << indent << "c += 4;\r\n";
// serializationSS << indent << indent << "} else if (length" << counter << " < std::numeric_limits<uint32_t>::max()) {\r\n";
serializationSS << indent << indent << "} else {\r\n";
serializationSS << indent << indent << indent << "data[c] = 0x84;\r\n";
serializationSS << indent << indent << indent << "data[c + 1] = length" << counter << " / (256 * 256 * 256);\r\n";
serializationSS << indent << indent << indent << "data[c + 2] = (length" << counter << " - data[c + 1] * (256 * 256 * 256)) / (256 * 256);\r\n";
serializationSS << indent << indent << indent << "data[c + 3] = (length" << counter << " - data[c + 1] * (256 * 256 * 256) - data[c + 2] * (256 * 256)) / 256;\r\n";
serializationSS << indent << indent << indent << "data[c + 4] = length" << counter << " % (256 * 256 * 256);\r\n";
serializationSS << indent << indent << indent << "c += 5;\r\n";
serializationSS << indent << indent << "}\r\n";
}
serializationSS << indent << indent << "unsigned char *data" << counter << " = ptr" << counter << ".Get();\r\n";
serializationSS << indent << indent << "for (uint32_t i = 0; i < length" << counter << "; i++) {\r\n";
serializationSS << indent << indent << indent << "data[c++] = data" << counter << "[i];\r\n";
serializationSS << indent << indent << "}\r\n";
counter++;
}
serializationSS << indent << indent << "if (c != totalLength) {\r\n";
serializationSS << indent << indent << indent <<
"std::cout << \"Struct Serialization: Inconsistency in length of serialized byte array.\" << std::endl;\r\n";
serializationSS << indent << indent << indent << "exit(1);\r\n";
serializationSS << indent << indent << "};\r\n";
serializationSS << indent << indent << "if (length_ptr) {\r\n";
serializationSS << indent << indent << indent << "*length_ptr = totalLength;\r\n";
serializationSS << indent << indent << "}\r\n";
serializationSS << indent << indent << "return data;\r\n";
std::string serialization = serializationSS.str();
/*
* Deserialization
*/
bool hasAnyVariableLengthField = false;
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
if (!TypeHelper::IsFixedLength(it->second->GetType())) {
hasAnyVariableLengthField = true;
}
}
std::stringstream deserializationSS;
deserializationSS << indent << indent << "uint32_t c = 0";
if (hasAnyVariableLengthField) {
deserializationSS << ", elength = 0;\r\n";
} else {
deserializationSS << ";\r\n";
}
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
if (TypeHelper::IsFixedLength(it->second->GetType())) {
deserializationSS << indent << indent <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall (
it->second->GetVariable()
) + "_";
if (TypeHelper::IsUDT(it->second->GetType()) && !TypeHelper::IsList(it->second->GetType())) {
deserializationSS << "->";
} else {
deserializationSS << ".";
}
deserializationSS << "Deserialize(data + c, " <<
TypeHelper::GetFixedLength(it->second->GetType()) << ");\r\n";
deserializationSS << indent << indent << "c += " <<
TypeHelper::GetFixedLength(it->second->GetType()) << ";\r\n";
} else {
deserializationSS << indent << indent << "if ((data[c] & 0x80) == 0) {\r\n";
deserializationSS << indent << indent << indent << "elength = data[c];\r\n";
deserializationSS << indent << indent << indent << "c++;\r\n";
deserializationSS << indent << indent << "} else {\r\n";
deserializationSS << indent << indent << indent << "uint8_t ll = data[c] & 0x0f;\r\n";
deserializationSS << indent << indent << indent << "c++;\r\n";
deserializationSS << indent << indent << indent << "if (ll == 1) {\r\n";
deserializationSS << indent << indent << indent << indent << "elength = data[c];\r\n";
deserializationSS << indent << indent << indent << indent << "c += 1;\r\n";
deserializationSS << indent << indent << indent << "} else if (ll == 2) {\r\n";
deserializationSS << indent << indent << indent << indent << "elength = data[c] * 256 + data[c + 1];\r\n";
deserializationSS << indent << indent << indent << indent << "c += 2;\r\n";
deserializationSS << indent << indent << indent << "} else if (ll == 3) {\r\n";
deserializationSS << indent << indent << indent << indent << "elength = data[c] * 256 * 256 + data[c + 1] * 256 + data[c + 2];\r\n";
deserializationSS << indent << indent << indent << indent << "c += 3;\r\n";
deserializationSS << indent << indent << indent << "} else if (ll == 4) {\r\n";
deserializationSS << indent << indent << indent << indent << "elength = data[c] * 256 * 256 * 256 + data[c + 1] * 256 * 256 + data[c + 2] * 256 + data[c + 3];\r\n";
deserializationSS << indent << indent << indent << indent << "c += 4;\r\n";
deserializationSS << indent << indent << indent << "}\r\n";
deserializationSS << indent << indent << "}\r\n";
if (TypeHelper::IsUDT(it->second->GetType()) && !TypeHelper::IsList(it->second->GetType())) {
deserializationSS << indent << indent << "if (elength > 0) {\r\n";
deserializationSS << indent << indent << indent <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) <<
"_ = new " << TypeHelper::GetCCType(it->second->GetType(), ns) << ";\r\n";
deserializationSS << indent << indent << indent <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) + "_";
deserializationSS << "->";
deserializationSS << "Deserialize(data + c, elength);\r\n";
deserializationSS << indent << indent << "} else {\r\n";
deserializationSS << indent << indent << indent <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) +
"_ = NULL;\r\n";
deserializationSS << indent << indent << "}\r\n";
} else {
deserializationSS << indent << indent <<
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) + "_";
deserializationSS << ".";
deserializationSS << "Deserialize(data + c, elength);\r\n";
}
deserializationSS << indent << indent << "c += elength;\r\n";
}
}
deserializationSS << indent << indent << "if (c != length) {\r\n";
deserializationSS << indent << indent << indent <<
"std::cout << \"Struct Deserialization: Inconsistency in length of deserialized byte array.\" << std::endl;\r\n";
deserializationSS << indent << indent << indent << "exit(1);\r\n";
deserializationSS << indent << indent << "};\r\n";
std::string deserialization = deserializationSS.str();
/*
* Ctor assignments
*/
std::string copyCtorAssign = "";
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
copyCtorAssign += indent + indent +
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall (
it->second->GetVariable()
) + "_";
copyCtorAssign += " = other." +
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall (
it->second->GetVariable()
) + "_;\r\n";
}
std::string pointerCtorAssign = "";
for (std::map<uint32_t, ::org::labcrypto::hottentot::generator::Declaration*>::iterator it =
structt->declarations_.begin();
it != structt->declarations_.end();
++it) {
pointerCtorAssign += indent + indent +
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) + "_";
pointerCtorAssign += " = other->" +
::org::labcrypto::hottentot::generator::StringHelper::MakeCamelCaseFirstSmall(it->second->GetVariable()) +
"_;\r\n";
}
/*
* Filling templates with real values
*/
std::map<std::string, std::string> params;
params.insert(std::pair<std::string, std::string>("GENERATION_DATE",
::org::labcrypto::hottentot::generator::DateTimeHelper::GetCurrentDateTime()));
params.insert(std::pair<std::string, std::string>("FILENAME", structNameSnakeCase + ".cc"));
params.insert(std::pair<std::string, std::string>("NAMESPACES_START", namespacesStart));
params.insert(std::pair<std::string, std::string>("NAMESPACES_END", namespacesEnd));
params.insert(std::pair<std::string, std::string>("NAMESPACE","::" +
::org::labcrypto::hottentot::generator::StringHelper::Concat(
::org::labcrypto::hottentot::generator::StringHelper::Split(
structt->module_->GetPackage(), '.'), "::")));
params.insert(std::pair<std::string, std::string>("STRUCT_NAME", structNameCamelCaseFirstCapital));
params.insert(std::pair<std::string, std::string>("SNAKE_CASE_STRUCT_NAME", structNameSnakeCase));
params.insert(std::pair<std::string, std::string>("COPY_CTOR_ASSIGN", copyCtorAssign));
params.insert(std::pair<std::string, std::string>("POINTER_CTOR_ASSIGN", pointerCtorAssign));
params.insert(std::pair<std::string, std::string>("SERIALIZATION", serialization));
params.insert(std::pair<std::string, std::string>("DESERIALIZATION", deserialization));
params.insert(std::pair<std::string, std::string>("INDENT", indent));
std::string structCCTemplate = templates["struct_cc"];
for (std::map<std::string, std::string>::iterator it = params.begin();
it != params.end();
++it) {
structCCTemplate =
::org::labcrypto::hottentot::generator::StringHelper::Replace (
structCCTemplate,
"[[[" + it->first + "]]]",
it->second
);
}
/*
* Writing final results to files
*/
std::fstream f;
f.open(structCCFilePath.c_str(), std::fstream::out | std::fstream::binary);
f << structCCTemplate;
f.close();
}
}
}
}
}
}
| 54.869806 | 172 | 0.591024 | NTNAEEM |
5d680959dcb71b868b23f43aa85a4f3640be88cc | 1,545 | cc | C++ | src/camera.cc | paly2/VESPID | aebfc05b7f9d152a69a168b9e31685de1abe48fa | [
"MIT"
] | 1 | 2018-05-08T07:40:57.000Z | 2018-05-08T07:40:57.000Z | src/camera.cc | paly2/VESPID | aebfc05b7f9d152a69a168b9e31685de1abe48fa | [
"MIT"
] | null | null | null | src/camera.cc | paly2/VESPID | aebfc05b7f9d152a69a168b9e31685de1abe48fa | [
"MIT"
] | null | null | null | #include <raspicam/raspicam_cv.h>
#include <cxcore.hpp>
#include <SDL_thread.h>
#include <SDL_mutex.h>
#include "camera.hh"
#include "util.hh"
namespace Camera {
Camera::Camera() : m_newimage_tracker(CAMERA_CLASER_ONSUMERS) {
m_thread.launch("CameraThread");
}
bool Camera::newImage(int src_id) {
if (m_newimage_tracker.getSingle(src_id)) {
return true;
} else if (SDL_SemTryWait(m_thread.newimage_sem) != SDL_MUTEX_TIMEDOUT) {
m_newimage_tracker.setAllTrue();
return true;
}
return false;
}
void Camera::waitForImage(int src_id) {
if (m_newimage_tracker.getSingle(src_id))
return;
SDL_SemWait(m_thread.newimage_sem);
m_newimage_tracker.setAllTrue();
}
void Camera::retrieve(cv::Mat &image, int src_id) {
SDL_LockMutex(m_thread.mutex);
image = m_thread.image;
SDL_UnlockMutex(m_thread.mutex);
m_newimage_tracker.setSingleFalse(src_id);
}
void CameraThread::construct() {
mutex = SDL_CreateMutex();
newimage_sem = SDL_CreateSemaphore(0);
}
CameraThread::~CameraThread() {
destruct();
if (newimage_sem != NULL)
SDL_DestroySemaphore(newimage_sem);
if (mutex != NULL)
SDL_DestroyMutex(mutex);
}
void CameraThread::onStart() {
camera.set(CV_CAP_PROP_FORMAT, CV_8UC3);
if (!camera.open())
throw CameraException();
}
void CameraThread::onEnd() {
camera.release();
}
void CameraThread::loop() {
camera.grab();
SDL_LockMutex(mutex);
camera.retrieve(image);
SDL_UnlockMutex(mutex);
if (SDL_SemValue(newimage_sem) == 0)
SDL_SemPost(newimage_sem);
}
}
| 21.164384 | 75 | 0.716505 | paly2 |
5d68da9b3e976b64485e5338e00a22222106cd49 | 1,901 | cpp | C++ | Demonstration/ranges.cpp | XuhuaHuang/Embeded-Cpp-Course | e1f67238fa3ae21963f144e4861802700845ebd9 | [
"MIT"
] | null | null | null | Demonstration/ranges.cpp | XuhuaHuang/Embeded-Cpp-Course | e1f67238fa3ae21963f144e4861802700845ebd9 | [
"MIT"
] | null | null | null | Demonstration/ranges.cpp | XuhuaHuang/Embeded-Cpp-Course | e1f67238fa3ae21963f144e4861802700845ebd9 | [
"MIT"
] | null | null | null | /*****************************************************************//**
* \file ranges.cpp
* \brief Demonstration of ranges and views in C++ 20.
*
* $ g++ ranges.cpp -o exec -std=c++20 -Wall -Wextra -Wpedantic
* $ ./exec
*
* \author Xuhua Huang
* \date March 2022
*********************************************************************/
#include <iostream>
#include <iomanip>
#include <vector>
#include <ranges>
int main()
{
std::vector<std::int16_t> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
constexpr auto is_even = [&](int elem) -> bool { return elem % 2 == 0; };
constexpr auto square = [&](int elem) -> int { return elem * elem; };
/* with std::views::filter */
auto even_nums = vec | std::views::filter(is_even);
// view on stack with adaptor
for (const int16_t& i : even_nums) {
std::cout << i << " ";
}
std::cout << "\n"
<< "End execution with " << std::quoted("std::views::filter(is_even)") << "\n";
/* with std::ranges::filter_view */
for (const int16_t& i : std::ranges::filter_view(vec, is_even)) {
std::cout << i << " ";
}
std::cout << "\n"
<< "End execution with " << std::quoted("std::ranges::filter_view(vec, is_even)") << "\n";
/* with std::views::transform */
auto even_nums_squared = even_nums | std::views::transform(square);
// view on range-for loop
for (const int16_t& i : even_nums_squared) {
std::cout << i << " ";
}
std::cout << "\n"
<< "End execution with " << std::quoted("std::views::transform(square)") << "\n";
/* pipelining syntax */
auto output = vec
| std::views::filter(is_even)
| std::views::transform(square);
// view on range-for loop
for (const int16_t& i : output) {
std::cout << i << " ";
}
std::cout << "\n"
<< "End execution with pipeline syntax" << "\n";
return 0;
} | 31.163934 | 97 | 0.509732 | XuhuaHuang |
5d6fe65c08f398e3f90cb09b236e570fdce17ca2 | 6,612 | cpp | C++ | Graph/10numberOfOpsToMakeNetworkConnected.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | 1 | 2021-01-18T14:51:20.000Z | 2021-01-18T14:51:20.000Z | Graph/10numberOfOpsToMakeNetworkConnected.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | null | null | null | Graph/10numberOfOpsToMakeNetworkConnected.cpp | Coderangshu/450DSA | fff6cee65f75e5a0bb61d5fd8d000317a7736ca3 | [
"MIT"
] | null | null | null | class Solution {
public:
// Method 1: Using adjacency matrix and DFS/BFS to traverse for each nodes
// By traversing each nodes we find the components of a graph
// then check if atleast component-1 redundant edges are present or not
// if present we return ans as component-1 as that many edges are
// required to create MST of all components
map<int,vector<int>> makeAdj(int n,vector<vector<int>> connections){
map<int,vector<int>> adjList;
for(auto v:connections){
int node1 = v[0], node2 = v[1];
adjList[node1].push_back(node2);
adjList[node2].push_back(node1);
}
return adjList;
}
int DFS(map<int,vector<int>> adjList, int u, vector<bool> &visited){
int ans = 0;
if(visited[u]) return ans;
else{
ans++;
visited[u] = true;
for(auto e:adjList[u]){
if(!visited[e]) ans += DFS(adjList,e,visited);
}
}
return ans;
}
int makeConnected1(int n, vector<vector<int>>& connections) {
// total edges present in graph
int E = connections.size();
// if edges are less than n-1(i.e. no. of nodes-1) then no Minimum
// spanning tree(MST) is possible
if(E<n-1) return -1;
// Make adjacency list of graph
map<int,vector<int>> adjList = makeAdj(n,connections);
vector<bool> visited(n,false);
// components are the individual elements present in a graph
// components include standalone nodes, connected graph, group
// of connected graphs
// Example given graph below:
// 0-------1 3
// \ / 5
// \ / \
// \ / 4 \
// 2 6
// This graph has 4 components, (0,1,2),(3),(4),(5,6)
int components = 0;
for(int i=0;i<n;i++){
// If not visited node appears means it is a new component
if(!visited[i]){
components++;
// DFS will mark the rest nodes of the current component
// (if present) as visited
// Here DFS returns the no. of nodes in each component
DFS(adjList,i,visited);
}
}
// Redundant edges are the edges that which even if remove won't
// break the connetivity of nodes
// For example in above graph any of (0,1) or (0,2) or (1,2) edge can
// be removed without breaking the connectivity of the nodes
// Also removing any of the above edges makes that component a MST
// n-1 => minimum no.of edges to make MST of all nodes
// components-1 => minimum no. of edges to make MST of all components
// thus (n-1)-(components-1) gives the possible MSTs in graph without
// adding extra edges(i.e. the minimum no. of edges in graph to maintain
// the connectivity of nodes as present)
// In above graph this value is 3 means that (0,1,2) and (5,6) maintains
// connectivity as same with 3 edges
// Thus we get total redundant nodes as total nodes - ((n-1)-(components-1))
int redundantEdges = E-((n-1)-(components-1));
// If redundant nodes are less then total components no connection possible
if(redundantEdges<components-1) return -1;
return (components-1);
}
// Method 2: Using Union Find Algorithm
// In this method firstly all nodes are standalone then using parent vector
// we start connecting the nodes to their parents and thus to their ultimate
// parents, this way we can find the nodes joined to each other and the nodes
// that are standalone
// Keeps track of immediate parent of each node
// i.e. for connected nodes they will have same parent(may not be immediate),
// for standalone they will have themselves as the parent
vector<int> parent;
// Finds parent of given node recursively in parent vector as parent stores
// the immediated parent of each node so recursion is used to find the ultimate
// parent
int find(int v){
if(parent[v]!=v) return find(parent[v]);
else return v;
}
int makeConnected(int n, vector<vector<int>>& connections) {
// total edges present in graph
int E = connections.size();
// if edges are less than n-1(i.e. no. of nodes-1) then no Minimum
// spanning tree(MST) is possible
if(E<n-1) return -1;
// Initially we consider every node is standalone
for(int i=0;i<n;i++) parent.push_back(i);
for(auto connection:connections){
int node1 = connection[0], node2 = connection[1];
// Ultimate parent of both node is found
int p1 = find(node1), p2 = find(node2);
// If ultimate parent isn't same then, ultimate parent of
// node1 is assigned as ultimate parent of node2
// This is naive union set finding
// this procedure takes linear time to find the disjoint
// sets, using rank decreases T(n) to logarithmic scale
// and using rank along with path compression reduces T(n)
// to constant
if(p1!=p2) parent[p2] = parent[p1];
}
int component = 0;
// Counting the components, nodes with same parent belong to same component
// thus when node's parent found as same node denotes its a new component's
// parent, else when not equal means node has some other parent
for(int i=0;i<n;i++)
if(parent[i]==i) component++;
// Uncomment to see immediate parent of each node
// for(int i=0;i<n;i++) cout<<i<<" "<<parent[i]<<endl;
return component-1;
}
// For input:
// 12
// [[1,5],[1,7],[1,2],[1,4],[3,7],[4,7],[3,5],[0,6],[0,1],[0,4],[2,6],[0,3],[0,2]]
// The parent-node relation comes out to be:
// 0
// / \
// 3 6
// /
// 1
// / / \ \
// 5 7 2 4
// Thus the standalone nodes are 8,9,10,11
// Thus total components are 5
};
| 37.355932 | 86 | 0.540532 | Coderangshu |
5d728769fe9f89708bd27c52f961093fad491786 | 3,116 | cpp | C++ | intern/cycles/util/util_murmurhash.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 365 | 2015-02-10T15:10:55.000Z | 2022-03-03T15:50:51.000Z | intern/cycles/util/util_murmurhash.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 45 | 2015-01-09T15:34:20.000Z | 2021-10-05T14:44:23.000Z | intern/cycles/util/util_murmurhash.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 172 | 2015-01-25T15:16:53.000Z | 2022-01-31T08:25:36.000Z | /*
* Copyright 2018 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* This is taken from alShaders/Cryptomatte/MurmurHash3.h:
*
* MurmurHash3 was written by Austin Appleby, and is placed in the public
* domain. The author hereby disclaims copyright to this source code.
*/
#include <stdlib.h>
#include <string.h>
#include "util/util_algorithm.h"
#include "util/util_murmurhash.h"
#if defined(_MSC_VER)
# define ROTL32(x, y) _rotl(x, y)
# define ROTL64(x, y) _rotl64(x, y)
# define BIG_CONSTANT(x) (x)
#else
ccl_device_inline uint32_t rotl32(uint32_t x, int8_t r)
{
return (x << r) | (x >> (32 - r));
}
# define ROTL32(x, y) rotl32(x, y)
# define BIG_CONSTANT(x) (x##LLU)
#endif
CCL_NAMESPACE_BEGIN
/* Block read - if your platform needs to do endian-swapping or can only
* handle aligned reads, do the conversion here. */
ccl_device_inline uint32_t mm_hash_getblock32(const uint32_t *p, int i)
{
return p[i];
}
/* Finalization mix - force all bits of a hash block to avalanche */
ccl_device_inline uint32_t mm_hash_fmix32(uint32_t h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
uint32_t util_murmur_hash3(const void *key, int len, uint32_t seed)
{
const uint8_t *data = (const uint8_t *)key;
const int nblocks = len / 4;
uint32_t h1 = seed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
const uint32_t *blocks = (const uint32_t *)(data + nblocks * 4);
for (int i = -nblocks; i; i++) {
uint32_t k1 = mm_hash_getblock32(blocks, i);
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
}
const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);
uint32_t k1 = 0;
switch (len & 3) {
case 3:
k1 ^= tail[2] << 16;
ATTR_FALLTHROUGH;
case 2:
k1 ^= tail[1] << 8;
ATTR_FALLTHROUGH;
case 1:
k1 ^= tail[0];
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
}
h1 ^= len;
h1 = mm_hash_fmix32(h1);
return h1;
}
/* This is taken from the cryptomatte specification 1.0 */
float util_hash_to_float(uint32_t hash)
{
uint32_t mantissa = hash & ((1 << 23) - 1);
uint32_t exponent = (hash >> 23) & ((1 << 8) - 1);
exponent = max(exponent, (uint32_t)1);
exponent = min(exponent, (uint32_t)254);
exponent = exponent << 23;
uint32_t sign = (hash >> 31);
sign = sign << 31;
uint32_t float_bits = sign | exponent | mantissa;
float f;
memcpy(&f, &float_bits, sizeof(uint32_t));
return f;
}
CCL_NAMESPACE_END
| 24.535433 | 75 | 0.652439 | rbabari |
5d72959b82f3512f3036468d26d20a78356e82a3 | 1,517 | hpp | C++ | src/Numerical/RootFinding/RootFinder.hpp | wthrowe/spectre | 0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15 | [
"MIT"
] | null | null | null | src/Numerical/RootFinding/RootFinder.hpp | wthrowe/spectre | 0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15 | [
"MIT"
] | null | null | null | src/Numerical/RootFinding/RootFinder.hpp | wthrowe/spectre | 0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Declares function find_root_of_function
#pragma once
#include <functional>
#include <limits>
#include <boost/math/tools/toms748_solve.hpp>
/*! \ingroup Functors
* \brief Finds the root of the function f with the TOMS_748 method.
*
* \requires Function f be callable
*/
template <typename Function>
double find_root_of_function(Function f, const double lower_bound,
const double upper_bound,
const double absolute_tolerance,
const double relative_tolerance,
const size_t max_iterations = 100) {
boost::uintmax_t max_iter = max_iterations;
// This solver requires tol to be passed as a termination condition. This
// termination condition is equivalent to the convergence criteria used by the
// GSL
auto tol = [absolute_tolerance, relative_tolerance](double lhs, double rhs) {
return (fabs(lhs - rhs) <=
absolute_tolerance +
relative_tolerance * fmin(fabs(lhs), fabs(rhs)));
};
// Lower and upper bound are shifted by absolute tolerance so that the root
// find does not fail if upper or lower bound are equal to the root within
// tolerance
auto result = boost::math::tools::toms748_solve(
f, lower_bound - absolute_tolerance, upper_bound + absolute_tolerance,
tol, max_iter);
return result.first + 0.5 * (result.second - result.first);
}
| 35.27907 | 80 | 0.673698 | wthrowe |
5d734406d164dd56a50e9f6dc0ce43d148360e57 | 455 | hpp | C++ | server/include/tds/ip/address_v4.hpp | JMazurkiewicz/TinDox | 7f6c8e826683c875692fc97a3e89a4c5833dabf9 | [
"MIT"
] | null | null | null | server/include/tds/ip/address_v4.hpp | JMazurkiewicz/TinDox | 7f6c8e826683c875692fc97a3e89a4c5833dabf9 | [
"MIT"
] | null | null | null | server/include/tds/ip/address_v4.hpp | JMazurkiewicz/TinDox | 7f6c8e826683c875692fc97a3e89a4c5833dabf9 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <ostream>
namespace tds::ip {
class AddressV4 {
public:
static const AddressV4 any;
AddressV4();
explicit AddressV4(std::uint32_t address);
std::uint32_t as_integer() const;
bool operator==(const AddressV4&) const noexcept = default;
private:
std::uint32_t m_address;
};
std::ostream& operator<<(std::ostream& stream, AddressV4 address);
}
| 19.782609 | 70 | 0.632967 | JMazurkiewicz |
5d749b35c084fdd829b8b299179b46a3a95a6714 | 1,870 | hpp | C++ | external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp | mikosz/caramel-engine | 7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a | [
"MIT"
] | 1 | 2019-01-12T22:37:21.000Z | 2019-01-12T22:37:21.000Z | external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp | mikosz/caramel-engine | 7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a | [
"MIT"
] | null | null | null | external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp | mikosz/caramel-engine | 7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a | [
"MIT"
] | null | null | null | // Copyright Mikolaj Radwan 2018
// Distributed under the MIT license (See accompanying file LICENSE)
#ifndef CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__
#define CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__
#include <type_traits>
namespace caramel::poly::detail {
template <class FirstT, class SecondT, class = void>
class ConstexprPairStorage;
template <class FirstT, class SecondT>
class ConstexprPairStorage<FirstT, SecondT, std::enable_if_t<std::is_empty_v<FirstT> && std::is_empty_v<SecondT>>> {
public:
constexpr ConstexprPairStorage() = default;
constexpr ConstexprPairStorage(FirstT, SecondT)
{
}
constexpr FirstT first() const {
return FirstT{};
}
constexpr SecondT second() const {
return SecondT{};
}
};
template <class FirstT, class SecondT>
class ConstexprPairStorage<FirstT, SecondT, std::enable_if_t<std::is_empty_v<FirstT> && !std::is_empty_v<SecondT>>> {
public:
constexpr ConstexprPairStorage() = default;
constexpr ConstexprPairStorage(FirstT, SecondT s) :
second_(std::move(s))
{
}
constexpr FirstT first() const {
return FirstT{};
}
constexpr SecondT second() const {
return second_;
}
private:
SecondT second_;
};
template <class FirstT, class SecondT>
class ConstexprPair : public ConstexprPairStorage<FirstT, SecondT> {
public:
using First = FirstT;
using Second = SecondT;
constexpr ConstexprPair() = default;
constexpr ConstexprPair(First f, Second s) :
ConstexprPairStorage<FirstT, SecondT>(std::move(f), std::move(s))
{
}
};
template <class First, class Second>
constexpr auto makeConstexprPair(First f, Second s) {
return ConstexprPair<First, Second>{ std::move(f), std::move(s) };
}
constexpr auto first = [](auto p) { return p.first(); };
constexpr auto second = [](auto p) { return p.second(); };
} // namespace caramel::poly::detail
#endif /* CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__ */
| 21.744186 | 117 | 0.738503 | mikosz |
5d74f56001e927aab9dae7bfaf5bcd2e6d6e99ed | 554 | inl | C++ | GameEngine/GameEngine/src/Resources.inl | SamCooksley/GameEngine | 3c32eba545428c8aa3227abcb815d8d799ab92d9 | [
"Apache-2.0"
] | null | null | null | GameEngine/GameEngine/src/Resources.inl | SamCooksley/GameEngine | 3c32eba545428c8aa3227abcb815d8d799ab92d9 | [
"Apache-2.0"
] | null | null | null | GameEngine/GameEngine/src/Resources.inl | SamCooksley/GameEngine | 3c32eba545428c8aa3227abcb815d8d799ab92d9 | [
"Apache-2.0"
] | null | null | null | namespace engine {
template <class T>
std::shared_ptr<T> Resources::Load(const String & _path)
{
static_assert(std::is_base_of<Asset, T>::value, "Resource must be type of Object.");
auto res = Application::s_context->resources.find(_path);
if (res != Application::s_context->resources.end())
{
return std::dynamic_pointer_cast<T>(res->second);
}
auto asset = T::Load(_path);
if (!asset)
{
return nullptr;
}
Application::s_context->resources[_path] = asset;
return asset;
}
} // engine | 22.16 | 88 | 0.633574 | SamCooksley |
5d78dee24835002659c1dc33aa0a35839be4b565 | 3,773 | cpp | C++ | ngraph/core/reference/src/runtime/reference/tile.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 2 | 2020-11-18T14:14:06.000Z | 2020-11-28T04:55:57.000Z | ngraph/core/reference/src/runtime/reference/tile.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 30 | 2020-11-13T11:44:07.000Z | 2022-02-21T13:03:16.000Z | ngraph/core/reference/src/runtime/reference/tile.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 1 | 2020-12-18T15:47:45.000Z | 2020-12-18T15:47:45.000Z | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
#include "ngraph/check.hpp"
#include "ngraph/runtime/reference/tile.hpp"
using namespace ngraph;
namespace
{
/// \brief For each axis calculates the product of inner axes
/// If dims has shape (2, 3, 4) then for 2 (first axis) the inner axes would be (3, 4)
/// and for 3 (second axis) it would be (4)
/// If dims has shape(2, 3, 4) then the output vector would be (3 * 4, 4, 1)
/// The outermost axis is not used. For innermost axis it is always 1.
/// \param[in] dims Shape of the output
///
/// \return Vector containing calculated values for each axis.
std::vector<int64_t> create_pitches(const Shape& dims)
{
std::vector<int64_t> pitch;
pitch.resize(dims.size() - 1);
std::partial_sum(
dims.rbegin(), dims.rend() - 1, pitch.rbegin(), std::multiplies<int64_t>());
pitch.push_back(1);
return pitch;
}
}
void runtime::reference::tile(const char* arg,
char* out,
const Shape& in_shape,
const Shape& out_shape,
const size_t elem_size,
const std::vector<int64_t>& repeats)
{
Shape in_shape_expanded(in_shape);
in_shape_expanded.insert(in_shape_expanded.begin(), out_shape.size() - in_shape.size(), 1);
size_t block_size = 0;
int64_t num_repeats = 0;
const int input_rank = in_shape_expanded.size();
const int64_t last_dim = in_shape_expanded[input_rank - 1];
const std::vector<int64_t> pitches = create_pitches(out_shape);
const char* copy = nullptr;
std::vector<int64_t> indices(in_shape_expanded.size() - 1, 0);
size_t axis = indices.size();
// Copy and repeat data for innermost axis as many times as described in the repeats parameter
while (axis <= indices.size())
{
block_size = last_dim * elem_size;
memcpy(out, arg, block_size);
out += block_size;
arg += block_size;
copy = out - block_size;
num_repeats = repeats[input_rank - 1] - 1;
for (int64_t i = 0; i < num_repeats; ++i)
{
memcpy(out, copy, block_size);
out += block_size;
}
// Copy and repeat data for other axes as many times as described in the repeats parameter
while (axis-- != 0)
{
if (++indices[axis] != in_shape_expanded[axis])
{
axis = indices.size();
break;
}
indices[axis] = 0;
ptrdiff_t pitch = pitches[axis] * in_shape_expanded[axis];
block_size = pitch * elem_size;
copy = out - block_size;
num_repeats = repeats[axis] - 1;
for (int64_t i = 0; i < num_repeats; i++)
{
memcpy(out, copy, block_size);
out += block_size;
}
}
}
}
| 35.933333 | 98 | 0.571694 | szabi-luxonis |
5d7af16dd1a8576e69027603e04837e44e0044ba | 2,066 | cpp | C++ | GameServer/Source/MapRateInfo.cpp | sp3cialk/MU-S8EP2-Repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 10 | 2019-04-09T23:36:43.000Z | 2022-02-10T19:20:52.000Z | GameServer/Source/MapRateInfo.cpp | microvn/mu-s8ep2-repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 1 | 2019-09-25T17:12:36.000Z | 2019-09-25T17:12:36.000Z | GameServer/Source/MapRateInfo.cpp | microvn/mu-s8ep2-repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 9 | 2019-09-25T17:12:57.000Z | 2021-08-18T01:21:25.000Z | #include "stdafx.h"
#include "MapRateInfo.h"
#include "..\pugixml\pugixml.hpp"
#include "GameMain.h"
#include "MasterSkillSystem.h"
using namespace pugi;
MapRateInfo g_MapRateInfo;
MapRateInfo::MapRateInfo()
{
}
MapRateInfo::~MapRateInfo()
{
}
void MapRateInfo::Init()
{
this->m_RateInfo.clear();
if( this->m_RateInfo.capacity() > 0 )
{
std::vector<MapRateData>().swap(this->m_RateInfo);
}
}
void MapRateInfo::Load()
{
this->Init();
this->Read(gDirPath.GetNewPath(FILE_CUSTOM_MAPRATEINFO));
}
void MapRateInfo::Read(LPSTR File)
{
xml_document Document;
xml_parse_result Result = Document.load_file(File);
// ----
if( Result.status != status_ok )
{
MsgBox("[MapRateInfo] File %s not found!", File);
return;
}
// ----
xml_node MapRateInfo = Document.child("maprateinfo");
// ----
for( xml_node Node = MapRateInfo.child("map"); Node; Node = Node.next_sibling() )
{
MapRateData lpInfo;
lpInfo.MapNumber = Node.attribute("id").as_int();
lpInfo.ExpIncrease = Node.attribute("exp").as_int();
lpInfo.MasterExpIncrease = Node.attribute("masterexp").as_int();
lpInfo.MoneyIncrease = Node.attribute("money").as_int();
this->m_RateInfo.push_back(lpInfo);
}
}
float MapRateInfo::GetExp(short MapNumber)
{
for( int i = 0; i < this->m_RateInfo.size(); i++ )
{
if( this->m_RateInfo[i].MapNumber == MapNumber
&& this->m_RateInfo[i].ExpIncrease != 0 )
{
return this->m_RateInfo[i].ExpIncrease;
}
}
// ----
return gAddExperience;
}
float MapRateInfo::GetMasterExp(short MapNumber)
{
for( int i = 0; i < this->m_RateInfo.size(); i++ )
{
if( this->m_RateInfo[i].MapNumber == MapNumber
&& this->m_RateInfo[i].MasterExpIncrease != 0 )
{
return this->m_RateInfo[i].MasterExpIncrease;
}
}
// ----
return g_MasterExp.m_AddExp;
}
float MapRateInfo::GetMoney(short MapNumber)
{
for( int i = 0; i < this->m_RateInfo.size(); i++ )
{
if( this->m_RateInfo[i].MapNumber == MapNumber
&& this->m_RateInfo[i].MoneyIncrease != 0 )
{
return this->m_RateInfo[i].MoneyIncrease;
}
}
// ----
return gAddZen;
} | 20.868687 | 82 | 0.671346 | sp3cialk |
5d7c098b2c29bc5c4548848c198e47fd3d847a75 | 2,573 | cc | C++ | linux/flutter_jscore_plugin.cc | xuelongqy/flutter_jscore | dd8bf1153c7a8bfc78adfd24accb129740b8aa29 | [
"MIT"
] | 122 | 2020-02-26T06:27:46.000Z | 2022-03-25T08:37:54.000Z | linux/flutter_jscore_plugin.cc | xuelongqy/flutter_jscore | dd8bf1153c7a8bfc78adfd24accb129740b8aa29 | [
"MIT"
] | 11 | 2020-03-15T10:36:57.000Z | 2022-01-19T06:28:08.000Z | linux/flutter_jscore_plugin.cc | xuelongqy/flutter_jscore | dd8bf1153c7a8bfc78adfd24accb129740b8aa29 | [
"MIT"
] | 19 | 2020-03-10T15:30:13.000Z | 2021-11-23T14:52:25.000Z | #include "include/flutter_jscore/flutter_jscore_plugin.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <sys/utsname.h>
#include <cstring>
#define FLUTTER_JSCORE_PLUGIN(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj), flutter_jscore_plugin_get_type(), \
FlutterJscorePlugin))
struct _FlutterJscorePlugin {
GObject parent_instance;
};
G_DEFINE_TYPE(FlutterJscorePlugin, flutter_jscore_plugin, g_object_get_type())
// Called when a method call is received from Flutter.
static void flutter_jscore_plugin_handle_method_call(
FlutterJscorePlugin* self,
FlMethodCall* method_call) {
g_autoptr(FlMethodResponse) response = nullptr;
const gchar* method = fl_method_call_get_name(method_call);
if (strcmp(method, "getPlatformVersion") == 0) {
struct utsname uname_data = {};
uname(&uname_data);
g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version);
g_autoptr(FlValue) result = fl_value_new_string(version);
response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
fl_method_call_respond(method_call, response, nullptr);
}
static void flutter_jscore_plugin_dispose(GObject* object) {
G_OBJECT_CLASS(flutter_jscore_plugin_parent_class)->dispose(object);
}
static void flutter_jscore_plugin_class_init(FlutterJscorePluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = flutter_jscore_plugin_dispose;
}
static void flutter_jscore_plugin_init(FlutterJscorePlugin* self) {}
static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
gpointer user_data) {
FlutterJscorePlugin* plugin = FLUTTER_JSCORE_PLUGIN(user_data);
flutter_jscore_plugin_handle_method_call(plugin, method_call);
}
void flutter_jscore_plugin_register_with_registrar(FlPluginRegistrar* registrar) {
FlutterJscorePlugin* plugin = FLUTTER_JSCORE_PLUGIN(
g_object_new(flutter_jscore_plugin_get_type(), nullptr));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlMethodChannel) channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
"flutter_jscore",
FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(channel, method_call_cb,
g_object_ref(plugin),
g_object_unref);
g_object_unref(plugin);
}
| 36.239437 | 82 | 0.743101 | xuelongqy |
5d8351b210297e42b59a3a9f4d8cef979bbf537a | 497 | cpp | C++ | CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Trace/Data/Sound/CsData_TraceWeapon_SoundFire.h"
#include "CsWp.h"
const FName ICsData_TraceWeapon_SoundFire::Name = FName("ICsData_TraceWeapon_SoundFire");
UCsData_TraceWeapon_SoundFire::UCsData_TraceWeapon_SoundFire(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
}
const FName NCsWeapon::NTrace::NData::NSound::NFire::IFire::Name = FName("NCsWeapon::NTrace::NData::NSound::NFire::IFire"); | 45.181818 | 132 | 0.806841 | closedsum |
5d8526bbc9ca05b3cea9dc75b261669fe244cff1 | 6,971 | hpp | C++ | Code/Foundation/Common/Containers/SlotMap.hpp | WelderUpdates/WelderEngineRevamp | 1c665239566e9c7156926852f7952948d9286d7d | [
"MIT"
] | 3 | 2022-02-11T10:34:33.000Z | 2022-02-24T17:44:17.000Z | Code/Foundation/Common/Containers/SlotMap.hpp | WelderUpdates/WelderEngineRevamp | 1c665239566e9c7156926852f7952948d9286d7d | [
"MIT"
] | null | null | null | Code/Foundation/Common/Containers/SlotMap.hpp | WelderUpdates/WelderEngineRevamp | 1c665239566e9c7156926852f7952948d9286d7d | [
"MIT"
] | null | null | null | // MIT Licensed (see LICENSE.md).
#pragma once
#include "ContainerCommon.hpp"
#include "Memory/Allocator.hpp"
namespace Zero
{
/// Intrusive slot map container. Uses an array of slots combined with
// a unique id. Value Type MUST be a pointer.
template <typename keyType, typename dataType, typename slotPolicy, typename Allocator = DefaultAllocator>
class Slotmap : public AllocationContainer<Allocator>
{
public:
typedef dataType data_type;
typedef dataType* pointer;
typedef const dataType* const_pointer;
typedef dataType& reference;
typedef const dataType& const_reference;
typedef ptrdiff_t difference_type;
typedef Slotmap<keyType, dataType, slotPolicy> this_type;
typedef AllocationContainer<Allocator> base_type;
using base_type::mAllocator;
static const size_t InvalidSlotIndex = 0xFFFFFFFF;
pointer mData;
data_type mNextFree;
size_t mLargestSize;
size_t mMaxSize;
size_t mSize;
pointer mBegin;
pointer mEnd;
Slotmap()
{
mSize = 0;
mMaxSize = 0;
mLargestSize = 0;
mNextFree = nullptr;
mBegin = nullptr;
mEnd = nullptr;
mData = nullptr;
}
~Slotmap()
{
Deallocate();
}
// The range/iterator for this container may not be intuitive.
// We move over an array of slots just like iterating over
// array of object pointers. The difference is that
// invalid slots must be skipped over.
struct range
{
public:
typedef dataType value_type;
typedef data_type FrontResult;
range(pointer b, pointer e, this_type* owner) : begin(b), end(e), owner(owner)
{
}
bool Empty()
{
return begin == end;
}
// NOT a reference
data_type Front()
{
ErrorIf(Empty(), "Accessed empty range.");
return *begin;
}
void PopFront()
{
ErrorIf(Empty(), "Popped empty range.");
++begin;
// Skip over slots
begin = owner->SkipInvalid(begin, end);
}
range& All()
{
return *this;
}
const range& All() const
{
return *this;
}
private:
pointer begin;
pointer end;
this_type* owner;
};
range All()
{
pointer begin = PointerBegin();
pointer end = PointerEnd();
begin = SkipInvalid(begin, end);
return range(begin, end, this);
}
bool IsValid(data_type objPointer)
{
if (objPointer == nullptr)
return false;
size_t* valueTableBase = (size_t*)mBegin;
size_t* endOfValueTable = (size_t*)mEnd;
if ((size_t*)objPointer < endOfValueTable && (size_t*)objPointer >= valueTableBase)
return false;
else
return true;
}
data_type FindValue(keyType& id)
{
// Get the slot index from the id
size_t slotIndex = id.GetSlot();
if (slotIndex > mMaxSize)
return nullptr;
// Get the value from the table
data_type objPointer = mData[slotIndex];
// This value may be a part of the internal free slot list
// not a valid object pointer
if (IsValid(objPointer))
{
// The pointer is valid by it may point to a object
// that has replaced the deleted object in the slot.
// Check to see if the id is equal.
keyType& foundId = slotPolicy::AccessId(objPointer);
// Use operator equals for the id.
if (foundId == id)
{
// id and object match this is correct object
return objPointer;
}
}
return nullptr;
}
range Find(keyType& id)
{
if (mData == nullptr)
return range(PointerEnd(), PointerEnd(), this);
data_type value = FindValue(id);
if (value == nullptr)
return range(PointerEnd(), PointerEnd(), this);
else
{
pointer b = PointerBegin() + id.GetSlot();
return range(b, b + 1, this);
}
}
/// Is the container empty?
bool Empty()
{
return mSize == 0;
}
// How many elements are stored in the container.
size_t Size()
{
return mSize;
}
void Clear()
{
mSize = 0;
InitializeSlots(0, mMaxSize);
}
void Erase(keyType& eraseId)
{
// This slot index is now free
size_t slotIndex = eraseId.GetSlot();
ErrorIf(slotIndex > mMaxSize, "Invalid slot index.");
// Get the value from the table
data_type pointer = mData[slotIndex];
keyType& foundId = slotPolicy::AccessId(pointer);
if (foundId == eraseId)
{
AddToFreeList(eraseId.GetSlot());
// Reduce the size
--mSize;
#ifdef ZeroDebug
eraseId.GetSlot() = InvalidSlotIndex;
#endif
}
}
void Erase(data_type objectToErase)
{
keyType& eraseId = slotPolicy::AccessId(objectToErase);
return Erase(eraseId);
}
void Deallocate()
{
if (mMaxSize != 0)
{
mAllocator.Deallocate(mData, mMaxSize * sizeof(data_type));
mSize = 0;
mMaxSize = 0;
mData = nullptr;
mNextFree = nullptr;
}
}
// Must already have a unique id
void Insert(data_type object)
{
keyType& insertKey = slotPolicy::AccessId(object);
if (mNextFree == nullptr)
{
// Need more slots
size_t currentSize = mMaxSize;
size_t newMaxSize = mMaxSize * 2;
if (newMaxSize == 0)
newMaxSize = 4;
pointer newTable = (pointer)mAllocator.Allocate(newMaxSize * sizeof(dataType));
// Copy over old elements
if (mMaxSize != 0)
{
mAllocator.MemCopy(newTable, mData, mMaxSize * sizeof(dataType));
mAllocator.Deallocate(mData, mMaxSize * sizeof(data_type));
}
mData = newTable;
mMaxSize = newMaxSize;
InitializeSlots(currentSize, newMaxSize);
mBegin = mData;
mEnd = mData + mMaxSize;
}
size_t* base = (size_t*)mBegin;
size_t index = (size_t*)mNextFree - base;
mNextFree = *(data_type*)mNextFree;
insertKey.Slot = index;
mData[index] = object;
// increase the size
++mSize;
// increase the watermark size
if (mSize > mLargestSize)
mLargestSize = mSize;
}
private:
void InitializeSlots(size_t startIndex, size_t endIndex)
{
for (size_t i = startIndex; i < endIndex - 1; ++i)
{
data_type next = (data_type)&mData[i + 1];
mData[i] = next;
}
mData[endIndex - 1] = nullptr;
mNextFree = (data_type)&mData[startIndex];
}
void AddToFreeList(size_t slotIndex)
{
// Get a pointer to the slot
size_t* base = (size_t*)mBegin;
size_t* next = base + slotIndex;
// Set it to the current free and the next
// free to this one.
mData[slotIndex] = (data_type)mNextFree;
mNextFree = (data_type)next;
}
pointer SkipInvalid(pointer cur, pointer end)
{
// While not at the end of the list
// and the slot is invalid move the pointer forward.
while (cur != end && !IsValid(*cur))
++cur;
return cur;
}
pointer PointerBegin()
{
return mBegin;
}
pointer PointerEnd()
{
return mEnd;
}
// non copyable
Slotmap(const Slotmap& other);
void operator=(const Slotmap& other);
};
} // namespace Zero
| 22.130159 | 106 | 0.629465 | WelderUpdates |
5d8656a057e698ddcbb02984eabfb6bfd9f7493b | 3,334 | cpp | C++ | src/cpp/23. Merge k Sorted Lists.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 222 | 2018-09-25T08:46:31.000Z | 2022-02-07T12:33:42.000Z | src/cpp/23. Merge k Sorted Lists.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 1 | 2017-11-23T04:39:48.000Z | 2017-11-23T04:39:48.000Z | src/cpp/23. Merge k Sorted Lists.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 12 | 2018-10-05T03:16:05.000Z | 2020-12-19T04:25:33.000Z | /*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <common.hpp>
using std::priority_queue;
class Solution
{
public:
struct compare
{
bool operator()(const ListNode *l, const ListNode *r)
{
if (l == NULL || r == NULL)
{
return false;
}
return l->val > r->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.empty())
{
return NULL;
}
priority_queue<ListNode *, vector<ListNode *>, compare> q;
for (auto it : lists)
{
//这一句很重要
if (it != NULL)
{
q.push(it);
}
}
ListNode dummy(0);
ListNode *result = &dummy;
while (!q.empty())
{
result->next = q.top();
result = result->next;
q.pop();
if (result != NULL && result->next != NULL)
{
q.push(result->next);
}
}
return dummy.next;
}
};
/*
solution 1
merge the list one by one, each process is a `merge 2 sorted lists` problem.
time:O(N^2)
solution 2
手动比较每个链表的当前第一个节点,选一个最小的合并
time:O(Nk)
solution 3
use priority_queue
time:O(Nlogk) k个链表一共有N个结点
space:O(N) 主要分配priority_queue的内存
该方法可能比较耗内存
solution 4
divide and conquer
原理和solution 1一样,但是合并过程用分治
这里的分治的意思是每两个链表合并一次,合并之后产生的新链表再重复这样的操作
两个链表合并还是按照solution 2的逐个比较元素,时间复杂度为O(n)
k个链表,两两合并,最终的复杂度为O(logk)
time:O(NlogK)
space:O(1)
*/
class Solution4
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.empty())
return NULL;
while (lists.size() > 1)
{
lists.push_back(mergeTwoLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
//可以用递归,也可以用迭代
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
if (l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
#ifdef USE_GTEST
TEST(DSA, 23_mergeKLists)
{
ListNode *l1 = create_list(vector<int>{1, 3, 5, 7});
ListNode *l2 = create_list(vector<int>{2, 4, 8});
ListNode *l3 = create_list(vector<int>{6, 9, 10});
vector<ListNode *> lists1 = {l1, l2, l3};
ListNode *result = create_list(vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
Solution s1;
ListNode *res = s1.mergeKLists(lists1);
compare_lists(res, result);
free_list(res);
ListNode *l4 = create_list(vector<int>{1, 3, 5, 7});
ListNode *l5 = create_list(vector<int>{2, 4, 8});
ListNode *l6 = create_list(vector<int>{6, 9, 10});
vector<ListNode *> lists2 = {l4, l5, l6};
Solution4 s4;
res = s4.mergeKLists(lists2);
compare_lists(res, result);
free_list(res);
free_list(result);
}
#endif | 22.375839 | 98 | 0.538092 | yjjnls |
5d8b1ef2a7b3daea0e07e0339cec613f8146aaac | 1,043 | cc | C++ | src/graphics/lib/compute/tests/common/vk_sampler_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/graphics/lib/compute/tests/common/vk_sampler_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/graphics/lib/compute/tests/common/vk_sampler_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2019 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 "vk_sampler.h"
#include <gtest/gtest.h>
#include "vk_app_state.h"
class VkSamplerTest : public ::testing::Test {
protected:
void
SetUp() override
{
const vk_app_state_config_t config = { .device_config = {
.required_queues = VK_QUEUE_GRAPHICS_BIT,
} };
ASSERT_TRUE(vk_app_state_init(&app_, &config));
}
void
TearDown() override
{
vk_app_state_destroy(&app_);
}
VkDevice
device() const
{
return app_.d;
}
const VkAllocationCallbacks *
allocator() const
{
return app_.ac;
}
private:
vk_app_state_t app_;
};
TEST_F(VkSamplerTest, CreateLinearClampToEdge)
{
VkSampler sampler = vk_sampler_create_linear_clamp_to_edge(device(), allocator());
ASSERT_TRUE(sampler);
vkDestroySampler(device(), sampler, allocator());
}
| 20.86 | 86 | 0.650048 | allansrc |
5d8d483cde66fb01c4dea11926a7591741ad3c7c | 551 | hpp | C++ | library/ATF/__TEMP_WAIT_TOWER.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/__TEMP_WAIT_TOWER.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/__TEMP_WAIT_TOWER.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CMapData.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct __TEMP_WAIT_TOWER
{
unsigned int dwMasterSerial;
char byItemIndex;
CMapData *pMap;
float fPos[3];
unsigned int dwPushTime;
bool bComplete;
public:
__TEMP_WAIT_TOWER();
void ctor___TEMP_WAIT_TOWER();
};
#pragma pack(pop)
END_ATF_NAMESPACE
| 22.958333 | 108 | 0.662432 | lemkova |
5d8df60e036426cf937e606695a8f286a1d4e977 | 440 | cpp | C++ | code/planecalib_ui/UserInterfaceInfo.cpp | TANHAIYU/Self-calibration-using-Homography-Constraints | a3e7efa8cc3de1be1489891d81c0fb00b5b98777 | [
"BSD-3-Clause"
] | 2 | 2020-03-17T16:34:31.000Z | 2020-06-17T18:30:13.000Z | code/planecalib_ui/UserInterfaceInfo.cpp | TANHAIYU/planecalib | a3e7efa8cc3de1be1489891d81c0fb00b5b98777 | [
"BSD-3-Clause"
] | null | null | null | code/planecalib_ui/UserInterfaceInfo.cpp | TANHAIYU/planecalib | a3e7efa8cc3de1be1489891d81c0fb00b5b98777 | [
"BSD-3-Clause"
] | null | null | null | #include "UserInterfaceInfo.h"
namespace planecalib {
std::unique_ptr<UserInterfaceInfo> UserInterfaceInfo::gInstance;
UserInterfaceInfo &UserInterfaceInfo::Instance()
{
if(gInstance.get() == NULL)
gInstance.reset(new UserInterfaceInfo());
return *gInstance;
}
UserInterfaceInfo::UserInterfaceInfo()
{
memset(mKeyState, 0, sizeof(mKeyState));
memset(mSpecialKeyState, 0, sizeof(mSpecialKeyState));
}
} /* namespace planecalib */
| 20.952381 | 64 | 0.768182 | TANHAIYU |
5d90e81bf19edf19ce57074503f29e43b805b7df | 996 | hpp | C++ | include/ShaderAST/Expr/ExprQuestion.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 148 | 2018-10-11T16:51:37.000Z | 2022-03-26T13:55:08.000Z | include/ShaderAST/Expr/ExprQuestion.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 30 | 2019-11-30T11:43:07.000Z | 2022-01-25T21:09:47.000Z | include/ShaderAST/Expr/ExprQuestion.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 8 | 2020-04-17T13:18:30.000Z | 2021-11-20T06:24:44.000Z | /*
See LICENSE file in root folder
*/
#ifndef ___AST_ExprQuestion_H___
#define ___AST_ExprQuestion_H___
#pragma once
#include "Expr.hpp"
namespace ast::expr
{
class Question
: public Expr
{
public:
SDAST_API Question( type::TypePtr type
, ExprPtr ctrlExpr
, ExprPtr trueExpr
, ExprPtr falseExpr );
SDAST_API void accept( VisitorPtr vis )override;
inline Expr * getCtrlExpr()const
{
return m_ctrlExpr.get();
}
inline Expr * getTrueExpr()const
{
return m_trueExpr.get();
}
inline Expr * getFalseExpr()const
{
return m_falseExpr.get();
}
private:
ExprPtr m_ctrlExpr;
ExprPtr m_trueExpr;
ExprPtr m_falseExpr;
};
using QuestionPtr = std::unique_ptr< Question >;
inline QuestionPtr makeQuestion( type::TypePtr type
, ExprPtr ctrlExpr
, ExprPtr trueExpr
, ExprPtr falseExpr )
{
return std::make_unique< Question >( std::move( type )
, std::move( ctrlExpr )
, std::move( trueExpr )
, std::move( falseExpr ) );
}
}
#endif
| 17.172414 | 56 | 0.688755 | jarrodmky |
5d91476154f3b00ee3a98cb9c21e624303f71476 | 4,846 | hpp | C++ | include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Type namespace: Org.BouncyCastle.Math.EC.Rfc7748
namespace Org::BouncyCastle::Math::EC::Rfc7748 {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Math.EC.Rfc7748.X448Field
// [CLSCompliantAttribute] Offset: DE2034
class X448Field : public ::Il2CppObject {
public:
// Creating value type constructor for type: X448Field
X448Field() noexcept {}
// static public System.Void Add(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z)
// Offset: 0x1D0E704
static void Add(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z);
// static public System.Void Carry(System.UInt32[] z)
// Offset: 0x1D0E784
static void Carry(::Array<uint>* z);
// static public System.Void CMov(System.Int32 cond, System.UInt32[] x, System.Int32 xOff, System.UInt32[] z, System.Int32 zOff)
// Offset: 0x1D0E910
static void CMov(int cond, ::Array<uint>* x, int xOff, ::Array<uint>* z, int zOff);
// static public System.Void CNegate(System.Int32 negate, System.UInt32[] z)
// Offset: 0x1D0E99C
static void CNegate(int negate, ::Array<uint>* z);
// static public System.Void Copy(System.UInt32[] x, System.Int32 xOff, System.UInt32[] z, System.Int32 zOff)
// Offset: 0x1D0EDCC
static void Copy(::Array<uint>* x, int xOff, ::Array<uint>* z, int zOff);
// static public System.UInt32[] Create()
// Offset: 0x1D0E9EC
static ::Array<uint>* Create();
// static public System.Void Encode(System.UInt32[] x, System.Byte[] z, System.Int32 zOff)
// Offset: 0x1D0EE48
static void Encode(::Array<uint>* x, ::Array<uint8_t>* z, int zOff);
// static private System.Void Encode24(System.UInt32 n, System.Byte[] bs, System.Int32 off)
// Offset: 0x1D0EF88
static void Encode24(uint n, ::Array<uint8_t>* bs, int off);
// static private System.Void Encode32(System.UInt32 n, System.Byte[] bs, System.Int32 off)
// Offset: 0x1D0EFF8
static void Encode32(uint n, ::Array<uint8_t>* bs, int off);
// static private System.Void Encode56(System.UInt32[] x, System.Int32 xOff, System.Byte[] bs, System.Int32 off)
// Offset: 0x1D0EF0C
static void Encode56(::Array<uint>* x, int xOff, ::Array<uint8_t>* bs, int off);
// static public System.Void Inv(System.UInt32[] x, System.UInt32[] z)
// Offset: 0x1D0F084
static void Inv(::Array<uint>* x, ::Array<uint>* z);
// static public System.Int32 IsZero(System.UInt32[] x)
// Offset: 0x1D0FC8C
static int IsZero(::Array<uint>* x);
// static public System.Void Mul(System.UInt32[] x, System.UInt32 y, System.UInt32[] z)
// Offset: 0x1D0FCEC
static void Mul(::Array<uint>* x, uint y, ::Array<uint>* z);
// static public System.Void Mul(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z)
// Offset: 0x1D0F324
static void Mul(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z);
// static public System.Void Normalize(System.UInt32[] z)
// Offset: 0x1D0FEF0
static void Normalize(::Array<uint>* z);
// static public System.Void One(System.UInt32[] z)
// Offset: 0x1D0FFD4
static void One(::Array<uint>* z);
// static private System.Void PowPm3d4(System.UInt32[] x, System.UInt32[] z)
// Offset: 0x1D0F0DC
static void PowPm3d4(::Array<uint>* x, ::Array<uint>* z);
// static private System.Void Reduce(System.UInt32[] z, System.Int32 x)
// Offset: 0x1D0FF1C
static void Reduce(::Array<uint>* z, int x);
// static public System.Void Sqr(System.UInt32[] x, System.UInt32[] z)
// Offset: 0x1D10030
static void Sqr(::Array<uint>* x, ::Array<uint>* z);
// static public System.Void Sqr(System.UInt32[] x, System.Int32 n, System.UInt32[] z)
// Offset: 0x1D0F2D8
static void Sqr(::Array<uint>* x, int n, ::Array<uint>* z);
// static public System.Void Sub(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z)
// Offset: 0x1D0EA38
static void Sub(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z);
// static public System.Void SubOne(System.UInt32[] z)
// Offset: 0x1D105EC
static void SubOne(::Array<uint>* z);
// static public System.Void Zero(System.UInt32[] z)
// Offset: 0x1D1063C
static void Zero(::Array<uint>* z);
}; // Org.BouncyCastle.Math.EC.Rfc7748.X448Field
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Math::EC::Rfc7748::X448Field*, "Org.BouncyCastle.Math.EC.Rfc7748", "X448Field");
| 52.673913 | 133 | 0.647751 | darknight1050 |
5d932fae9acbe884480123b136f824626fa03bda | 17,557 | cpp | C++ | library/uapki/src/api/verify.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | library/uapki/src/api/verify.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | library/uapki/src/api/verify.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, The UAPKI Project Authors.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "api-json-internal.h"
#include "content-info.h"
#include "global-objects.h"
#include "parson-helper.h"
#include "store-utils.h"
#include "time-utils.h"
#include "uapki-errors.h"
#include "verify-signer-info.h"
#include "verify-utils.h"
#include <vector>
#undef FILE_MARKER
#define FILE_MARKER "api/verify.c"
#define DEBUG_OUTCON(expression)
#ifndef DEBUG_OUTCON
#define DEBUG_OUTCON(expression) expression
#endif
using namespace std;
typedef struct VerifyOptions_S {
bool encodeCert;
bool validateCertByOCSP;
bool validateCertByCRL;
VerifyOptions_S (void)
: encodeCert(true), validateCertByOCSP(false), validateCertByCRL(false) {}
} VerifyOptions;
static int decode_signed_data (const ByteArray* baEncoded, SignedData_t** signedData, ByteArray** baEncapContent)
{
int ret = RET_OK;
ContentInfo_t* cinfo = nullptr;
SignedData_t* sdata = nullptr;
long version = 0;
CHECK_NOT_NULL(cinfo = (ContentInfo_t*)asn_decode_ba_with_alloc(get_ContentInfo_desc(), baEncoded));
DO(cinfo_get_signed_data(cinfo, &sdata));
DO(asn_INTEGER2long(&sdata->version, &version));
if ((version < 1) || (version > 5) || (version == 2)) {
SET_ERROR(RET_UAPKI_INVALID_STRUCT_VERSION);
}
if (sdata->signerInfos.list.count == 0) {
SET_ERROR(RET_UAPKI_INVALID_STRUCT);
}
if (sdata->encapContentInfo.eContent != nullptr) {
DO(asn_OCTSTRING2ba(sdata->encapContentInfo.eContent, baEncapContent));
}
*signedData = sdata;
sdata = nullptr;
cleanup:
asn_free(get_ContentInfo_desc(), cinfo);
asn_free(get_SignedData_desc(), sdata);
return ret;
}
static int get_digest_algorithms (SignedData_t* signedData, vector<char*>& dgstAlgos)
{
int ret = RET_OK;
char* s_dgstalgo = nullptr;
if (signedData->digestAlgorithms.list.count == 0) {
SET_ERROR(RET_UAPKI_INVALID_STRUCT);
}
for (size_t i = 0; i < signedData->digestAlgorithms.list.count; i++) {
DO(asn_oid_to_text(&signedData->digestAlgorithms.list.array[i]->algorithm, &s_dgstalgo));
dgstAlgos.push_back(s_dgstalgo);
s_dgstalgo = nullptr;
}
cleanup:
if (ret != RET_OK) {
for (size_t i = 0; i < dgstAlgos.size(); i++) {
::free(dgstAlgos[i]);
}
dgstAlgos.clear();
}
::free(s_dgstalgo);
return ret;
}
static int get_certs_to_store (SignedData_t* signedData, vector<const CerStore::Item*>& certs)
{
int ret = RET_OK;
CerStore* cer_store = nullptr;
ByteArray* ba_cert = nullptr;
cer_store = get_cerstore();
if (!cer_store) {
SET_ERROR(RET_UAPKI_GENERAL_ERROR);
}
DEBUG_OUTCON(printf("get_certs_to_store(), count certs in cert-store (before): %d\n", (int)cer_store->count()));
if (signedData->certificates) {
if (signedData->certificates->list.count == 0) {
SET_ERROR(RET_UAPKI_INVALID_STRUCT);
}
for (size_t i = 0; i < signedData->certificates->list.count; i++) {
bool is_unique;
const CerStore::Item* cer_item = nullptr;
DO(asn_encode_ba(get_CertificateChoices_desc(), signedData->certificates->list.array[i], &ba_cert));
DO(cer_store->addCert(ba_cert, false, false, false, is_unique, &cer_item));
ba_cert = nullptr;
certs.push_back(cer_item);
}
}
DEBUG_OUTCON(printf("get_certs_to_store(), count certs in cert-store (after) : %d\n", (int)cer_store->count()));
cleanup:
ba_free(ba_cert);
return ret;
}
static int result_set_content (JSON_Object* joContent, const OBJECT_IDENTIFIER_t* eContentType, ByteArray* baContent)
{
if (joContent == nullptr) return RET_UAPKI_GENERAL_ERROR;
int ret = RET_OK;
char* s_contype = nullptr;
DO(asn_oid_to_text(eContentType, &s_contype));
ret = (json_object_set_string(joContent, "type", s_contype) == JSONSuccess) ? RET_OK : RET_UAPKI_GENERAL_ERROR;
if ((ret == RET_OK) && (baContent != nullptr)) {
DO(json_object_set_base64(joContent, "bytes", baContent));
}
cleanup:
free(s_contype);
return ret;
}
static int result_set_list_attrs (JSON_Object* joResult, const char* key, const vector<AttrItem>& attrItems)
{
if (attrItems.empty()) return RET_OK;
int ret = RET_OK;
json_object_set_value(joResult, key, json_value_init_array());
JSON_Array* ja_attrs = json_object_get_array(joResult, key);
for (size_t i = 0; i < attrItems.size(); i++) {
const AttrItem& attr_item = attrItems[i];
json_array_append_value(ja_attrs, json_value_init_object());
JSON_Object* jo_attr = json_array_get_object(ja_attrs, i);
DO_JSON(json_object_set_string(jo_attr, "type", attr_item.attrType));
DO_JSON(json_object_set_base64(jo_attr, "bytes", attr_item.baAttrValue));
}
cleanup:
return ret;
}
static int parse_attr_sigpolicy (JSON_Object* joResult, const ByteArray* baEncoded)
{
int ret = RET_OK;
SignaturePolicyIdentifier_t* spi = nullptr;
char* s_policyid = nullptr;
CHECK_NOT_NULL(spi = (SignaturePolicyIdentifier_t*)asn_decode_ba_with_alloc(get_SignaturePolicyIdentifier_desc(), baEncoded));
if (spi->present == SignaturePolicyIdentifier_PR_signaturePolicyId) {
DO(asn_oid_to_text(&spi->choice.signaturePolicyId.sigPolicyId, &s_policyid));
DO_JSON(json_object_set_string(joResult, "sigPolicyId", s_policyid));
}
cleanup:
asn_free(get_SignaturePolicyIdentifier_desc(), spi);
free(s_policyid);
return ret;
}
static int result_set_parsed_signedattrs (JSON_Object* joResult, const vector<AttrItem>& attrItems)
{
int ret = RET_OK;
for (auto& it : attrItems) {
if (strcmp(it.attrType, OID_PKCS9_SIG_POLICY_ID) == 0) {
DO_JSON(json_object_set_value(joResult, "signaturePolicy", json_value_init_object()));
DO(parse_attr_sigpolicy(json_object_get_object(joResult, "signaturePolicy"), it.baAttrValue));
}
}
cleanup:
return ret;
}
static int result_set_parsed_unsignedattrs (JSON_Object* joResult, const vector<AttrItem>& attrItems)
{
int ret = RET_OK;
//TODO: here process unsigned attrs
//for (auto& it : attrItems) {
//if (strcmp(it.attrType, OID_any_attr) == 0) {}
//}
//cleanup:
return ret;
}
static void parse_verify_options (JSON_Object* joOptions, VerifyOptions& options)
{
options.encodeCert = ParsonHelper::jsonObjectGetBoolean(joOptions, "encodeCert", true);
options.validateCertByOCSP = ParsonHelper::jsonObjectGetBoolean(joOptions, "validateCertByOCSP", false);
options.validateCertByCRL = ParsonHelper::jsonObjectGetBoolean(joOptions, "validateCertByCRL", false);
}
static int attr_timestamp_to_json (JSON_Object* joSignerInfo, const char* attrName, const AttrTimeStamp* attrTS)
{
int ret = RET_OK;
JSON_Object* jo_attrts = nullptr;
if (attrTS == nullptr) return ret;
DO_JSON(json_object_set_value(joSignerInfo, attrName, json_value_init_object()));
jo_attrts = json_object_get_object(joSignerInfo, attrName);
DO_JSON(json_object_set_string(jo_attrts, "genTime", TimeUtils::mstimeToFormat(attrTS->msGenTime).c_str()));
DO_JSON(json_object_set_string(jo_attrts, "policyId", attrTS->policy));
DO_JSON(json_object_set_string(jo_attrts, "hashAlgo", attrTS->hashAlgo));
DO_JSON(json_object_set_base64(jo_attrts, "hashedMessage", attrTS->baHashedMessage));
DO_JSON(json_object_set_string(jo_attrts, "statusDigest", SIGNATURE_VERIFY::toStr(attrTS->statusDigest)));
//TODO: need impl "statusSign" (statusSignedData)
cleanup:
return ret;
}
static int verify_cms (const ByteArray* baSignature, const ByteArray* baContent, const bool isDigest,
JSON_Object* joOptions, JSON_Object* joResult)
{
int ret = RET_OK;
CerStore* cer_store = nullptr;
VerifyOptions options;
uint32_t version = 0;
SignedData_t* sdata = nullptr;
ByteArray* ba_content = nullptr;
const ByteArray* ref_content = nullptr;
vector<char*> dgst_algos;
vector<const CerStore::Item*> certs;
vector<const VerifyInfo*> verify_infos;
JSON_Array* ja = nullptr;
JSON_Object* jo = nullptr;
cer_store = get_cerstore();
if (!cer_store) {
SET_ERROR(RET_UAPKI_GENERAL_ERROR);
}
parse_verify_options(joOptions, options);
DO(decode_signed_data(baSignature, &sdata, &ba_content));
ref_content = (ba_content != nullptr) ? ba_content : baContent;
DO(get_digest_algorithms(sdata, dgst_algos));
DO(get_certs_to_store(sdata, certs));
// For each signerInfo
for (size_t i = 0; i < sdata->signerInfos.list.count; i++) {
VerifyInfo* verify_info = new VerifyInfo();
if (!verify_info) {
SET_ERROR(RET_UAPKI_GENERAL_ERROR);
}
DO(verify_signer_info(sdata->signerInfos.list.array[0], dgst_algos, ref_content, isDigest, verify_info));
verify_infos.push_back(verify_info);
}
// Out param 'content', object
DO_JSON(json_object_set_value(joResult, "content", json_value_init_object()));
DO(result_set_content(json_object_get_object(joResult, "content"), &sdata->encapContentInfo.eContentType, ba_content));
// Out param 'certIds' (certificates), array
DO_JSON(json_object_set_value(joResult, "certIds", json_value_init_array()));
ja = json_object_get_array(joResult, "certIds");
for (auto& it: certs) {
DO_JSON(json_array_append_base64(ja, it->baCertId));
}
// Out param 'signatureInfos', array
DO_JSON(json_object_set_value(joResult, "signatureInfos", json_value_init_array()));
ja = json_object_get_array(joResult, "signatureInfos");
for (size_t i = 0; i < verify_infos.size(); i++) {
bool is_valid = false;
DO_JSON(json_array_append_value(ja, json_value_init_object()));
jo = json_array_get_object(ja, i);
const VerifyInfo* verify_info = verify_infos[i];
DO(json_object_set_base64(jo, "signerCertId", verify_info->cerStoreItem->baCertId));
is_valid = (verify_info->statusSignature == SIGNATURE_VERIFY::STATUS::VALID)
&& (verify_info->statusMessageDigest == SIGNATURE_VERIFY::STATUS::VALID);
if (is_valid && (verify_info->statusEssCert != SIGNATURE_VERIFY::STATUS::NOT_PRESENT)) {
is_valid = (verify_info->statusEssCert == SIGNATURE_VERIFY::STATUS::VALID);
}
if (is_valid && verify_info->contentTS) {
is_valid = (verify_info->contentTS->statusDigest == SIGNATURE_VERIFY::STATUS::VALID);
//TODO: verify_info->contentTS->statusSign
}
if (is_valid && verify_info->signatureTS) {
is_valid = (verify_info->signatureTS->statusDigest == SIGNATURE_VERIFY::STATUS::VALID);
//TODO: verify_info->signatureTS->statusSign
}
SIGNATURE_VALIDATION::STATUS status = is_valid ? SIGNATURE_VALIDATION::STATUS::TOTAL_VALID : SIGNATURE_VALIDATION::STATUS::TOTAL_FAILED;
//TODO: check options.validateCertByCRL and options.validateCertByOCSP
// added status SIGNATURE_VALIDATION::STATUS::INDETERMINATE
DO_JSON(json_object_set_string(jo, "status", SIGNATURE_VALIDATION::toStr(status)));
DO_JSON(json_object_set_string(jo, "statusSignature", SIGNATURE_VERIFY::toStr(verify_info->statusSignature)));
DO_JSON(json_object_set_string(jo, "statusMessageDigest", SIGNATURE_VERIFY::toStr(verify_info->statusMessageDigest)));
DO_JSON(json_object_set_string(jo, "statusEssCert", SIGNATURE_VERIFY::toStr(verify_info->statusEssCert)));
if (verify_info->signingTime > 0) {
DO_JSON(json_object_set_string(jo, "signingTime", TimeUtils::mstimeToFormat(verify_info->signingTime).c_str()));
}
DO(result_set_parsed_signedattrs(jo, verify_info->signedAttrs));
DO(result_set_parsed_unsignedattrs(jo, verify_info->unsignedAttrs));
DO_JSON(attr_timestamp_to_json(jo, "contentTS", verify_info->contentTS));
DO_JSON(attr_timestamp_to_json(jo, "signatureTS", verify_info->signatureTS));
DO(result_set_list_attrs(jo, "signedAttributes", verify_info->signedAttrs));
DO(result_set_list_attrs(jo, "unsignedAttributes", verify_info->unsignedAttrs));
}
cleanup:
for (size_t i = 0; i < dgst_algos.size(); i++) {
::free(dgst_algos[i]);
}
for (size_t i = 0; i < verify_infos.size(); i++) {
delete verify_infos[i];
}
asn_free(get_SignedData_desc(), sdata);
ba_free(ba_content);
return ret;
}
static int verify_raw (const ByteArray* baSignature, const ByteArray* baContent, const bool isDigest,
JSON_Object* joSignParams, JSON_Object* joSignerPubkey, JSON_Object* joResult)
{
int ret = RET_OK;
CerStore::Item* cer_parsed = nullptr;
ByteArray* ba_certid = nullptr;
ByteArray* ba_encoded = nullptr;
ByteArray* ba_spki = nullptr;
const CerStore::Item* cer_item = nullptr;
const char* s_signalgo = nullptr;
SIGNATURE_VERIFY::STATUS status_sign = SIGNATURE_VERIFY::STATUS::UNDEFINED;
bool is_digitalsign = true;
s_signalgo = json_object_get_string(joSignParams, "signAlgo");
if (s_signalgo == nullptr) return RET_UAPKI_INVALID_PARAMETER;
ba_encoded = json_object_get_base64(joSignerPubkey, "certificate");
if (ba_encoded) {
DO(CerStore::parseCert(ba_encoded, &cer_parsed));
ba_encoded = nullptr;
cer_item = (const CerStore::Item*)cer_parsed;
}
else {
ba_certid = json_object_get_base64(joSignerPubkey, "certId");
if (ba_certid) {
CerStore* cer_store = get_cerstore();
if (!cer_store) {
SET_ERROR(RET_UAPKI_GENERAL_ERROR);
}
DO(cer_store->getCertByCertId(ba_certid, &cer_item));
}
else {
ba_spki = json_object_get_base64(joSignerPubkey, "spki");
if (!ba_spki) {
SET_ERROR(RET_UAPKI_INVALID_PARAMETER);
}
}
}
ret = verify_signature(s_signalgo, baContent, isDigest,
(cer_item != nullptr) ? cer_item->baSPKI : ba_spki, baSignature);
switch (ret) {
case RET_OK:
status_sign = SIGNATURE_VERIFY::STATUS::VALID;
break;
case RET_VERIFY_FAILED:
status_sign = SIGNATURE_VERIFY::STATUS::INVALID;
break;
default:
status_sign = SIGNATURE_VERIFY::STATUS::FAILED;
}
DO_JSON(json_object_set_string(joResult, "statusSignature", SIGNATURE_VERIFY::toStr(status_sign)));
ret = RET_OK;
cleanup:
delete cer_parsed;
ba_free(ba_certid);
ba_free(ba_encoded);
ba_free(ba_spki);
return ret;
}
int uapki_verify_signature (JSON_Object* joParams, JSON_Object* joResult)
{
int ret = RET_OK;
ByteArray* ba_content = nullptr;
ByteArray* ba_signature = nullptr;
JSON_Object* jo_options = nullptr;
JSON_Object* jo_signature = nullptr;
JSON_Object* jo_signparams = nullptr;
JSON_Object* jo_signerpubkey = nullptr;
bool is_digest, is_raw = false;
jo_options = json_object_get_object(joParams, "options");
jo_signature = json_object_get_object(joParams, "signature");
ba_signature = json_object_get_base64(jo_signature, "bytes");
ba_content = json_object_get_base64(jo_signature, "content");
is_digest = ParsonHelper::jsonObjectGetBoolean(jo_signature, "isDigest", false);
if (!ba_signature) {
SET_ERROR(RET_UAPKI_INVALID_PARAMETER);
}
jo_signparams = json_object_get_object(joParams, "signParams");
jo_signerpubkey = json_object_get_object(joParams, "signerPubkey");
is_raw = (jo_signparams != nullptr) || (jo_signerpubkey != nullptr);
if (!is_raw) {
DO(verify_cms(ba_signature, ba_content, is_digest, jo_options, joResult));
}
else {
if ((ba_content == nullptr) || (jo_signparams == nullptr) || (jo_signerpubkey == nullptr)) {
SET_ERROR(RET_UAPKI_INVALID_PARAMETER);
}
DO(verify_raw(ba_signature, ba_content, is_digest, jo_signparams, jo_signerpubkey, joResult));
}
cleanup:
ba_free(ba_content);
ba_free(ba_signature);
return ret;
}
| 37.040084 | 144 | 0.695734 | DJm00n |
5d942c48f1e2de0e10c3373c5f87dc55178b15b6 | 8,658 | hpp | C++ | src/core/storage/query_engine/algorithm/ec_sort.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/core/storage/query_engine/algorithm/ec_sort.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/core/storage/query_engine/algorithm/ec_sort.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef SFRAME_ALGORITHM_EC_SORT_HPP
#define SFRAME_ALGORITHM_EC_SORT_HPP
#include <vector>
#include <memory>
namespace turi {
class sframe;
namespace query_eval {
struct planner_node;
/**
* \ingroup sframe_query_engine
* \addtogroup Algorithms Algorithms
* \{
*/
/**
* External Memory Columnar Sort. See \ref ec_sort for details.
*
*
* The current sort algorithm (in \ref turi::query_eval::sort) implementation
* has lasted us a while and it is time to think about something better.
*
* A brief overview of the old sort algorithm
* ==========================================
*
* The old algorithm implemented in \ref sort essentially a bucket sort.
*
* Pivot generation
* ----------------
* - A fraction of random elements is selected on the key column filling a
* quantile sketch
* - The quantile sketch is used to select a set of K-1 pivots (hence K buckets)
* - Each bucket is associated with an output file
*
* Scatter
* -------
* - The entire sframe is materialized to a stream which consumes the sframe row
* by row.
* - For each row, the key is compared to the pivots, and the row is written
* row-wise into the bucket.
* - This process can be done in parallel
*
* Sort
* ----
* - Each bucket is loaded into memory and an in memory quicksort is performed.
* - This process can be done in parallel
*
* Advantages
* ----------
*
* 1. Exactly 2x write amplification. Every tuple is only written exactly twice.
* (But see Issue 1)
* 2. Works with Lazy sframe sources
*
* Issues
* ------
*
* 1. Much more than 2x write amplification.Though the buckets are not that well
* compressed since they are done row-wise. So while every tuple is written
* exactly twice, the effective \#bytes written can be *much much* larger.
*
* 2. Wide reads of SFrames are slow. If the SFrame to be sorted has a few hundred
* columns on disk, things break.
*
* 3. Memory limits are hard to control. Image columns or very big dictionaries /
* lists are problematic.
*
* The Proposed algorithm
* =======================
* Firstly, we assume that the sframe is read one value at a time, i.e.
* we get a stream of *(column\_number, row\_number, value)*. With the
* assumption that the data is at least, sequential within the column.
* I.e. if I just received *(c, r, v) : r \> 0*, Â I must have already
* received *(c, r-1, v)*
*
* The the algorithm proceeds as such:
*
* Forward Map Generation
* ----------------------
*
* - A set of row numbers are added to the key columns, and the key
* columns are sorted. And then dropped. This gives the inverse map.
* (i.e. x[i] = j implies output row i is read from input row j)
* - Row numbers are added again, and its sorted again by the first set
* of row numbers. This gives the forward map (i.e. y[i] = j implies
* input row i is written to output row j)
* - (In SFrame pseudocode:
*
* B = A[['key']].add_row_number('r1').sort('key')
* inverse_map = B['r1'] # we don't need this
* C = B.add_row_number('r2').sort('r1')
* foward_map = C['r2']
*
* The forward map is held as an SArray of integers.
*
* Pivot Generation
* ----------------
* - Now we have a forward map, we can get exact buckets. Of N/K
* length. I.e. row r is written to bucket `Floor(K \ forward_map(r) / N)`
*
* Scatter
* -------
* - For each (c,r,v) in data:
* Write (c,v) to bucket `Floor(K \ forward_map(r) / N)`
*
* This requires a little modification to the sframe writer to allow
* single columns writes (really it already does this internally. It
* transposes written rows to turn it to columns). This exploits the
* property that if (c,r-1,v) must be read before (c,r,v). Hence the
* rows are written in the correct order. (though how to do this in
* parallel is a question.)
*
* We will also have to generate a per-bucket forward_map using the same
* scatter procedure.
*
* This requires a little bit of intelligence in the caching of the
* forward map SArray. If the forward map is small, we can keep it all
* in memory. If it is large, need a bit more work. Some intelligence
* needed in this datastructure.
*
* Sort
* ----
*
* For each Bucket b:
* Allocate Output vector of (Length of bucket) * (#columns)
* Let S be the starting index of bucket b (i.e. b*N/k)
* Let T be the ending index of bucket b (i.e. (b+1)*N/k)
* Load forward_map[S:T] into memory
* For each (c,r,v) in bucket b
* Output[per_bucket_forward_map(r) - S][c] = v
* Dump Output to an SFrame
*
* Advantages
* ----------
*
* 1. Only sequential sweeps on the input SFrames, block-wise.
* 2. Does not matter if there are a large number of columns.
* 3. Memory limits can be easier to control.
* a. Scatter has little memory requirements (apart from the write buffer stage).
* b. The forward map is all integers.
* c. The Sort stage can happen a few columns at a time.
*
* Issues
* ------
*
* 1. The block-wise reads do not work well on lazy SFrames. In theory this is
* possible, since the algorithm is technically more general and will work even if
* the (c,r,v) tuples are generated one row at a time (i.e. wide reads). However,
* executing this on a lazy Sframe, means that we *actually* perform the wide
* reads which are slow. (Example: if I have a really wide SFrame on disk.
* And I perform the read through the query execution pipeline, the query
* execution pipeline performs the wide read and that is slow. Whereas if I go to
* the disk SFrame directly, I can completely avoid the wide read).
*
*
* 2. Due to (1) it is better to materialize the SFrame and operate on
* the physical SFrame. Hence we get up to 3x write amplification.
* However, every intermediate bucket is fully compressed.
*
* Optimizations And implementation Details
* ----------------------------------------
*
* - One key aspect is the construction of the forward map. We still
* need to have a second sort algorithm to make that work. We could use
* our current sorting algo, or try to make something simpler since the
* 'value' is always a single integer. As a start, I would just use our
* current sort implementation. And look for something better in the
* future.
*
* - We really need almost random seeks on the forward map. I.e. it is mostly
* sequential due to the column ordering. Some intelligence is needed to decide
* how much of the forward map to hold in memory, and how much to keep on disk.
*
* - Particular excessively heavy columns (like super big dictionaries,
* lists, images) , we store the row number instead during the scatter
* phase. And we use seeks against the original input to transfer it
* straight from input to output. We could take a guess about the
* column data size and use the seek strategy if it is too large.
*
* - There are 2 optimizations possible.
* - One is the above: we write row number into the bucket, and we go back
* to the original input SFrame for data. We can put a threshold size here
* of say ... 256 KB. about 100MBps * 2ms.
*
* - The second is optimization in the final sort of the bucket. We can perform
* seeks to fetch elements from the bucket. Unlike the above, we pay for an
* additional write + seek of the element, but it IS a smaller file.
*
* - Minimize full decode of dictionary/list type. We should be able to
* read/write dict/list columns in the input SFrame as strings. (Annoyingly
* this is actually quite hard to achieve at the moment)
*
* Notes on the current implementation
* -----------------------------------
* - The current implementation uses the old sort algorithm for the backward
* map generation, and the forward map generation. A faster algorithm could be
* used for the forward map sort since it now very small. A dedicated sort
* around just sorting integers could be nice.
*
* \param sframe_planner_node The lazy sframe to be sorted
* \param sort_column_names The columns to be sorted
* \param sort_orders The order for each column to be sorted, true is ascending
*
* \return The sorted sframe
*/
std::shared_ptr<sframe> ec_sort(
std::shared_ptr<planner_node> sframe_planner_node,
const std::vector<std::string> column_names,
const std::vector<size_t>& key_column_indices,
const std::vector<bool>& sort_orders);
/// \}
} // query_eval
} // turicreate
#endif
| 38.651786 | 86 | 0.681682 | Bpowers4 |
4b68327de115fb63425fb394ef35d2566477cad3 | 4,240 | cpp | C++ | 2 Year/2015 Pattern/DSL/Group A/Assignment 9.cpp | bhushanasati25/College | 638ab4f038a783beae297652623e8c6679465fef | [
"MIT"
] | 4 | 2020-10-22T15:37:09.000Z | 2022-02-17T17:30:03.000Z | 2 Year/2015 Pattern/DSL/Group A/Assignment 9.cpp | mohitkhedkar/College | f713949827d69f13b1bf8fb082e86e8bead7ac6e | [
"MIT"
] | null | null | null | 2 Year/2015 Pattern/DSL/Group A/Assignment 9.cpp | mohitkhedkar/College | f713949827d69f13b1bf8fb082e86e8bead7ac6e | [
"MIT"
] | 5 | 2021-06-19T01:23:18.000Z | 2022-02-26T14:47:15.000Z | // Write C/C++ program for storing matrix. Write functions for
// 1. Check whether given matrix is upper triangular or not
// 2. Compute summation of diagonal elements
// 3. Compute transpose of matrix
// 4. Add, subtract and multiply two matrices
// Author: Mohit Khedkar
#include<iostream>
using namespace std;
void diagonal(int[3][3]);
void triangular(int[3][3]);
void transpose(int[3][3]);
void arithmatic(int[3][3]);
int main()
{ int mat[3][3], choice;
cout<<"\nEnter the elements in matrix";
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cin>>mat[i][j];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"\nMENU\n 1) To check for diagonal elements \n 2) To check for upper triangular matrix \n 3) Transpose \n 4) Arithmatic operations\n";
cin>>choice;
switch(choice)
{
case 1 :diagonal(mat);
break;
case 2 :triangular(mat);
break;
case 3 :transpose(mat);
break;
case 4 :arithmatic(mat);
break;
default : cout<<"\nEnter the valid option!!!";
break;
}
return 0;
}
void diagonal(int mat[3][3])
{ int a=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==j&&mat[i][j]==0)
{
a++;
}
}
}
if(a==3){
cout<<"\nIt is a diagonal matrix";}
else
cout<<"\nIt is not a diagonal matrix";
}
void triangular(int mat[3][3])
{int b=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i>j&&mat[i][j]==0)
{
b++;
}
}
}
if(b==3)
{cout<<"\nIt is an upper triangular matrix\n";
}
else
cout<<"It is not an upper traingular matrix";
}
void transpose(int mat[3][3])
{for(int j=0;j<3;j++)
{
for(int i=0;i<3;i++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
}
void arithmatic(int mat[3][3])
{ int art[3][3],choice, mut[3][3],sum[3][3],sub[3][3];
cout<<"\nEnter the values in another matrix\n";
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
cin>>art[k][l];
cout<<" ";
}
}
cout<<"1)Addition \n 2) Subtraction \n 3) Multiplication";
cout<<"\nChoose the operation you want to perform : ";
cin>>choice;
switch(choice)
{
case 1 : for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
sum[i][j]=mat[i][j]+art[i][j];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<sum[i][j]<<"\t";
}
cout<<"\n";
}
break;
case 2 :for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
sub[i][j]=mat[i][j]-art[i][j];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<sub[i][j]<<"\t";
}
cout<<"\n";
}
break;
case 3 :for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
mut[i][j]=0;
}
}
for(int k=0;k<3;k++){
for(int l=0;l<3;l++){
for(int a=0;a<3;a++){
mut[k][l]=mut[k][l]+(mat[l][a]*art[a][k]);
}
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<mut[j][i]<<"\t";
}
cout<<"\n";
}
break;
default : cout<<"\nEnter the valid option!!!";
break;
}
}
| 20.582524 | 143 | 0.365094 | bhushanasati25 |
4b6b6b0da66e98c0b06eae7ea6b4d0052f4684ef | 562 | cpp | C++ | test/test_main.cpp | polestar/audio_utils | 9f5aedb2e21475b4b86e0adfab2da13fbf539930 | [
"MIT"
] | 1 | 2020-02-23T09:53:27.000Z | 2020-02-23T09:53:27.000Z | test/test_main.cpp | polestar/audio_utils | 9f5aedb2e21475b4b86e0adfab2da13fbf539930 | [
"MIT"
] | 1 | 2022-03-06T09:04:17.000Z | 2022-03-06T09:04:17.000Z | test/test_main.cpp | cfogelklou/sweet_osal_platform | 3ebb0ccc37910caf09fd7d2974c742cbdb57171e | [
"MIT"
] | 1 | 2021-12-16T04:26:49.000Z | 2021-12-16T04:26:49.000Z | #include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace testing;
#ifdef WIN32
#include <Windows.h>
#define usleep(x) Sleep(x/1000)
#endif
static void stupidRandom(uint8_t *buf, int cnt) {
for (int i = 0; i < cnt; i++) {
buf[i] = rand() % 255;
}
}
TEST(TestAudioLib, bleah){
}
int main(int argc, char** argv){
// The following line must be executed to initialize Google Mock
// (and Google Test) before running the tests.
::testing::InitGoogleMock(&argc, argv);
const int gtest_rval = RUN_ALL_TESTS();
return gtest_rval;
}
| 18.733333 | 66 | 0.670819 | polestar |
4b6c557bfac6858f633efb7419bd279a58bc67f6 | 2,425 | cpp | C++ | Assignment2/report/src/main.cpp | Gripnook/numerical-methods | 14cb60050e5f2ba413f59690beb24cacb1153563 | [
"MIT"
] | 1 | 2019-02-21T01:35:02.000Z | 2019-02-21T01:35:02.000Z | Assignment2/src/main.cpp | Gripnook/numerical-methods | 14cb60050e5f2ba413f59690beb24cacb1153563 | [
"MIT"
] | null | null | null | Assignment2/src/main.cpp | Gripnook/numerical-methods | 14cb60050e5f2ba413f59690beb24cacb1153563 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <cmath>
#include "matrix.h"
#include "matrix-util.h"
#include "solver.h"
#include "finite-differences.h"
#include "conjugate-gradient.h"
using namespace Numeric;
void question3();
void print(const Matrix<double>& nodes, const Matrix<double>& index);
int main()
{
question3();
return 0;
}
void question3()
{
std::cout << "========== Question 3 ==========" << std::endl;
double h = 0.02;
Matrix<double> A, b, index;
std::tie(A, b, index) = createGrid(h);
std::cout << "Testing for Positive Definite" << std::endl;
auto isPositiveDefinite = bcholesky(A);
std::cout << " A is positive definite: " << std::boolalpha
<< isPositiveDefinite.second << std::endl;
isPositiveDefinite = bcholesky(transpose(A) * A);
std::cout << " A' A is positive definite: " << std::boolalpha
<< isPositiveDefinite.second << std::endl;
std::cout << "Banded Cholesky Solver" << std::endl;
auto bresult = bsolve(transpose(A) * A, transpose(A) * b);
print(bresult, index);
std::cout << "Conjugate Gradient Solver" << std::endl;
std::cout << "iteration,2-norm,inf-norm" << std::endl;
int iteration = 0;
std::function<void(const Matrix<double>&)> callback =
[&](const Matrix<double>& x) {
auto r = b - A * x;
auto twoNorm = std::sqrt(
std::inner_product(r.begin(), r.end(), r.begin(), 0.0));
auto infNorm = std::abs(
*std::max_element(r.begin(), r.end(), [](auto lhs, auto rhs) {
return std::abs(lhs) < std::abs(rhs);
}));
std::cout << iteration++ << "," << twoNorm << "," << infNorm
<< std::endl;
};
auto cgresult = cgsolve(transpose(A) * A, transpose(A) * b, callback);
print(cgresult.first, index);
}
void print(const Matrix<double>& nodes, const Matrix<double>& index)
{
for (int j = index.rows() - 1; j >= 0; --j)
{
for (int i = 0; i < index.cols(); ++i)
{
if (index(i, j) > 0)
{
std::cout << std::setw(10) << nodes(index(i, j) - 1) << " ";
}
else
{
std::cout << std::setw(10) << std::abs(index(i, j)) << " ";
}
}
std::cout << std::endl;
}
}
| 29.938272 | 78 | 0.525361 | Gripnook |
4b6c9e2d2865f26739898f527eb513ebf0d5a6ee | 4,681 | cpp | C++ | core/jitk/codegen_util.cpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 236 | 2015-03-31T15:39:30.000Z | 2022-03-24T01:43:14.000Z | core/jitk/codegen_util.cpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 324 | 2015-05-27T10:35:38.000Z | 2021-12-10T07:34:10.000Z | core/jitk/codegen_util.cpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 41 | 2015-05-26T12:38:42.000Z | 2022-01-10T15:16:37.000Z | /*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <iomanip>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include <unistd.h>
#include <sstream>
#include <boost/filesystem/operations.hpp>
#include <bohrium/jitk/codegen_util.hpp>
#include <bohrium/jitk/view.hpp>
#include <bohrium/jitk/instruction.hpp>
using namespace std;
namespace bohrium {
namespace jitk {
string hash_filename(uint64_t compilation_hash, size_t source_hash, string extension) {
stringstream ss;
ss << setfill ('0') << setw(sizeof(size_t)*2) << hex << compilation_hash << "_"<< source_hash << extension;
return ss.str();
}
boost::filesystem::path write_source2file(const std::string &src,
const boost::filesystem::path &dir,
const std::string &filename,
bool verbose) {
boost::filesystem::path srcfile = dir;
srcfile /= filename;
ofstream ofs(srcfile.string());
ofs << src;
ofs.flush();
ofs.close();
if (verbose) {
cout << "Write source " << srcfile << endl;
}
return srcfile;
}
boost::filesystem::path get_tmp_path(const ConfigParser &config) {
boost::filesystem::path tmp_path, unique_path;
const boost::filesystem::path tmp_dir = config.defaultGet<boost::filesystem::path>("tmp_dir", "NONE");
if (tmp_dir.empty()) {
tmp_path = boost::filesystem::temp_directory_path();
} else {
tmp_path = boost::filesystem::path(tmp_dir);
}
// We add the process id to the unique template
stringstream unique_template;
unique_template << "bh_" << std::hex << getpid() << "_%%%%%";
// On some systems `boost::filesystem::unique_path()` throws a runtime error
// when `LC_ALL` is undefined (or invalid). In this case, we set `LC_ALL=C` and try again.
try {
unique_path = boost::filesystem::unique_path(unique_template.str());
} catch(std::runtime_error &e) {
setenv("LC_ALL", "C", 1); // Force C locale
unique_path = boost::filesystem::unique_path(unique_template.str());
}
return tmp_path / unique_path;
}
void create_directories(const boost::filesystem::path &path) {
constexpr int tries = 5;
for (int i = 1; i <= tries; ++i) {
try {
boost::filesystem::create_directories(path);
return;
} catch (boost::filesystem::filesystem_error &e) {
if (i == tries) {
throw;
}
this_thread::sleep_for(chrono::seconds(3));
cerr << e.what() << endl;
cout << "Warning: " << e.what() << " (" << i << " attempt)" << endl;
}
}
}
std::vector<InstrPtr> order_sweep_set(const std::set<InstrPtr> &sweep_set, const SymbolTable &symbols) {
vector<InstrPtr> ret;
ret.reserve(sweep_set.size());
std::copy(sweep_set.begin(), sweep_set.end(), std::back_inserter(ret));
std::sort(ret.begin(), ret.end(),
[symbols](const InstrPtr & a, const InstrPtr & b) -> bool
{
return symbols.viewID(a->operand[0]) > symbols.viewID(b->operand[0]);
});
return ret;
}
bool row_major_access(const bh_view &view) {
if(not view.isConstant()) {
assert(view.ndim > 0);
for(int64_t i = 1; i < view.ndim; ++ i) {
if (view.stride[i] > view.stride[i-1]) {
return false;
}
}
}
return true;
}
bool row_major_access(const bh_instruction &instr) {
for (const bh_view &view: instr.operand) {
if (not row_major_access(view)) {
return false;
}
}
return true;
}
void to_column_major(std::vector<bh_instruction> &instr_list) {
for(bh_instruction &instr: instr_list) {
if (instr.opcode < BH_MAX_OPCODE_ID and row_major_access(instr)) {
instr.transpose();
}
}
}
} // jitk
} // bohrium
| 32.734266 | 111 | 0.618885 | bh107 |