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
8847f3406218db6478b2dd223dca1bda84814406
1,718
hpp
C++
kernel/memory_map.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
kernel/memory_map.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
kernel/memory_map.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
#pragma once #include <stdint.h> // 構造体定義はUEFI specificな部分. UEFI規格で定められてる定義を独自に構造体定義とした. // ref: edk2/MdePkg/Include/Uefi/UefiSpec.h // ref: p57 struct MemoryMap { unsigned long long buffer_size; // memory mapの中身の先頭アドレス. // 内部的にはEFI_MEMORY_DESCRIPTORの配列になっている(ref:edk2/MdePkg/Include/Uefi/UefiSpec.h) void* buffer; // MemoryMap全体のsizeを表す(EFI_MEMORY_DESCRIPTORエントリのサイズではない!) unsigned long long map_size; unsigned long long map_key; // EFI_MEMORY_DESCRIPTORのサイズ.(UEFIがupdateされるにつれ、ここが変動しうる) unsigned long long descriptor_size; // EFI_MEMORY_DESCRIPTORのサイズ.(上とも関連し、恐らくupdateされることを見越してこのfieldを入れた?) uint32_t descriptor_version; }; // MEMO: EFI_MEMORY_DESCRIPTORの定義を独自構造体として再定義したもの struct MemoryDescriptor { uint32_t type; uintptr_t physical_start; uintptr_t virtual_start; uint64_t number_of_pages; uint64_t attribute; }; #ifdef __cplusplus enum class MemoryType { kEfiReservedMemoryType, kEfiLoaderCode, kEfiLoaderData, kEfiBootServicesCode, kEfiBootServicesData, kEfiRuntimeServicesCode, kEfiRuntimeServicesData, kEfiConventionalMemory, kEfiUnusableMemory, kEfiACPIReclaimMemory, kEfiACPIMemoryNVS, kEfiMemoryMappedIO, kEfiMemoryMappedIOPortSpace, kEfiPalCode, kEfiPersistentMemory, kEfiMaxMemoryType }; inline bool operator==(uint32_t lhs, MemoryType rhs) { return lhs == static_cast<uint32_t>(rhs); } inline bool operator==(MemoryType lhs, uint32_t rhs) { return rhs == lhs; } inline bool IsAvailable(MemoryType memory_type) { return memory_type == MemoryType::kEfiBootServicesCode || memory_type == MemoryType::kEfiBootServicesData || memory_type == MemoryType::kEfiConventionalMemory; } const int kUEFIPageSize = 4096; #endif
25.264706
81
0.786962
mox692
88491b236a93fd2f6d9cfcd0b3b86a55d38fea6c
1,016
cpp
C++
src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp
chrissmith-mcafee/opendxl-broker
a3f985fc19699ab8fcff726bbd1974290eb6e044
[ "Apache-2.0", "MIT" ]
13
2017-10-15T14:32:34.000Z
2022-02-17T08:25:26.000Z
src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp
vkrish-mcafee/opendxl-broker
39c5d06c233dbe01146f0db781eccfd67bbaafbf
[ "Apache-2.0", "MIT" ]
14
2017-10-17T18:23:50.000Z
2021-12-10T22:05:25.000Z
src/brokerlib/message/payload/src/BrokerRegistryQueryResponsePayload.cpp
vkrish-mcafee/opendxl-broker
39c5d06c233dbe01146f0db781eccfd67bbaafbf
[ "Apache-2.0", "MIT" ]
26
2017-10-27T00:27:29.000Z
2021-09-02T16:57:55.000Z
/****************************************************************************** * Copyright (c) 2018 McAfee, LLC - All Rights Reserved. *****************************************************************************/ #include "include/BrokerSettings.h" #include "message/include/DxlMessageConstants.h" #include "message/payload/include/BrokerStateEventPayload.h" #include "message/payload/include/BrokerRegistryQueryResponsePayload.h" using namespace dxl::broker; using namespace dxl::broker::message; using namespace dxl::broker::message::payload; using namespace Json; /** {@inheritDoc} */ void BrokerRegistryQueryResponsePayload::write( Json::Value& out ) const { Value brokers( Json::objectValue ); for( auto it = m_states.begin(); it != m_states.end(); it++ ) { Value jsonObject( Json::objectValue ); BrokerStateEventPayload( *(*it) ).write( jsonObject ); brokers[ (*it)->getBroker().getId() ] = jsonObject; } out[ DxlMessageConstants::PROP_BROKERS ] = brokers; }
37.62963
79
0.601378
chrissmith-mcafee
884a5dbbf30a0c4e1c9530680f9ec4793931eb3d
11,610
cc
C++
test/utils/strings/test_numeric_string.cc
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
test/utils/strings/test_numeric_string.cc
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
test/utils/strings/test_numeric_string.cc
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
// // Created by igor on 25/07/2021. // #include <doctest/doctest.h> #include <neutrino/utils/strings/numeric_string.hh> #include <climits> using namespace neutrino::utils; TEST_SUITE("numeric string conversions") { TEST_CASE("int2string") { // decimal std::string result; REQUIRE (int_to_str(0, 10, result)); REQUIRE (result == "0"); REQUIRE (int_to_str(0, 10, result, false, 10, '0')); REQUIRE (result == "0000000000"); REQUIRE (int_to_str(1234567890, 10, result)); REQUIRE (result == "1234567890"); REQUIRE (int_to_str(-1234567890, 10, result)); REQUIRE (result == "-1234567890"); REQUIRE (int_to_str(-1234567890, 10, result, false, 15, '0')); REQUIRE (result == "-00001234567890"); REQUIRE (int_to_str(-1234567890, 10, result, false, 15)); REQUIRE (result == " -1234567890"); REQUIRE (int_to_str(-1234567890, 10, result, false, 0, 0, ',')); REQUIRE (result == "-1,234,567,890"); // binary REQUIRE (int_to_str(1234567890, 2, result)); REQUIRE (result == "1001001100101100000001011010010"); REQUIRE (int_to_str(1234567890, 2, result, true)); REQUIRE (result == "1001001100101100000001011010010"); REQUIRE (int_to_str(1234567890, 2, result, true, 35, '0')); REQUIRE (result == "00001001001100101100000001011010010"); REQUIRE (uint_to_str(0xFF, 2, result)); REQUIRE (result == "11111111"); REQUIRE (uint_to_str(0x0F, 2, result, false, 8, '0')); REQUIRE (result == "00001111"); REQUIRE (uint_to_str(0x0F, 2, result)); REQUIRE (result == "1111"); REQUIRE (uint_to_str(0xF0, 2, result)); REQUIRE (result == "11110000"); REQUIRE (uint_to_str(0xFFFF, 2, result)); REQUIRE (result == "1111111111111111"); REQUIRE (uint_to_str(0xFF00, 2, result)); REQUIRE (result == "1111111100000000"); REQUIRE (uint_to_str(0xFFFFFFFF, 2, result)); REQUIRE (result == "11111111111111111111111111111111"); REQUIRE (uint_to_str(0xFF00FF00, 2, result)); REQUIRE (result == "11111111000000001111111100000000"); REQUIRE (uint_to_str(0xF0F0F0F0, 2, result)); REQUIRE (result == "11110000111100001111000011110000"); REQUIRE (uint_to_str(0xFFFFFFFFFFFFFFFF, 2, result)); REQUIRE (result == "1111111111111111111111111111111111111111111111111111111111111111"); REQUIRE (uint_to_str(0xFF00000FF00000FF, 2, result)); REQUIRE (result == "1111111100000000000000000000111111110000000000000000000011111111"); // octal REQUIRE (uint_to_str(1234567890, 010, result)); REQUIRE (result == "11145401322"); REQUIRE (uint_to_str(1234567890, 010, result, true)); REQUIRE (result == "011145401322"); REQUIRE (uint_to_str(1234567890, 010, result, true, 15, '0')); REQUIRE (result == "000011145401322"); REQUIRE (uint_to_str(012345670, 010, result, true)); REQUIRE (result == "012345670"); REQUIRE (uint_to_str(012345670, 010, result)); REQUIRE (result == "12345670"); // hexadecimal REQUIRE (uint_to_str(0, 0x10, result, true)); REQUIRE (result == "0x0"); REQUIRE (uint_to_str(0, 0x10, result, true, 4, '0')); REQUIRE (result == "0x00"); REQUIRE (uint_to_str(0, 0x10, result, false, 4, '0')); REQUIRE (result == "0000"); REQUIRE (uint_to_str(1234567890, 0x10, result)); REQUIRE (result == "499602D2"); REQUIRE (uint_to_str(1234567890, 0x10, result, true)); REQUIRE (result == "0x499602D2"); REQUIRE (uint_to_str(1234567890, 0x10, result, true, 15, '0')); REQUIRE (result == "0x00000499602D2"); REQUIRE (uint_to_str(0x1234567890ABCDEF, 0x10, result, true)); REQUIRE (result == "0x1234567890ABCDEF"); REQUIRE (uint_to_str(0xDEADBEEF, 0x10, result)); REQUIRE (result == "DEADBEEF"); REQUIRE (uint_to_str(0xFFFFFFFFFFFFFFFF, 0x10, result)); REQUIRE (result == "FFFFFFFFFFFFFFFF"); REQUIRE (uint_to_str(0xFFFFFFFFFFFFFFFF, 0x10, result, true)); REQUIRE (result == "0xFFFFFFFFFFFFFFFF"); char pResult[NEUTRINO_MAX_INT_STRING_LEN]; std::size_t sz = NEUTRINO_MAX_INT_STRING_LEN; REQUIRE_THROWS(int_to_str(0, 10, pResult, sz, false, (int) sz + 1, ' ')); } TEST_CASE("float2string") { double val = 1.03721575516329e-112; std::string str; REQUIRE (double_to_str(str, val, 14, 21) == "1.03721575516329e-112"); REQUIRE (double_to_str(str, val, 14, 22) == " 1.03721575516329e-112"); val = -val; REQUIRE (double_to_str(str, val, 14, 22) == "-1.03721575516329e-112"); REQUIRE (double_to_str(str, val, 14, 23) == " -1.03721575516329e-112"); val = -10372157551632.9; REQUIRE (double_to_str(str, val, 1, 21, ',') == "-10,372,157,551,632.9"); REQUIRE (double_to_str(str, val, 1, 22, ',') == " -10,372,157,551,632.9"); REQUIRE (double_to_str(str, val, 2, 22, ',') == "-10,372,157,551,632.90"); REQUIRE (double_to_str(str, val, 2, 22, '.', ',') == "-10.372.157.551.632,90"); REQUIRE (double_to_str(str, val, 2, 22, ' ', ',') == "-10 372 157 551 632,90"); int ival = 1234567890; REQUIRE (double_to_str(str, ival, 1, 15, ',') == "1,234,567,890.0"); ival = -123456789; REQUIRE (double_to_str(str, ival, 1, 14, ',') == "-123,456,789.0"); } TEST_CASE("testNumericStringLimit") { char c = 0, t = -1; REQUIRE(!isIntOverflow<char>(c)); REQUIRE(safeIntCast<char>(c, t) == c); REQUIRE(t == c); short s = SHRT_MAX; REQUIRE(isIntOverflow<char>(s)); REQUIRE_THROWS(safeIntCast(s, t)); s = SHRT_MIN; REQUIRE(isIntOverflow<char>(s)); REQUIRE_THROWS(safeIntCast(s, t)); signed char sc = 0, st = -1; REQUIRE(!isIntOverflow<signed char>(sc)); REQUIRE(safeIntCast<char>(sc, st) == sc); REQUIRE(st == sc); short ss = SHRT_MAX; REQUIRE(isIntOverflow<signed char>(ss)); REQUIRE(isIntOverflow<char>(ss)); REQUIRE_THROWS(safeIntCast(ss, st)); ss = SHRT_MIN; REQUIRE(isIntOverflow<signed char>(ss)); REQUIRE(isIntOverflow<char>(ss)); REQUIRE_THROWS(safeIntCast(ss, st)); REQUIRE(safeIntCast<signed char>(sc, st) == c); REQUIRE(st == sc); unsigned char uc = 0, ut = (unsigned char)-1; REQUIRE(!isIntOverflow<unsigned char>(uc)); REQUIRE(safeIntCast<char>(uc, ut) == uc); REQUIRE(ut == uc); ss = SHRT_MAX; REQUIRE(isIntOverflow<unsigned char>(ss)); REQUIRE_THROWS(safeIntCast(ss, st)); ss = -1; REQUIRE(isIntOverflow<unsigned char>(ss)); REQUIRE_THROWS(safeIntCast(ss, uc)); int i = 0; REQUIRE(!isIntOverflow<int>(i)); REQUIRE(!isIntOverflow<unsigned>(i)); i = -1; unsigned int ti = (unsigned int)-1; REQUIRE(isIntOverflow<unsigned>(i)); REQUIRE_THROWS(safeIntCast(i, ti)); if constexpr (sizeof(long) > sizeof(int)) { long l = LONG_MAX; REQUIRE(isIntOverflow<int>(l)); l = -1L; REQUIRE(isIntOverflow<unsigned>(l)); i = -1; REQUIRE(!isIntOverflow<long>(i)); long tl = 0; REQUIRE(safeIntCast(i, tl) == i); unsigned long ul = ULONG_MAX, tul = 0; REQUIRE(isIntOverflow<long>(ul)); REQUIRE_THROWS(safeIntCast(ul, tl)); REQUIRE(!isIntOverflow<unsigned long>(ul)); tl = 0; REQUIRE(safeIntCast(ul, tul) == ul); l = LONG_MIN; REQUIRE(isIntOverflow<unsigned long>(l)); REQUIRE_THROWS(safeIntCast(l, ul)); ul = LONG_MAX; REQUIRE(!isIntOverflow<long>(ul)); REQUIRE(safeIntCast(ul, l) == ul); } /* numericStringLimitSameSign<unsigned short, unsigned char>(); numericStringLimitSameSign<short, char>(); numericStringLimitSameSign<unsigned int, unsigned short>(); numericStringLimitSameSign<int, short>(); if (sizeof(long) > sizeof(int)) { numericStringLimitSameSign<unsigned long, unsigned int>(); numericStringLimitSameSign<long, int>(); } numericStringLowerLimit<short, char>(); numericStringLowerLimit<int, short>(); if (sizeof(long) > sizeof(int)) { numericStringLowerLimit<Poco::Int64, Poco::Int32>(); } */ REQUIRE(!isIntOverflow<int8_t>(0)); REQUIRE(isIntOverflow<int8_t>(std::numeric_limits<int16_t>::max())); REQUIRE(isIntOverflow<int8_t>(std::numeric_limits<int16_t>::min())); REQUIRE(!isIntOverflow<uint8_t>(0)); REQUIRE(isIntOverflow<uint8_t>(std::numeric_limits<int16_t>::max())); REQUIRE(isIntOverflow<uint8_t>(-1)); REQUIRE(!isIntOverflow<int32_t>(0)); REQUIRE(isIntOverflow<int32_t>(std::numeric_limits<int64_t>::max())); REQUIRE(!isIntOverflow<uint32_t>(0)); REQUIRE(isIntOverflow<uint32_t>(-1)); REQUIRE(isIntOverflow<uint32_t>(-1L)); REQUIRE(isIntOverflow<uint32_t>(-1LL)); REQUIRE(!isIntOverflow<int64_t>(-1)); REQUIRE(isIntOverflow<int64_t>(std::numeric_limits<uint64_t>::max())); REQUIRE(!isIntOverflow<uint64_t>(std::numeric_limits<uint64_t>::max())); REQUIRE(isIntOverflow<uint64_t>(std::numeric_limits<int64_t>::min())); REQUIRE(!isIntOverflow<uint64_t>(std::numeric_limits<uint64_t>::min())); REQUIRE(!isIntOverflow<int64_t>(std::numeric_limits<int64_t>::max())); /* numericStringLimitSameSign<uint16_t, uint8_t>(); numericStringLimitSameSign<int16_t, int8_t>(); numericStringLimitSameSign<uint32_t, uint16_t>(); numericStringLimitSameSign<int32_t, int16_t>(); numericStringLimitSameSign<uint64_t, uint32_t>(); numericStringLimitSameSign<int64_t, int32_t>(); numericStringLowerLimit<int16_t, int8_t>(); numericStringLowerLimit<int32_t, int16_t>(); numericStringLowerLimit<int64_t, int32_t>(); */ } TEST_CASE("testNumericStringPadding") { std::string str; REQUIRE (float_to_str(str, 0.999f, 2, 4) == "1.00"); REQUIRE (float_to_str(str, 0.945f, 2, 4) == "0.95"); REQUIRE (float_to_str(str, 0.944f, 2, 4) == "0.94"); REQUIRE (float_to_str(str, 12.45f, 2, 5) == "12.45"); REQUIRE (float_to_str(str, 12.45f, 1, 4) == "12.5"); REQUIRE (float_to_str(str, 12.45f, 2, 6) == " 12.45"); REQUIRE (float_to_str(str, 12.455f, 3, 7) == " 12.455"); REQUIRE (float_to_str(str, 12.455f, 2, 6) == " 12.46"); REQUIRE (float_to_str(str, 1.23556E-16f, 2, 6) == "1.24e-16"); REQUIRE (double_to_str(str, 0.999, 2, 4) == "1.00"); REQUIRE (double_to_str(str, 0.945, 2, 4) == "0.95"); REQUIRE (double_to_str(str, 0.944, 2, 4) == "0.94"); REQUIRE (double_to_str(str, 12.45, 2, 5) == "12.45"); REQUIRE (double_to_str(str, 12.45, 1, 4) == "12.5"); REQUIRE (double_to_str(str, 12.45, 2, 6) == " 12.45"); REQUIRE (double_to_str(str, 12.455, 3, 7) == " 12.455"); REQUIRE (double_to_str(str, 12.455, 2, 6) == " 12.46"); REQUIRE (double_to_str(str, 1.23556E-16, 2, 6) == "1.24e-16"); } }
41.170213
92
0.595349
devbrain
884bcdf60400ceca8e082489717b4773b8b35acc
1,059
cpp
C++
PaintlLess/Assets/components/Ability_Priest.cpp
rubenglezortiz/Proyectos2-2020-21
74b52b8ec4c60717292f8287fa05c00a3748b0d4
[ "CC0-1.0" ]
null
null
null
PaintlLess/Assets/components/Ability_Priest.cpp
rubenglezortiz/Proyectos2-2020-21
74b52b8ec4c60717292f8287fa05c00a3748b0d4
[ "CC0-1.0" ]
null
null
null
PaintlLess/Assets/components/Ability_Priest.cpp
rubenglezortiz/Proyectos2-2020-21
74b52b8ec4c60717292f8287fa05c00a3748b0d4
[ "CC0-1.0" ]
null
null
null
#include "Ability_Priest.h" Ability_Priest::Ability_Priest() : AbilityStruct(selectorH, ShaderForm::TxT, ShaderType::nullSh) {} bool Ability_Priest::AbilityExecute(int x, int y) { bool hasCured = false; GameMap* map = this->getAbility()->getMap(); Entity* entity_ = this->getAbility()->getEntity(); std::vector<Vector2D> abilityCells = this->getAbility()->getCells(); if (abilityCells.empty()) { this->getAbility()->Shade(); abilityCells = this->getAbility()->getCells(); } for (int i = 0; i < abilityCells.size(); i++) { if (map->getCharacter(abilityCells[i]) != nullptr) { if ((map->getCharacter(abilityCells[i])->hasGroup<Equipo_Azul>() && entity_->hasGroup<Equipo_Azul>()) || (map->getCharacter(abilityCells[i])->hasGroup<Equipo_Rojo>() && entity_->hasGroup<Equipo_Rojo>())) { map->getCharacter(abilityCells[i])->getComponent<Health>()->healMonaguillo(1); entity_->getComponent<FramedImage>()->setAnim(A_A_A); sdlutils().soundEffects().at("monaguilloSound").play(); hasCured = true; } } } return hasCured; }
39.222222
209
0.687441
rubenglezortiz
884bd6f3ee6572e5aaa93f8e2e7cd4b0c97193b3
21,491
cpp
C++
20/jurassic_jigsaw.cpp
ComicSansMS/AdventOfCode2020
a46b49f5c566cabbea0e61e24f6238e4caf7470c
[ "Unlicense" ]
null
null
null
20/jurassic_jigsaw.cpp
ComicSansMS/AdventOfCode2020
a46b49f5c566cabbea0e61e24f6238e4caf7470c
[ "Unlicense" ]
null
null
null
20/jurassic_jigsaw.cpp
ComicSansMS/AdventOfCode2020
a46b49f5c566cabbea0e61e24f6238e4caf7470c
[ "Unlicense" ]
null
null
null
#include <jurassic_jigsaw.hpp> #include <fmt/printf.h> #include <range/v3/view/cartesian_product.hpp> #include <range/v3/range/conversion.hpp> #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <charconv> #include <iterator> #include <limits> #include <numeric> #include <regex> #include <sstream> #include <string> std::vector<RawTile> parseInput(std::string_view input) { std::vector<RawTile> ret; std::stringstream sstr{std::string{input}}; int line_count = 0; std::string line; RawTile t; while (std::getline(sstr, line)) { if (line_count == 0) { assert(line.starts_with("Tile ")); assert(line[9] == ':'); t.id = std::stoi(line.substr(5, 4)); } else if (line_count == 11) { assert(line == ""); ret.push_back(t); line_count = 0; continue; } else { assert(line.size() == 10); int start_index = (line_count - 1) * 10; for (int i = 0; i < 10; ++i) { assert((line[i] == '.') || (line[i] == '#')); t.field[start_index + i] = (line[i] == '.') ? 0 : 1; } } ++line_count; } assert(line_count == 0); return ret; } CompressedTile compressTile(RawTile const& t) { CompressedTile ret; for (int i = 0; i < 10; ++i) { ret.top[9 - i] = t.field[i]; } for (int i = 0; i < 10; ++i) { ret.bottom[9 - i] = t.field[i + 90]; } for (int i = 0; i < 10; ++i) { ret.left[9 - i] = t.field[i * 10]; } for (int i = 0; i < 10; ++i) { ret.right[9 - i] = t.field[(i * 10) + 9]; } ret.id = t.id; ret.transform = TransformState::Straight; return ret; } template<std::size_t N> std::bitset<N> reverse(std::bitset<N> const& b) { std::bitset<N> ret; for(std::size_t i = 0; i < N; ++i) { ret[i] = b[N - i - 1]; } return ret; } bool hasMatchingSide(CompressedTile const& candidate, CompressedTile const& match, std::bitset<10> CompressedTile::* side_to_check) { std::bitset<10> const& s = candidate.*side_to_check; return ((match.top == s) || (reverse(match.top) == s) || (match.bottom == s) || (reverse(match.bottom) == s) || (match.left == s) || (reverse(match.left) == s) || (match.right == s) || (reverse(match.right) == s)); } SortedTiles findCorners(std::vector<RawTile> const& t) { std::vector<CompressedTile> ctiles; ctiles.reserve(t.size()); std::transform(begin(t), end(t), std::back_inserter(ctiles), compressTile); auto const check_side = [&ctiles](std::size_t candidate_index, std::bitset<10> CompressedTile::* side_to_check) -> bool { CompressedTile const& candidate = ctiles[candidate_index]; bool found_match = false; for (std::size_t ii = 0; ii < ctiles.size(); ++ii) { if (ii != candidate_index) { if(hasMatchingSide(candidate, ctiles[ii], side_to_check)) { found_match = true; break; } } } return found_match; }; SortedTiles ret; for (std::size_t i = 0; i < t.size(); ++i) { int unmatched_sides = 0; if (!check_side(i, &CompressedTile::top)) { ++unmatched_sides; } if (!check_side(i, &CompressedTile::bottom)) { ++unmatched_sides; } if (!check_side(i, &CompressedTile::left)) { ++unmatched_sides; } if (!check_side(i, &CompressedTile::right)) { ++unmatched_sides; } assert(unmatched_sides < 3); if (unmatched_sides == 2) { ret.corner.push_back(t[i]); } else if(unmatched_sides == 1) { ret.edge.push_back(t[i]); } else { assert(unmatched_sides == 0); ret.middle.push_back(t[i]); } } return ret; } int64_t solve1(std::vector<RawTile> const& t) { auto const corners = findCorners(t).corner; assert(corners.size() == 4); return std::accumulate(begin(corners), end(corners), int64_t{1}, [](int64_t acc, RawTile const& t) { return acc * t.id; }); } [[nodiscard]] CompressedTile transformCompressed(CompressedTile ct) { auto rot90 = [](CompressedTile const& ct) -> CompressedTile { CompressedTile ret = ct; ret.right = ct.top; ret.bottom = reverse(ct.right); ret.left = ct.bottom; ret.top = reverse(ct.left); return ret; }; auto flip = [](CompressedTile const& ct) -> CompressedTile { CompressedTile ret = ct; ret.right = reverse(ct.right); ret.bottom = ct.top; ret.top = ct.bottom; ret.left = reverse(ct.left); return ret; }; switch (ct.transform) { default: assert(false); case TransformState::Straight: ct.transform = TransformState::Rot90; return rot90(ct); case TransformState::Rot90: ct.transform = TransformState::Rot180; return rot90(ct); case TransformState::Rot180: ct.transform = TransformState::Rot270; return rot90(ct); case TransformState::Rot270: ct.transform = TransformState::Flip; return flip(rot90(ct)); case TransformState::Flip: ct.transform = TransformState::Flip90; return rot90(ct); case TransformState::Flip90: ct.transform = TransformState::Flip180; return rot90(ct); case TransformState::Flip180: ct.transform = TransformState::Flip270; return rot90(ct); case TransformState::Flip270: ct.transform = TransformState::Straight; return flip(rot90(ct)); } } [[nodiscard]] RawTile rot90(RawTile const& t) { RawTile ret; ret.id = t.id; for (int j = 0; j < 10; ++j) { for (int i = 0; i < 10; ++i) { ret.field[i*10 + j] = t.field[(10 - j - 1)*10 + i]; } } return ret; } [[nodiscard]] RawTile flip(RawTile const& t) { RawTile ret; ret.id = t.id; for (int j = 0; j < 10; ++j) { for (int i = 0; i < 10; ++i) { ret.field[i*10 + j] = t.field[(10 - i - 1)*10 + j]; } } return ret; } [[nodiscard]] RawTile transformTo(RawTile const& t, TransformState target_state) { switch (target_state) { default: assert(false); case TransformState::Straight: return t; case TransformState::Rot90: return rot90(t); case TransformState::Rot180: return rot90(rot90(t)); case TransformState::Rot270: return rot90(rot90(rot90(t))); case TransformState::Flip: return flip(t); case TransformState::Flip90: return rot90(flip(t)); break; case TransformState::Flip180: return rot90(rot90(flip(t))); break; case TransformState::Flip270: return flip(rot90(t)); break; } } bool hasAnyMatch(CompressedTile const& source_tile, std::vector<CompressedTile> const& haystack, std::bitset<10> CompressedTile::* source_edge) { return std::any_of(begin(haystack), end(haystack), [&source_tile, source_edge](CompressedTile const& m) { return (&m != &source_tile) && hasMatchingSide(source_tile, m, source_edge); }); } std::vector<std::vector<CompressedTile>::iterator> findMatchesFor(CompressedTile const& source_tile, std::vector<CompressedTile>& haystack, std::bitset<10> CompressedTile::* source_edge) { std::vector<std::vector<CompressedTile>::iterator> ret; for (auto it = haystack.begin(), it_end = haystack.end(); it != it_end; ++it) { if (hasMatchingSide(source_tile, *it, source_edge)) { ret.push_back(it); } } return ret; } std::vector<RawTile> solvePuzzle(SortedTiles const& sorted_tiles) { assert(sorted_tiles.corner.size() == 4); assert(sorted_tiles.edge.size() % 4 == 0); int const dimension = static_cast<int>(sorted_tiles.edge.size() / 4) + 2; assert(sorted_tiles.middle.size() == (dimension - 2) * (dimension - 2)); std::vector<CompressedTile> corner; std::transform(begin(sorted_tiles.corner), end(sorted_tiles.corner), std::back_inserter(corner), compressTile); std::vector<CompressedTile> edge; std::transform(begin(sorted_tiles.edge), end(sorted_tiles.edge), std::back_inserter(edge), compressTile); std::vector<CompressedTile> middle; std::transform(begin(sorted_tiles.middle), end(sorted_tiles.middle), std::back_inserter(middle), compressTile); std::vector<CompressedTile> solution; solution.reserve(dimension * dimension); // orient first corner correctly solution.push_back(corner.back()); corner.pop_back(); CompressedTile& corner_ul = solution.front(); while (!(hasAnyMatch(corner_ul, edge, &CompressedTile::right) && hasAnyMatch(corner_ul, edge, &CompressedTile::bottom))) { corner_ul = transformCompressed(corner_ul); } // solve top edge for (int i = 0; i < dimension - 2; ++i) { CompressedTile const& left_neighbour = solution.back(); auto matches = findMatchesFor(left_neighbour, edge, &CompressedTile::right); assert(matches.size() == 1); auto it_next = matches.back(); assert(it_next != end(edge)); CompressedTile edge_piece = *it_next; edge.erase(it_next); // find correct orientation while (! ((left_neighbour.right == edge_piece.left) && (hasAnyMatch(edge_piece, (i == (dimension - 3) ? corner : edge), &CompressedTile::right)) && (hasAnyMatch(edge_piece, middle, &CompressedTile::bottom))) ) { edge_piece = transformCompressed(edge_piece); assert(edge_piece.transform != TransformState::Straight); } solution.push_back(edge_piece); } // solve top-left corner { CompressedTile const& left_neighbour = solution.back(); auto matches = findMatchesFor(left_neighbour, corner, &CompressedTile::right); assert(matches.size() == 1); auto it_next = matches.back(); CompressedTile next_piece = *it_next; corner.erase(it_next); // find correct orientation while (! ((left_neighbour.right == next_piece.left) && (hasAnyMatch(next_piece, edge, &CompressedTile::bottom))) ) { next_piece = transformCompressed(next_piece); assert(next_piece.transform != TransformState::Straight); } solution.push_back(next_piece); } // solve center pieces for (int i_row = 0; i_row < dimension - 2; ++i_row) { // left edge { CompressedTile const& top_neighbour = solution[i_row * dimension]; auto matches = findMatchesFor(top_neighbour, edge, &CompressedTile::bottom); assert(matches.size() == 1); auto it_next = matches.back(); CompressedTile next_piece = *it_next; edge.erase(it_next); // find correct orientation while (! ((top_neighbour.bottom == next_piece.top) && (hasAnyMatch(next_piece, middle, &CompressedTile::right))) ) { next_piece = transformCompressed(next_piece); assert(next_piece.transform != TransformState::Straight); } solution.push_back(next_piece); } // middle for (int i_col = 0; i_col < dimension - 2; ++i_col) { CompressedTile const& top_neighbour = solution[(i_row * dimension) + i_col + 1]; CompressedTile const& left_neighbour = solution.back(); auto matches = findMatchesFor(top_neighbour, middle, &CompressedTile::bottom); assert(matches.size() == 1); auto it_next = matches.back(); CompressedTile next_piece = *it_next; middle.erase(it_next); // find correct orientation while (! ((top_neighbour.bottom == next_piece.top) && (left_neighbour.right == next_piece.left) && (hasAnyMatch(next_piece, ((i_col == dimension - 3) ? edge : middle), &CompressedTile::right))) ) { next_piece = transformCompressed(next_piece); assert(next_piece.transform != TransformState::Straight); } solution.push_back(next_piece); } // right edge { CompressedTile const& top_neighbour = solution[(i_row + 1) * dimension - 1]; CompressedTile const& left_neighbour = solution.back(); auto matches = findMatchesFor(top_neighbour, edge, &CompressedTile::bottom); assert(matches.size() == 1); auto it_next = matches.back(); CompressedTile next_piece = *it_next; edge.erase(it_next); // find correct orientation while (! ((top_neighbour.bottom == next_piece.top) && (left_neighbour.right == next_piece.left)) ) { next_piece = transformCompressed(next_piece); assert(next_piece.transform != TransformState::Straight); } solution.push_back(next_piece); } } assert(middle.empty()); // solve bottom-left corner { CompressedTile const& top_neighbour = solution[(dimension - 2) * dimension]; auto matches = findMatchesFor(top_neighbour, corner, &CompressedTile::bottom); assert(matches.size() == 1); auto it_next = matches.back(); CompressedTile next_piece = *it_next; corner.erase(it_next); // find correct orientation while (! ((top_neighbour.bottom == next_piece.top) && (hasAnyMatch(next_piece, edge, &CompressedTile::right))) ) { next_piece = transformCompressed(next_piece); assert(next_piece.transform != TransformState::Straight); } solution.push_back(next_piece); } // solve bottom edge for (int i = 0; i < dimension - 2; ++i) { CompressedTile const& top_neighbour = solution[(dimension - 2) * dimension + i + 1]; CompressedTile const& left_neighbour = solution.back(); auto matches = findMatchesFor(left_neighbour, edge, &CompressedTile::right); assert(matches.size() == 1); auto it_next = matches.back(); assert(it_next != end(edge)); CompressedTile edge_piece = *it_next; edge.erase(it_next); // find correct orientation while (! ((left_neighbour.right == edge_piece.left) && (top_neighbour.bottom == edge_piece.top) && (hasAnyMatch(edge_piece, (i == (dimension - 3) ? corner : edge), &CompressedTile::right))) ) { edge_piece = transformCompressed(edge_piece); assert(edge_piece.transform != TransformState::Straight); } solution.push_back(edge_piece); } assert(edge.empty()); // place final corner { assert(corner.size() == 1); CompressedTile final_corner = corner.back(); corner.pop_back(); CompressedTile const& top_neighbour = solution[(dimension - 1) * dimension - 1]; CompressedTile const& left_neighbour = solution.back(); // find correct orientation while (! ((left_neighbour.right == final_corner.left) && (top_neighbour.bottom == final_corner.top)) ) { final_corner = transformCompressed(final_corner); assert(final_corner.transform != TransformState::Straight); } solution.push_back(final_corner); } assert(corner.empty()); // assemble raw tile solution std::vector<RawTile> all_tiles; all_tiles.reserve(dimension * dimension); all_tiles = sorted_tiles.corner; all_tiles.insert(end(all_tiles), begin(sorted_tiles.edge), end(sorted_tiles.edge)); all_tiles.insert(end(all_tiles), begin(sorted_tiles.middle), end(sorted_tiles.middle)); std::vector<RawTile> ret; ret.reserve(dimension * dimension); for (auto const& cs : solution) { auto it = std::find_if(begin(all_tiles), end(all_tiles), [id = cs.id](auto const& t) { return t.id == id; }); assert(it != end(all_tiles)); ret.push_back(transformTo(*it, cs.transform)); } return ret; } std::vector<RawTile> transformSolution(std::vector<RawTile> const& in, TransformState target_state) { int const dimension = static_cast<int>(std::sqrt(in.size())); assert(dimension * dimension == in.size()); auto const rot90 = [dimension](std::vector<RawTile> const& in) { std::vector<RawTile> ret; ret.resize(dimension * dimension); for (int iy = 0; iy < dimension; ++iy) { for (int ix = 0; ix < dimension; ++ix) { ret[ix*dimension + iy] = transformTo(in[(dimension - iy - 1)*dimension + ix], TransformState::Rot90); } } return ret; }; auto const flip = [dimension](std::vector<RawTile> const& in) { std::vector<RawTile> ret; ret.resize(dimension * dimension); for (int iy = 0; iy < dimension; ++iy) { for (int ix = 0; ix < dimension; ++ix) { ret[ix*dimension + iy] = transformTo(in[(dimension - ix - 1)*dimension + iy], TransformState::Flip); } } return ret; }; switch (target_state) { case TransformState::Rot90: return rot90(in); case TransformState::Rot180: return rot90(rot90(in)); case TransformState::Rot270: return rot90(rot90(rot90(in))); case TransformState::Flip: return flip(in); case TransformState::Flip90: return rot90(flip(in)); case TransformState::Flip180: return rot90(rot90(flip(in))); case TransformState::Flip270: return rot90(rot90(rot90(flip(in)))); case TransformState::Straight: break; } return in; } GaplessField makeGapless(std::vector<RawTile> const& tiles) { int const dimension = static_cast<int>(std::sqrt(tiles.size())); assert(dimension * dimension == tiles.size()); GaplessField ret; ret.dimension = dimension * 8; ret.field.resize(ret.dimension * ret.dimension); for (int ity = 0; ity < dimension; ++ity) { for (int itx = 0; itx < dimension; ++itx) { RawTile const& t = tiles[ity * dimension + itx]; for (int iy = 1; iy < 9; ++iy) { int const target_y = (ity * 8) + iy - 1; for (int ix = 1; ix < 9; ++ix) { int const target_x = (itx * 8) + ix - 1; ret.field[target_y * ret.dimension + target_x] = t.field[iy * 10 + ix]; } } } } return ret; } Pattern getDragonPattern() { char const pattern[] = " # \n" "# ## ## ###\n" " # # # # # # \n"; Pattern p; p.height = 3; p.width = 20; p.data.reserve(p.width * p.height); for (auto const c : pattern) { if ((c == '\n') || (c == '\0')) { assert(p.data.size() % p.width == 0); } else { p.data.push_back((c == '#') ? 1 : 0); } } assert(p.data.size() == p.width * p.height); return p; } std::vector<Vec2> findInField(std::vector<RawTile> const& field, Pattern const& p) { TransformState const transforms[] = { TransformState::Straight, TransformState::Rot90, TransformState::Rot180, TransformState::Rot270, TransformState::Flip, TransformState::Flip90, TransformState::Flip180, TransformState::Flip270 }; for (auto const transform : transforms) { GaplessField gf = makeGapless(transformSolution(field, transform)); std::vector<Vec2> ret; for (int iy = 0; iy < gf.dimension; ++iy) { for (int ix = 0; ix < gf.dimension; ++ix) { bool found_pattern = true; for(int py = 0; py < p.height; ++py) { for(int px = 0; px < p.width; ++px) { int const fy = iy + py; int const fx = ix + px; if ((fy >= gf.dimension) || (fx >= gf.dimension)) { found_pattern = false; break; } if (p.data[py * p.width + px]) { if (!gf.field[fy * gf.dimension + fx]) { found_pattern = false; break; } } } if (!found_pattern) { break; } } if (found_pattern) { ret.push_back(Vec2{ ix, iy }); } } } if (!ret.empty()) { return ret; } } return {}; } int64_t solve2(std::vector<RawTile> const& tiles) { auto const sorted_tiles = findCorners(tiles); auto const solved_puzzle = solvePuzzle(sorted_tiles); auto const findings = findInField(solved_puzzle, getDragonPattern()); GaplessField gf = makeGapless(solved_puzzle); auto const fields_total = std::count(begin(gf.field), end(gf.field), 1); auto const dragon_pattern = getDragonPattern(); auto const fields_dragon = std::count(begin(dragon_pattern.data), end(dragon_pattern.data), 1); return fields_total - (fields_dragon * findings.size()); }
37.375652
186
0.574566
ComicSansMS
884db12965f9183dfc14a42dbb47df8e610cccb2
802
cpp
C++
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Sensor/OpticalFlowCamera.cpp
Sid1057/carla_sport
76323ce68f7093278b2f47aa3d37ec90fa19038a
[ "MIT" ]
null
null
null
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Sensor/OpticalFlowCamera.cpp
Sid1057/carla_sport
76323ce68f7093278b2f47aa3d37ec90fa19038a
[ "MIT" ]
null
null
null
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Sensor/OpticalFlowCamera.cpp
Sid1057/carla_sport
76323ce68f7093278b2f47aa3d37ec90fa19038a
[ "MIT" ]
null
null
null
#include "Carla.h" #include "Carla/Sensor/OpticalFlowCamera.h" #include "Carla/Sensor/PixelReader.h" FActorDefinition AOpticalFlowCamera::GetSensorDefinition() { return UActorBlueprintFunctionLibrary::MakeCameraDefinition(TEXT("optical_flow")); } AOpticalFlowCamera::AOpticalFlowCamera(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { Enable16BitFormat(true); AddPostProcessingMaterial( TEXT("Material'/Carla/PostProcessingMaterials/PhysicLensDistortion.PhysicLensDistortion'")); AddPostProcessingMaterial( TEXT("Material'/Carla/PostProcessingMaterials/VelocityMaterial.VelocityMaterial'")); } void AOpticalFlowCamera::PostPhysTick(UWorld *World, ELevelTick TickType, float DeltaSeconds) { FPixelReader::SendPixelsInRenderThread(*this, true); }
32.08
98
0.809227
Sid1057
71ff03117ca1f6a8e39e472f49ed3a361e5e3905
6,049
cpp
C++
src/planner/Admin.cpp
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
1
2021-08-23T05:55:55.000Z
2021-08-23T05:55:55.000Z
src/planner/Admin.cpp
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
null
null
null
src/planner/Admin.cpp
critical27/nebula-graph
04d00e779e860ed3ddb226c416c335a22acc1147
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "planner/Admin.h" #include "common/interface/gen-cpp2/graph_types.h" #include "util/ToJson.h" namespace nebula { namespace graph { std::unique_ptr<cpp2::PlanNodeDescription> CreateSpace::explain() const { auto desc = SingleInputNode::explain(); addDescription("ifNotExists", util::toJson(ifNotExists_), desc.get()); addDescription("spaceDesc", folly::toJson(util::toJson(spaceDesc_)), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> DropSpace::explain() const { auto desc = SingleInputNode::explain(); addDescription("spaceName", spaceName_, desc.get()); addDescription("ifExists", util::toJson(ifExists_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> DescSpace::explain() const { auto desc = SingleInputNode::explain(); addDescription("spaceName", spaceName_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ShowCreateSpace::explain() const { auto desc = SingleInputNode::explain(); addDescription("spaceName", spaceName_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> DropSnapshot::explain() const { auto desc = SingleInputNode::explain(); addDescription("snapshotName", snapshotName_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ShowParts::explain() const { auto desc = SingleInputNode::explain(); addDescription("spaceId", folly::to<std::string>(spaceId_), desc.get()); addDescription("partIds", folly::toJson(util::toJson(partIds_)), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ShowConfigs::explain() const { auto desc = SingleInputNode::explain(); addDescription("module", meta::cpp2::_ConfigModule_VALUES_TO_NAMES.at(module_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> SetConfig::explain() const { auto desc = SingleInputNode::explain(); addDescription("module", meta::cpp2::_ConfigModule_VALUES_TO_NAMES.at(module_), desc.get()); addDescription("name", name_, desc.get()); addDescription("value", value_.toString(), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> GetConfig::explain() const { auto desc = SingleInputNode::explain(); addDescription("module", meta::cpp2::_ConfigModule_VALUES_TO_NAMES.at(module_), desc.get()); addDescription("name", name_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> CreateNode::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("ifNotExist", util::toJson(ifNotExist_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> DropNode::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("ifExist", util::toJson(ifExist_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> CreateUser::explain() const { auto desc = CreateNode::explain(); addDescription("username", *username_, desc.get()); addDescription("password", "******", desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> DropUser::explain() const { auto desc = DropNode::explain(); addDescription("username", *username_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> UpdateUser::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("username", *username_, desc.get()); addDescription("password", "******", desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> GrantRole::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("username", *username_, desc.get()); addDescription("spaceName", *spaceName_, desc.get()); addDescription("role", meta::cpp2::_RoleType_VALUES_TO_NAMES.at(role_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> RevokeRole::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("username", *username_, desc.get()); addDescription("spaceName", *spaceName_, desc.get()); addDescription("role", meta::cpp2::_RoleType_VALUES_TO_NAMES.at(role_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ChangePassword::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("username", *username_, desc.get()); addDescription("password", "******", desc.get()); addDescription("newPassword", "******", desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ListUserRoles::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("username", *username_, desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ListRoles::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("space", util::toJson(space_), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> SubmitJob::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("operation", meta::cpp2::_AdminJobOp_VALUES_TO_NAMES.at(op_), desc.get()); addDescription("command", meta::cpp2::_AdminCmd_VALUES_TO_NAMES.at(cmd_), desc.get()); addDescription("parameters", folly::toJson(util::toJson(params_)), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> Balance::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("deleteHosts", folly::toJson(util::toJson(deleteHosts_)), desc.get()); return desc; } std::unique_ptr<cpp2::PlanNodeDescription> ShowBalance::explain() const { auto desc = SingleDependencyNode::explain(); addDescription("balanceId", util::toJson(id_), desc.get()); return desc; } } // namespace graph } // namespace nebula
36.439759
96
0.707555
critical27
71ff9d745e6b58330862f32226f7e98802b7139a
40,132
cpp
C++
lib/Lex/Lexer.cpp
MelvinG24/Latino-LLVM
74bc2f6192a0337590f2aec3a382587a16cae8a2
[ "MIT" ]
null
null
null
lib/Lex/Lexer.cpp
MelvinG24/Latino-LLVM
74bc2f6192a0337590f2aec3a382587a16cae8a2
[ "MIT" ]
null
null
null
lib/Lex/Lexer.cpp
MelvinG24/Latino-LLVM
74bc2f6192a0337590f2aec3a382587a16cae8a2
[ "MIT" ]
1
2019-01-28T22:37:09.000Z
2019-01-28T22:37:09.000Z
#include "latino/Lex/Lexer.h" #include "UnicodeCharSets.h" #include "latino/Basic/CharInfo.h" #include "latino/Basic/Diagnostic.h" #include "latino/Basic/IdentifierTable.h" #include "latino/Basic/LLVM.h" #include "latino/Basic/LangOptions.h" #include "latino/Basic/SourceLocation.h" #include "latino/Basic/SourceManager.h" #include "latino/Basic/TokenKinds.h" #include "latino/Lex/Token.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/NativeFormatting.h" #include "llvm/Support/UnicodeCharRanges.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <tuple> #include <utility> using namespace latino; //===----------------------------------------------------------------------===// // Lexer Class Implementation //===----------------------------------------------------------------------===// // void Lexer::anchor() {} void Lexer::InitLexer(const char *BuffStart, const char *BuffPtr, const char *BuffEnd) { BufferStart = BuffStart; BufferPtr = BuffPtr; BufferEnd = BuffEnd; assert(BuffEnd[0] == 0 && "We assume that the input buffer has a null character at the end" " to simplify lexing"); // Check whether we have a BOM in the beginning of the buffer. If yes - act // accordingly. Right now we support only UTF-8 with and without BOM, so, just // skip the UTF-8 BOM if it's present. if (BufferStart == BufferPtr) { // Determine the size of the BOM. StringRef Buf(BufferStart, BufferEnd - BufferStart); size_t BOMLength = llvm::StringSwitch<size_t>(Buf) .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM .Default(0); // Skip the BOM. BufferPtr += BOMLength; } // Start of the file is a start of line. IsAtStartOfLine = true; IsAtPhysicalStartOfLine = true; HasLeadingSpace = false; } /// Lexer constructor - Create a new lexer object for the specified buffer /// with the specified preprocessor managing the lexing process. This lexer /// assumes that the associated file buffer and Preprocessor objects will /// outlive it, so it doesn't take ownership of either of them. Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, const SourceManager &SM) : FileLoc(SM.getLocForStartOfFile(FID)) { InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(), InputFile->getBufferEnd()); // resetExtendedTokenMode(); } /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text /// range will outlive it, so it doesn't take ownership of it. Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts, const char *BufStart, const char *BufPtr, const char *BufEnd) : FileLoc(fileloc) { InitLexer(BufStart, BufPtr, BufEnd); // We *are* in raw mode. // LexingRawMode = true; } /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text /// range will outlive it, so it doesn't take ownership of it. Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile, const SourceManager &SM, const LangOptions &langOpts) : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(), FromFile->getBufferStart(), FromFile->getBufferEnd()) {} /// getSourceLocation - Return a source location identifier for the specified /// offset in the current file. SourceLocation Lexer::getSourceLocation(const char *Loc, unsigned TokLen) const { assert(Loc >= BufferStart && Loc <= BufferEnd && "Location out of range for this buffer!"); // In the normal case, we're just lexing from a simple file buffer, return // the file id from FileLoc with the offset specified. unsigned CharNo = Loc - BufferStart; if (FileLoc.isFileID()) return FileLoc.getLocWithOffset(CharNo); /* // Otherwise, this is the _Pragma lexer case, which pretends that all of the // tokens are lexed from where the _Pragma was defined. assert(PP && "This doesn't work on raw lexers"); return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen); */ } bool Lexer::Lex(Token &Result) { // Start a new token. Result.startToken(); // Set up misc whitespace flags for LexTokenInternal. if (IsAtStartOfLine) { Result.setFlag(Token::StartOfLine); IsAtStartOfLine = false; } if (HasLeadingSpace) { Result.setFlag(Token::LeadingSpace); HasLeadingSpace = false; } if (HasLeadingEmptyMacro) { Result.setFlag(Token::LeadingEmptyMacro); HasLeadingEmptyMacro = false; } bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine; IsAtPhysicalStartOfLine = false; bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine); return returnedToken; } //===----------------------------------------------------------------------===// // Trigraph and Escaped Newline Handling Code. //===----------------------------------------------------------------------===// /* /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, /// return the decoded trigraph letter it corresponds to, or '\0' if nothing. static char GetTrigraphCharForLetter(char Letter) { switch (Letter) { default: return 0; case '=': return '#'; case ')': return ']'; case '(': return '['; case '!': return '|'; case '\'': return '^'; case '>': return '}'; case '/': return '\\'; case '<': return '{'; case '-': return '~'; } } */ bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) { // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$] unsigned Size; unsigned char C = *CurPtr++; while (isIdentifierBody(C)) C = *CurPtr++; --CurPtr; // Back up over the skipped character. // Fast path, no $,\,? in identifier found. '\' might be an escaped newline // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN. // // TODO: Could merge these checks into an InfoTable flag to make the // comparison cheaper if (isASCII(C)) { FinishIdentifier: const char *IdStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::raw_identifier); Result.setRawIdentifierData(IdStart); return true; } return false; } /// LexCharConstant - Lex the remainder of a character constant, after having /// lexed either ' or L' or u8' or u' or U'. bool Lexer::LexCharConstant(Token &Result, const char *CurPtr, tok::TokenKind Kind) { // Does this character contain the \0 character? const char *NulCharacter = nullptr; char C = getAndAdvanceChar(CurPtr, Result); if (C == '\'') { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } while (C != '\'') { // Skip escaped characters. if (C == '\\') C = getAndAdvanceChar(CurPtr, Result); if (C == '\n' || C == '\r' || // Newline. (C == 0 && CurPtr - 1 == BufferEnd)) { // End of file. FormTokenWithChars(Result, CurPtr - 1, tok::unknown); return true; } if (C == 0) { NulCharacter = CurPtr - 1; } C = getAndAdvanceChar(CurPtr, Result); } const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, Kind); Result.setLiteralData(TokStart); return true; } /// SkipWhitespace - Efficiently skip over a series of whitespace characters. /// Update BufferPtr to point to the next non-whitespace character and return. /// /// This method forms a token and returns true if KeepWhitespaceMode is enabled. bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // Whitespace - Skip it, then return the token after the whitespace. bool SawNewline = isVerticalWhitespace(CurPtr[-1]); unsigned char Char = *CurPtr; // Skip consecutive spaces efficiently. while (true) { // Skip horizontal whitespace very aggressively. while (isHorizontalWhitespace(Char)) Char = *++CurPtr; // Otherwise if we have something other than whitespace, we're done. if (!isVerticalWhitespace(Char)) break; SawNewline = true; Char = *++CurPtr; } // If this isn't immediately after a newline, there is leading space. char PrevChar = CurPtr[-1]; bool HasLeadingSpace = !isVerticalWhitespace(PrevChar); // Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace); if (SawNewline) { Result.setFlag(Token::StartOfLine); TokAtPhysicalStartOfLine = true; } BufferPtr = CurPtr; return false; } bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr, tok::TokenKind Kind) { const char *NulCharacter = nullptr; char C = getAndAdvanceChar(CurPtr, Result); while (C != '"') { if (C == '\\') C = getAndAdvanceChar(CurPtr, Result); if (C == '\n' || C == '\r' || (C == 0 && CurPtr - 1 == BufferEnd)) { FormTokenWithChars(Result, CurPtr - 1, tok::unknown); return true; } if (C == 0) { NulCharacter = CurPtr - 1; } C = getAndAdvanceChar(CurPtr, Result); } const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, Kind); Result.setLiteralData(TokStart); return true; } /// LexNumericConstant - Lex the remainder of a integer or floating point /// constant. From[-1] is the first character lexed. Return the end of the /// constant. bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { unsigned Size; char C = getCharAndSize(CurPtr, Size); char PrevCh = 0; while (latino::isPreprocessingNumberBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); PrevCh = C; C = getCharAndSize(CurPtr, Size); } // If we fell out, check for a sign, due to 1e+12. If we have one, continue. if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) { // If we are in Microsoft mode, don't continue if the constant is hex. // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1 if (!isHexaLiteral(BufferPtr, LangOpts)) return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); } // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::numeric_constant); Result.setLiteralData(TokStart); return true; } /// isHexaLiteral - Return true if Start points to a hex constant. /// in microsoft mode (where this is supposed to be several different tokens). bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) { unsigned Size; char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts); if (C1 != '0') return false; char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts); return (C2 == 'x' || C2 == 'X'); } /// We have just read the // characters from input. Skip until we find the /// newline character that terminates the comment. Then update BufferPtr and /// return. /// /// If we're in KeepCommentMode or any CommentHandler has inserted /// some tokens, this will store the first token and return true. bool Lexer::SkipLineComment(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // Scan over the body of the comment. The common case, when scanning, is that // the comment contains normal ascii characters with nothing interesting in // them. As such, optimize for this case with the inner loop. // // This loop terminates with CurPtr pointing at the newline (or end of buffer) // character that ends the line comment. char C; while (true) { C = *CurPtr; // Skip over characters in the fast loop. while (C != 0 && // Potentially EOF. C != '\n' && C != '\r') // Newline or DOS-style newline. C = *++CurPtr; const char *NextLine = CurPtr; if (C != 0) { // We found a newline, see if it's escaped. const char *EscapePtr = CurPtr - 1; bool HasSpace = false; while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace. --EscapePtr; HasSpace = true; } if (*EscapePtr == '\\') CurPtr = EscapePtr; // Escaped newline. else break; // This is a newline, we're done. } // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to // properly decode the character. Read it in raw mode to avoid emitting // diagnostics about things like trigraphs. If we see an escaped newline, // we'll handle it below. const char *OldPtr = CurPtr; C = getAndAdvanceChar(CurPtr, Result); // If we only read only one character, then no special handling is needed. // We're done and can skip forward to the newline. if (C != 0 && CurPtr == OldPtr + 1) { CurPtr = NextLine; break; } // If we read multiple characters, and one of those characters was a \r or // \n, then we had an escaped newline within the comment. Emit diagnostic // unless the next line is also a // comment. if (CurPtr != OldPtr + 1 && C != '/' && (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) { for (; OldPtr != CurPtr; ++OldPtr) if (OldPtr[0] == '\n' || OldPtr[0] == '\r') { // Okay, we found a // comment that ends in a newline, if the next // line is also a // comment, but has spaces, don't emit a diagnostic. if (isWhitespace(C)) { const char *ForwardPtr = CurPtr; while (isWhitespace(*ForwardPtr)) ++ForwardPtr; // Skip Whitespace if (ForwardPtr[0] == '#' || (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')) break; } } } if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) { --CurPtr; break; } } // Otherwise, eat the \n character. We don't care if this is a \n\r or // \r\n sequence. This is an efficiency hack (because we know the \n can't // contribute to another token), it isn't needed for correctness. Note that // this is ok even in KeepWhitespaceMode, because we would have returned the /// comment above in that mode. if (C != '\0') ++CurPtr; // The next returned token is at the start of the line. Result.setFlag(Token::StartOfLine); TokAtPhysicalStartOfLine = true; // No leading whitespace seen so far. Result.clearFlag(Token::LeadingSpace); BufferPtr = CurPtr; return false; } /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline /// character (either \\n or \\r) is part of an escaped newline sequence. Issue /// a diagnostic if so. We know that the newline is inside of a block comment. static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L) { assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); // Back up off the newline. --CurPtr; // If this is a two-character newline sequence, skip the other character. if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { // \n\n or \r\r -> not escaped newline. if (CurPtr[0] == CurPtr[1]) return false; // \n\r or \r\n -> skip the newline. --CurPtr; } // If we have horizontal whitespace, skip over it. We allow whitespace // between the slash and newline. bool HasSpace = false; while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) { --CurPtr; HasSpace = true; } // If we have a slash, we know this is an escaped newline. if (*CurPtr == '\\') { if (CurPtr[-1] != '*') return false; } return true; } /// We have just read from input the / and * characters that started a comment. /// Read until we find the * and / characters that terminate the comment. /// Note that we don't bother decoding trigraphs or escaped newlines in block /// comments, because they cannot cause the comment to end. The only thing /// that can happen is the comment could end with an escaped newline between /// the terminating * and /. /// /// If we're in KeepCommentMode or any CommentHandler has inserted /// some tokens, this will store the first token and return true. bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // Scan one character past where we should, looking for a '/' character. Once // we find it, check to see if it was preceded by a *. This common // optimization helps people who like to put a lot of * characters in their // comments. // The first character we get with newlines and trigraphs skipped to handle // the degenerate /*/ case below correctly if the * has an escaped newline // after it. unsigned CharSize; unsigned char C = getCharAndSize(CurPtr, CharSize); CurPtr += CharSize; if (C == 0 && CurPtr == BufferEnd + 1) { --CurPtr; BufferPtr = CurPtr; return false; } // Check to see if the first character after the '/*' is another /. If so, // then this slash does not end the block comment, it is part of it. if (C == '/') C = *CurPtr++; while (true) { // Loop to scan the remainder. while (C != '/' && C != '\0') C = *CurPtr++; if (C == '/') { FoundSlash: if (CurPtr[-2] == '*') // We found the final */ We're done! break; if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this)) { // We found the final */, though it had an escaped newline between the // * and /. We're done! break; } } } else if (C == 0 && CurPtr == BufferEnd + 1) { // Note: the user probably forgot a */. We could continue immediately // after the /*, but this would involve lexing a lot of what really is the // comment, which surely would confuse the parser. --CurPtr; BufferPtr = CurPtr; return false; } C = *CurPtr++; } // It is common for the tokens immediately after a /**/ comment to be // whitespace. Instead of going through the big switch, handle it // efficiently now. This is safe even in KeepWhitespaceMode because we would // have already returned above with the comment as a token. if (isHorizontalWhitespace(*CurPtr)) { SkipWhitespace(Result, CurPtr + 1, TokAtPhysicalStartOfLine); return false; } // Otherwise, just return so that the next character will be lexed as a token. BufferPtr = CurPtr; Result.setFlag(Token::LeadingSpace); return false; } /// LexEndOfFile - CurPtr points to the end of this file. Handle this /// condition, reporting diagnostics and handling other edge cases as required. /// This returns true if Result contains a token, false if PP.Lex should be /// called again. bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { Result.startToken(); BufferPtr = BufferEnd; FormTokenWithChars(Result, BufferEnd, tok::eof); return true; } unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { unsigned Size = 0; while (latino::isWhitespace(Ptr[Size])) { ++Size; if (Ptr[Size - 1] != '\n' && Ptr[Size] != '\r') continue; if ((Ptr[Size] == '\n' || Ptr[Size] == '\r') && Ptr[Size - 1] != Ptr[Size]) ++Size; return Size; } return Size; } /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer, /// get its size, and return it. This is tricky in several cases: /// 1. If currently at the start of a trigraph, we warn about the trigraph, /// then either return the trigraph (skipping 3 chars) or the '?', /// depending on whether trigraphs are enabled or not. /// 2. If this is an escaped newline (potentially with whitespace between /// the backslash and newline), implicitly skip the newline and return /// the char after it. /// /// This handles the slow/uncommon case of the getCharAndSize method. Here we /// know that we can accumulate into Size, and that we have already incremented /// Ptr by Size bytes. /// /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should /// be updated to match. char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok) { // If we have a slash, look for an escaped newline. if (Ptr[0] == '\\') { ++Size; ++Ptr; if (!latino::isWhitespace(Ptr[0])) return '\\'; if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { if (Tok) Tok->setFlag(Token::NeedsCleaning); Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; return getCharAndSizeSlow(Ptr, Size, Tok); } return '\\'; } ++Size; return *Ptr; } /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size, /// and that we have already incremented Ptr by Size bytes. /// /// NOTE: When this method is updated, getCharAndSizeSlow (above) should /// be updated to match. char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts) { // If we have a slash, look for an escaped newline. if (Ptr[0] == '\\') { ++Size; ++Ptr; // Slash: // Common case, backslash-char where the char is not whitespace. if (!isWhitespace(Ptr[0])) return '\\'; // See if we have optional whitespace characters followed by a newline. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { // Found backslash<whitespace><newline>. Parse the char after it. Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; // Use slow version to accumulate a correct size field. return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts); } // Otherwise, this is not an escaped newline, just return the slash. return '\\'; } /* // If this is a trigraph, process it. if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { // If this is actually a legal trigraph (not something like "??x"), return // it. if (char C = GetTrigraphCharForLetter(Ptr[2])) { Ptr += 3; Size += 3; if (C == '\\') goto Slash; return C; } } */ // If this is neither, return a single character. ++Size; return *Ptr; } static size_t getSpellingSlow(const Token &Tok, const char *BufPtr, const LangOptions &LangOpts, char *Spelling) { assert(Tok.needsCleaning() && "getSpellingSlow called on simple token"); size_t Length = 0; const char *BufEnd = BufPtr + Tok.getLength(); if (tok::isStringLiteral(Tok.getKind())) { while (BufPtr < BufEnd) { unsigned Size; Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); BufPtr += Size; if (Spelling[Length - 1] == '"') break; } if (Length >= 2 && Spelling[Length - 1] == '"') { const char *RawEnd = BufEnd; do --RawEnd; while (*RawEnd != '"'); size_t RawLength = RawEnd - BufPtr + 1; memcpy(Spelling + Length, BufPtr, RawLength); Length += RawLength; BufPtr += RawLength; } } while (BufPtr < BufEnd) { unsigned Size; Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); BufPtr += Size; } assert(Length < Tok.getLength() && "NeedsCleaning flag set on token that didn't needs cleaning!"); return Length; } /// getSpelling() - Return the 'spelling' of this token. The spelling of a /// token are the characters used to represent the token in the source file /// after trigraph expansion and escaped-newline folding. In particular, this /// wants to get the true, uncanonicalized, spelling of things like digraphs /// UCNs, etc. std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid) { assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); bool CharDataInvalid = false; const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid); if (Invalid) *Invalid = CharDataInvalid; if (CharDataInvalid) return {}; // If this token contains nothing interesting, return it directly. if (!Tok.needsCleaning()) return std::string(TokStart, TokStart + Tok.getLength()); std::string Result; Result.resize(Tok.getLength()); Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin())); return Result; } bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr) { static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars( UnicodeWhitespaceCharRanges); /*if (!isLexingRawMode() && UnicodeWhitespaceChars.contains(C)) { Result.setFlag(Token::LeadingSpace); return true; }*/ return false; } bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) { assert(latino::isVerticalWhitespace(Str[0])); if (Str - 1 < BufferStart) return false; if ((Str[0] == '\n' && Str[-1] == '\r') || (Str[0] == '\r' && Str[-1] == '\n')) { if (Str - 2 < BufferStart) return false; --Str; } --Str; while (Str > BufferStart && latino::isHorizontalWhitespace(*Str)) --Str; return *Str == '\\'; } static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) { const char *BufStart = Buffer.data(); if (Offset >= Buffer.size()) return nullptr; const char *LexStart = BufStart + Offset; for (; LexStart != BufStart; --LexStart) { if (latino::isVerticalWhitespace(LexStart[0]) && !Lexer::isNewLineEscaped(BufStart, LexStart)) { ++LexStart; break; } } return LexStart; } static SourceLocation getBeginningOfFileToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { assert(Loc.isFileID()); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (LocInfo.first.isInvalid()) return Loc; bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) return Loc; // Back up from the current location until we hit the beginning of a line // (or the buffer). We'll relex from that point. const char *StrData = Buffer.data() + LocInfo.second; const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second); if (!LexStart || LexStart == StrData) return Loc; // Create a lexer starting at the beginning of this token. SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second); Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart, Buffer.end()); // TheLexer.SetCommentRetentionState(true); // Lex tokens until we find the token that contains the source location. Token TheTok; do { TheLexer.LexFromRawLexer(TheTok); if (TheLexer.getBufferLocation() > StrData) { // Lexing this token has taken the lexer past the source location we're // looking for. If the current token encompasses our source location, // return the beginning of that token. if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData) return TheTok.getLocation(); // We ended up skipping over the source location entirely, which means // that it points into whitespace. We're done here. break; } } while (TheTok.getKind() != tok::eof); // We've passed our source location; just return the original source location. return Loc; } SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { if (Loc.isFileID()) return getBeginningOfFileToken(Loc, SM, LangOpts); if (!SM.isMacroArgExpansion(Loc)) return Loc; SourceLocation FileLoc = SM.getSpellingLoc(Loc); SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts); std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc); std::pair<FileID, unsigned> BeginFileLocInfo = SM.getDecomposedLoc(BeginFileLoc); assert(FileLocInfo.first == BeginFileLocInfo.first && FileLocInfo.second >= BeginFileLocInfo.second); return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second); } /*bool Lexer::getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, bool IgnoreWhitespace) { Loc = SM.getExpansionLoc(Loc); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) return true; const char *StrData = Buffer.data() + LocInfo.second; if (!IgnoreWhitespace && latino::isWhitespace(StrData[0])) return true; Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Buffer.begin(), StrData, Buffer.end()); TheLexer.SetCommentRetentionState(true); TheLexer.LexFromRawLexer(Result); return false; }*/ /*unsigned Lexer::MeasureTokenLength(SourceLocation Loc, const SourceManager &SM) { Token TheTok; if (getRawToken(Loc, TheTok, SM)) return 0; return TheTok.getLength(); }*/ /*SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM) { if (Loc.isInvalid()) return SourceLocation(); unsigned Len = Lexer::MeasureTokenLength(Loc, SM); if (Len > Offset) Len = Len - Offset; else return Loc; return Loc.getFileLoc(Len); }*/ /*static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range, const SourceManager &SM) { SourceLocation Begin = Range.getBegin(); SourceLocation End = Range.getEnd(); assert(Begin.isFileID() && End.isFileID()); if (Range.isTokenRange()) { End = Lexer::getLocForEndOfToken(End, 0, SM); if (End.isInvalid()) return CharSourceRange(); } FileID FID; unsigned BeginOffs; std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin); if (FID.isInvalid()) return CharSourceRange(); unsigned EndOffs; if (!SM.isInFileID(End, FID, &EndOffs) || BeginOffs > EndOffs) return CharSourceRange(); return CharSourceRange::getCharRange(Begin, End); } */ /*CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range, const SourceManager &SM) { SourceLocation Begin = Range.getBegin(); SourceLocation End = Range.getEnd(); if (Begin.isInvalid() || End.isInvalid()) return CharSourceRange(); if (Begin.isFileID() && End.isFileID()) return makeRangeFromFileLocs(Range, SM); bool Invalid = false; const latino::SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin), &Invalid); if (Invalid) return CharSourceRange(); return CharSourceRange(); }*/ void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) { BufferPtr = BufferStart + Offset; if (BufferPtr > BufferEnd) BufferPtr = BufferEnd; IsAtStartOfLine = StartOfLine; IsAtPhysicalStartOfLine = StartOfLine; } /// LexTokenInternal - This implements a simple C family lexer. It is an /// extremely performance critical piece of code. This assumes that the buffer /// has a null character at the end of the file. This returns a preprocessing /// token, not a normal token, as such, it is an internal interface. It assumes /// that the Flags of result have been cleared before calling this. bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) { unsigned int SizeTmp, SizeTmp2; LexNextToken: Result.clearFlag(Token::NeedsCleaning); Result.setIdentifierInfo(nullptr); const char *CurPtr = BufferPtr; if ((*CurPtr == ' ') || (*CurPtr == '\t')) { ++CurPtr; while ((*CurPtr == ' ') || (*CurPtr == '\t')) ++CurPtr; /*if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; }*/ BufferPtr = CurPtr; Result.setFlag(Token::LeadingSpace); } char Char = getAndAdvanceChar(CurPtr, Result); tok::TokenKind Kind; switch (Char) { case 0: if (CurPtr - 1 == BufferEnd) return LexEndOfFile(Result, CurPtr - 1); Result.setFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; goto LexNextToken; case '\r': if (CurPtr[0] == '\n') Char = getAndAdvanceChar(CurPtr, Result); LLVM_FALLTHROUGH; case '\n': Result.clearFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; goto LexNextToken; case ' ': case '\t': case '\f': case '\v': SkipHorizontalWhitespace: Result.setFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; SkipIgnoreUnits: CurPtr = BufferPtr; if (CurPtr[0] == '#') { if (SkipLineComment(Result, CurPtr + 1, TokAtPhysicalStartOfLine)) return true; } else if (CurPtr[0] == '/' && CurPtr[1] == '/') { if (SkipLineComment(Result, CurPtr + 2, TokAtPhysicalStartOfLine)) return true; // goto SkipIgnoreUnits; } else if (CurPtr[0] == '/' && CurPtr[1] == '*') { if (SkipBlockComment(Result, CurPtr + 2, TokAtPhysicalStartOfLine)) return true; goto SkipIgnoreUnits; } else if (latino::isHorizontalWhitespace(*CurPtr)) { goto SkipHorizontalWhitespace; } goto LexNextToken; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return LexNumericConstant(Result, CurPtr); case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '_': return LexIdentifier(Result, CurPtr); case '#': if (SkipLineComment(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; goto LexNextToken; case '\'': return LexCharConstant(Result, CurPtr, tok::char_constant); case '\"': return LexStringLiteral(Result, CurPtr, tok::string_literal); case '?': Kind = tok::question; break; case '[': Kind = tok::l_square; break; case ']': Kind = tok::r_square; break; case '(': Kind = tok::l_paren; break; case ')': Kind = tok::r_paren; break; case '{': Kind = tok::l_brace; break; case '}': Kind = tok::r_brace; break; case '.': Char = getCharAndSize(CurPtr, SizeTmp); if (Char >= '0' && Char <= '9') { return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); } else if (Char == '.' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '.') { Kind = tok::ellipsis; CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else if (Char == '.') { Kind = tok::periodperiod; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::period; } break; case '&': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '&') { Kind = tok::ampamp; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } break; case '*': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::starequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::star; } break; case '+': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '+') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::plusplus; } else if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::plusequal; } else { Kind = tok::plus; } break; case '-': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '-') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::minusminus; } else if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::minusequal; } else { Kind = tok::minus; } break; case '~': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::tildeequal; } break; case '!': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::exclaimequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::exclaim; } break; case '/': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '/') { if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), TokAtPhysicalStartOfLine)) return true; goto SkipIgnoreUnits; } if (Char == '*') { if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), TokAtPhysicalStartOfLine)) return true; goto LexNextToken; } if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::slashequal; } else { Kind = tok::slash; } break; case '%': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { Kind = tok::percentequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::percent; } break; case '<': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::lessequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::less; } break; case '>': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::greaterequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::greater; } break; case '|': if (getCharAndSize(CurPtr, SizeTmp) == '|') { Kind = tok::pipepipe; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } break; case ':': Kind = tok::colon; break; case ';': Kind = tok::semi; break; case '=': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { Kind = tok::equalequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::equal; } break; case ',': Kind = tok::comma; break; default: if (latino::isASCII(Char)) { Kind = tok::unknown; break; } llvm::UTF32 CodePoint; --CurPtr; llvm::ConversionResult Status = llvm::convertUTF8Sequence( (const llvm::UTF8 **)&CurPtr, (const llvm::UTF8 *)BufferEnd, &CodePoint, llvm::strictConversion); if (Status == llvm::conversionOK) { if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) { if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; goto LexNextToken; } return LexUnicode(Result, CodePoint, CurPtr); } BufferPtr = CurPtr + 1; goto LexNextToken; } /* end switch */ FormTokenWithChars(Result, CurPtr, Kind); return true; }
32.787582
80
0.628526
MelvinG24
9c008761a4ea0029f4ed43ab696820a5ad4c27d8
5,671
cpp
C++
Game/Source/Graphics/TextureUtils.cpp
JanVijfhuizen/Data-Oriented-Engine
cf0af33249a5b81a28adb8e3502e426d112934ba
[ "MIT" ]
null
null
null
Game/Source/Graphics/TextureUtils.cpp
JanVijfhuizen/Data-Oriented-Engine
cf0af33249a5b81a28adb8e3502e426d112934ba
[ "MIT" ]
null
null
null
Game/Source/Graphics/TextureUtils.cpp
JanVijfhuizen/Data-Oriented-Engine
cf0af33249a5b81a28adb8e3502e426d112934ba
[ "MIT" ]
null
null
null
#include "pch.h" #include "Graphics/TextureUtils.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "StringView.h" #include "VkRenderer/VkApp.h" #include "VkRenderer/VkStackAllocator.h" #include "VkRenderer/VkCommandBufferUtils.h" #include "VkRenderer/VkSyncUtils.h" #include "VkRenderer/VkImageUtils.h" namespace game::texture { VkFormat GetFormat() { return VK_FORMAT_R8G8B8A8_SRGB; } VkImageLayout GetImageLayout() { return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } Texture Load(const EngineOutData& outData, const jlb::StringView path) { auto& app = *outData.app; auto& logicalDevice = app.logicalDevice; auto& vkAllocator = *outData.vkAllocator; // Load pixels. int texWidth, texHeight, texChannels; stbi_uc* pixels = stbi_load(path, &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); const VkDeviceSize imageSize = texWidth * texHeight * 4; assert(pixels); // Create staging buffer. VkBuffer stagingBuffer; VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = imageSize; bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; auto result = vkCreateBuffer(logicalDevice, &bufferInfo, nullptr, &stagingBuffer); assert(!result); VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(logicalDevice, stagingBuffer, &memRequirements); const auto stagingPoolId = vkAllocator.GetPoolId(app, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); const auto stagingMemBlock = vkAllocator.AllocateBlock(app, memRequirements.size, memRequirements.alignment, stagingPoolId); result = vkBindBufferMemory(logicalDevice, stagingBuffer, stagingMemBlock.memory, stagingMemBlock.offset); assert(!result); // Copy pixels to staging buffer. void* data; vkMapMemory(logicalDevice, stagingMemBlock.memory, stagingMemBlock.offset, imageSize, 0, &data); memcpy(data, pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(logicalDevice, stagingMemBlock.memory); // Free pixels. stbi_image_free(pixels); // Create image. auto imageInfo = vk::image::CreateDefaultInfo({texWidth, texHeight}, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); VkImage image; result = vkCreateImage(logicalDevice, &imageInfo, nullptr, &image); assert(!result); vkGetImageMemoryRequirements(logicalDevice, image, &memRequirements); const auto poolId = vkAllocator.GetPoolId(app, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); const auto memBlock = vkAllocator.AllocateBlock(app, memRequirements.size, memRequirements.alignment, poolId); result = vkBindImageMemory(logicalDevice, image, memBlock.memory, memBlock.offset); assert(!result); // Start transfer. VkCommandBuffer cmdBuffer; auto cmdBufferAllocInfo = vk::cmdBuffer::CreateDefaultInfo(app); result = vkAllocateCommandBuffers(app.logicalDevice, &cmdBufferAllocInfo, &cmdBuffer); assert(!result); VkFence fence; auto fenceInfo = vk::sync::CreateFenceDefaultInfo(); result = vkCreateFence(app.logicalDevice, &fenceInfo, nullptr, &fence); assert(!result); result = vkResetFences(app.logicalDevice, 1, &fence); assert(!result); // Begin recording. auto cmdBeginInfo = vk::cmdBuffer::CreateBeginDefaultInfo(); vkBeginCommandBuffer(cmdBuffer, &cmdBeginInfo); vk::image::TransitionLayout(image, cmdBuffer, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); vk::image::CopyBufferToImage(stagingBuffer, image, cmdBuffer, { texWidth, texHeight }); vk::image::TransitionLayout(image, cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); // End recording. result = vkEndCommandBuffer(cmdBuffer); assert(!result); // Submit. auto cmdSubmitInfo = vk::cmdBuffer::CreateSubmitDefaultInfo(cmdBuffer); result = vkQueueSubmit(app.queues.graphics, 1, &cmdSubmitInfo, fence); assert(!result); result = vkWaitForFences(logicalDevice, 1, &fence, VK_TRUE, UINT64_MAX); assert(!result); vkDestroyFence(logicalDevice, fence, nullptr); // Destroy staging buffer. vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr); vkAllocator.FreeBlock(stagingMemBlock); Texture texture{}; texture.image = image; texture.memBlock = memBlock; texture.resolution = { texWidth, texHeight }; return texture; } SubTexture GenerateSubTexture(const Texture& texture, const size_t chunkSize, const glm::ivec2 lTop, const glm::ivec2 rBot) { const float xMul = static_cast<float>(chunkSize) / texture.resolution.x; const float yMul = static_cast<float>(chunkSize) / texture.resolution.y; SubTexture sub{}; sub.leftTop.x = xMul * lTop.x; sub.leftTop.y = yMul * lTop.y; sub.rightBot.x = xMul * rBot.x; sub.rightBot.y = yMul * rBot.y; return sub; } SubTexture GenerateSubTexture(const Texture& texture, const size_t chunkSize, const size_t index) { const glm::ivec2 lTop = IndexToCoordinates(texture, chunkSize, index); return GenerateSubTexture(texture, chunkSize, lTop, lTop + glm::ivec2{1, 1}); } glm::ivec2 IndexToCoordinates(const Texture& texture, const size_t chunkSize, const size_t index) { const glm::ivec2 resolution = texture.resolution / glm::ivec2{chunkSize, chunkSize}; return { index % resolution.x, index / resolution.x }; } void Free(const EngineOutData& outData, Texture& texture) { vkDestroyImage(outData.app->logicalDevice, texture.image, nullptr); outData.vkAllocator->FreeBlock(texture.memBlock); } }
35.892405
155
0.771822
JanVijfhuizen
9c02ecc280f407167c3137ad329a449cc14e6d6b
22,341
hpp
C++
routing/index_graph_starter_joints.hpp
seckalou/fonekk_pub
5f2464229d2e3f7ef67aaa5dddb341fea8dd3d2f
[ "Apache-2.0" ]
1
2019-05-27T02:45:22.000Z
2019-05-27T02:45:22.000Z
routing/index_graph_starter_joints.hpp
Mahmoudabdelmobdy/omim
1d444650803b27e507b5e9532551d41bab621a53
[ "Apache-2.0" ]
null
null
null
routing/index_graph_starter_joints.hpp
Mahmoudabdelmobdy/omim
1d444650803b27e507b5e9532551d41bab621a53
[ "Apache-2.0" ]
null
null
null
#pragma once #include "routing/base/astar_graph.hpp" #include "routing/fake_feature_ids.hpp" #include "routing/index_graph_starter.hpp" #include "routing/joint_segment.hpp" #include "routing/segment.hpp" #include "geometry/point2d.hpp" #include "base/assert.hpp" #include <algorithm> #include <limits> #include <map> #include <queue> #include <set> #include <vector> #include "boost/optional.hpp" namespace routing { template <typename Graph> class IndexGraphStarterJoints : public AStarGraph<JointSegment, JointEdge, RouteWeight> { public: explicit IndexGraphStarterJoints(Graph & graph) : m_graph(graph) {} IndexGraphStarterJoints(Graph & graph, Segment const & startSegment, Segment const & endSegment); IndexGraphStarterJoints(Graph & graph, Segment const & startSegment); void Init(Segment const & startSegment, Segment const & endSegment); m2::PointD const & GetPoint(JointSegment const & jointSegment, bool start); JointSegment const & GetStartJoint() const { return m_startJoint; } JointSegment const & GetFinishJoint() const { return m_endJoint; } // AStarGraph overridings // @{ RouteWeight HeuristicCostEstimate(Vertex const & from, Vertex const & to) override; void GetOutgoingEdgesList(Vertex const & vertex, std::vector<Edge> & edges) override { GetEdgeList(vertex, true /* isOutgoing */, edges); } void GetIngoingEdgesList(Vertex const & vertex, std::vector<Edge> & edges) override { GetEdgeList(vertex, false /* isOutgoing */, edges); } void SetAStarParents(bool forward, std::map<Vertex, Vertex> & parents) override { m_graph.SetAStarParents(forward, parents); } bool AreWavesConnectible(std::map<Vertex, Vertex> & forwardParents, Vertex const & commonVertex, std::map<Vertex, Vertex> & backwardParents) override { auto converter = [&](JointSegment const & vertex) { ASSERT(!vertex.IsRealSegment(), ()); auto const it = m_fakeJointSegments.find(vertex); ASSERT(it != m_fakeJointSegments.cend(), ()); auto const & first = it->second.GetSegment(true /* start */); if (first.IsRealSegment()) return first.GetFeatureId(); auto const & second = it->second.GetSegment(false /* start */); return second.GetFeatureId(); }; return m_graph.AreWavesConnectible(forwardParents, commonVertex, backwardParents, std::move(converter)); } // @} WorldGraphMode GetMode() const { return m_graph.GetMode(); } /// \brief Reconstructs JointSegment by segment after building the route. std::vector<Segment> ReconstructJoint(JointSegment const & joint); void Reset(); // Can not check segment for fake or not with segment.IsRealSegment(), because all segments // have got fake m_numMwmId during mwm generation. bool IsRealSegment(Segment const & segment) const { return segment.GetFeatureId() != FakeFeatureIds::kIndexGraphStarterId; } Segment const & GetSegmentOfFakeJoint(JointSegment const & joint, bool start); ~IndexGraphStarterJoints() override = default; private: static auto constexpr kInvalidId = JointSegment::kInvalidId; static auto constexpr kInvisibleEndId = kInvalidId - 1; static auto constexpr kInvisibleStartId = kInvalidId - 2; struct FakeJointSegment { FakeJointSegment() = default; FakeJointSegment(Segment const & start, Segment const & end) : m_start(start), m_end(end) {} Segment const & GetSegment(bool start) const { return start ? m_start : m_end; } Segment m_start; Segment m_end; }; void AddFakeJoints(Segment const & segment, bool isOutgoing, std::vector<JointEdge> & edges); void GetEdgeList(JointSegment const & vertex, bool isOutgoing, std::vector<JointEdge> & edges); JointSegment CreateFakeJoint(Segment const & from, Segment const & to); bool IsJoint(Segment const & segment, bool fromStart) const { return m_graph.IsJoint(segment, fromStart); } bool FillEdgesAndParentsWeights(JointSegment const & vertex, bool isOutgoing, size_t & firstFakeId, std::vector<JointEdge> & edges, std::vector<Weight> & parentWeights); boost::optional<Segment> GetParentSegment(JointSegment const & vertex, bool isOutgoing, std::vector<JointEdge> & edges); /// \brief Makes BFS from |startSegment| in direction |fromStart| and find the closest segments /// which end RoadPoints are joints. Thus we build fake joint segments graph. std::vector<JointEdge> FindFirstJoints(Segment const & startSegment, bool fromStart); JointSegment CreateInvisibleJoint(Segment const & segment, bool start); bool IsInvisible(JointSegment const & jointSegment) const { static_assert(kInvisibleStartId < kInvisibleEndId && kInvisibleEndId != kInvalidId, "FakeID's are crossing in JointSegment."); return jointSegment.GetStartSegmentId() == jointSegment.GetEndSegmentId() && (jointSegment.GetStartSegmentId() == kInvisibleStartId || jointSegment.GetStartSegmentId() == kInvisibleEndId) && jointSegment.GetStartSegmentId() != kInvalidId; } // For GetEdgeList from segments. Graph & m_graph; // Fake start and end joints. JointSegment m_startJoint; JointSegment m_endJoint; Segment m_startSegment; Segment m_endSegment; m2::PointD m_startPoint; m2::PointD m_endPoint; // See comments in |GetEdgeList()| about |m_savedWeight|. std::map<JointSegment, Weight> m_savedWeight; // JointSegment consists of two segments of one feature. // FakeJointSegment consists of two segments of different features. // So we create an invalid JointSegment (see |ToFake()| method), that // converts to FakeJointSegments. This std::map is converter. std::map<JointSegment, FakeJointSegment> m_fakeJointSegments; std::map<JointSegment, std::vector<Segment>> m_reconstructedFakeJoints; // List of JointEdges that are outgoing from start. std::vector<JointEdge> m_startOutEdges; // List of incoming to finish. std::vector<JointEdge> m_endOutEdges; uint32_t m_fakeId = 0; bool m_init = false; }; template <typename Graph> IndexGraphStarterJoints<Graph>::IndexGraphStarterJoints(Graph & graph, Segment const & startSegment, Segment const & endSegment) : m_graph(graph), m_startSegment(startSegment), m_endSegment(endSegment) { Init(m_startSegment, m_endSegment); } template <typename Graph> IndexGraphStarterJoints<Graph>::IndexGraphStarterJoints(Graph & graph, Segment const & startSegment) : m_graph(graph), m_startSegment(startSegment), m_endSegment(Segment()) { Init(m_startSegment, m_endSegment); } template <typename Graph> void IndexGraphStarterJoints<Graph>::Init(Segment const & startSegment, Segment const & endSegment) { m_startSegment = startSegment; m_endSegment = endSegment; m_startPoint = m_graph.GetPoint(m_startSegment, true /* front */); m_endPoint = m_graph.GetPoint(m_endSegment, true /* front */); if (IsRealSegment(startSegment)) m_startJoint = CreateInvisibleJoint(startSegment, true /* start */); else m_startJoint = CreateFakeJoint(m_graph.GetStartSegment(), m_graph.GetStartSegment()); if (IsRealSegment(endSegment)) m_endJoint = CreateInvisibleJoint(endSegment, false /* start */); else m_endJoint = CreateFakeJoint(m_graph.GetFinishSegment(), m_graph.GetFinishSegment()); m_reconstructedFakeJoints[m_startJoint] = {m_startSegment}; m_reconstructedFakeJoints[m_endJoint] = {m_endSegment}; m_startOutEdges = FindFirstJoints(startSegment, true /* fromStart */); m_endOutEdges = FindFirstJoints(endSegment, false /* fromStart */); m_savedWeight[m_endJoint] = Weight(0.0); for (auto const & edge : m_endOutEdges) m_savedWeight[edge.GetTarget()] = edge.GetWeight(); m_init = true; } template <typename Graph> RouteWeight IndexGraphStarterJoints<Graph>::HeuristicCostEstimate(JointSegment const & from, JointSegment const & to) { Segment const & fromSegment = from.IsFake() || IsInvisible(from) ? m_fakeJointSegments[from].GetSegment(false /* start */) : from.GetSegment(false /* start */); Segment const & toSegment = to.IsFake() || IsInvisible(to) ? m_fakeJointSegments[to].GetSegment(false /* start */) : to.GetSegment(false /* start */); ASSERT(toSegment == m_startSegment || toSegment == m_endSegment, ("Invariant violated.")); return toSegment == m_startSegment ? m_graph.HeuristicCostEstimate(fromSegment, m_startPoint) : m_graph.HeuristicCostEstimate(fromSegment, m_endPoint); } template <typename Graph> m2::PointD const & IndexGraphStarterJoints<Graph>::GetPoint(JointSegment const & jointSegment, bool start) { Segment segment = jointSegment.IsFake() ? m_fakeJointSegments[jointSegment].GetSegment(start) : jointSegment.GetSegment(start); return m_graph.GetPoint(segment, jointSegment.IsForward()); } template <typename Graph> std::vector<Segment> IndexGraphStarterJoints<Graph>::ReconstructJoint(JointSegment const & joint) { // We have invisible JointSegments, which are come from start to start or end to end. // They need just for generic algorithm working. So we skip such objects. if (IsInvisible(joint)) return {}; // In case of a fake vertex we return its prebuilt path. if (joint.IsFake()) { auto const it = m_reconstructedFakeJoints.find(joint); CHECK(it != m_reconstructedFakeJoints.cend(), ("Can not find such fake joint")); return it->second; } // Otherwise just reconstruct segment consequently. std::vector<Segment> subpath; Segment currentSegment = joint.GetSegment(true /* start */); Segment lastSegment = joint.GetSegment(false /* start */); bool const forward = currentSegment.GetSegmentIdx() < lastSegment.GetSegmentIdx(); while (currentSegment != lastSegment) { subpath.emplace_back(currentSegment); currentSegment.Next(forward); } subpath.emplace_back(lastSegment); return subpath; } template <typename Graph> void IndexGraphStarterJoints<Graph>::AddFakeJoints(Segment const & segment, bool isOutgoing, std::vector<JointEdge> & edges) { // If |isOutgoing| is true, we need real segments, that are real parts // of fake joints, entered to finish and vice versa. std::vector<JointEdge> const & endings = isOutgoing ? m_endOutEdges : m_startOutEdges; bool const opposite = !isOutgoing; for (auto const & edge : endings) { // The one end of FakeJointSegment is start/finish and the opposite end is real segment. // So we check, whether |segment| is equal to the real segment of FakeJointSegment. // If yes, that means, that we can go from |segment| to start/finish. Segment const & firstSegment = m_fakeJointSegments[edge.GetTarget()].GetSegment(!opposite /* start */); if (firstSegment == segment) { edges.emplace_back(edge); return; } } } template <typename Graph> Segment const & IndexGraphStarterJoints<Graph>::GetSegmentOfFakeJoint(JointSegment const & joint, bool start) { auto const it = m_fakeJointSegments.find(joint); CHECK(it != m_fakeJointSegments.cend(), ("No such fake joint:", joint, "in JointStarter.")); return (it->second).GetSegment(start); } template <typename Graph> boost::optional<Segment> IndexGraphStarterJoints<Graph>::GetParentSegment(JointSegment const & vertex, bool isOutgoing, std::vector<JointEdge> & edges) { boost::optional<Segment> parentSegment; bool const opposite = !isOutgoing; if (vertex.IsFake()) { CHECK(m_fakeJointSegments.find(vertex) != m_fakeJointSegments.end(), ("No such fake joint:", vertex, "in JointStarter.")); FakeJointSegment fakeJointSegment = m_fakeJointSegments[vertex]; auto const & startSegment = isOutgoing ? m_startSegment : m_endSegment; auto const & endSegment = isOutgoing ? m_endSegment : m_startSegment; auto const & endJoint = isOutgoing ? GetFinishJoint() : GetStartJoint(); // This is case when we can build route from start to finish without real segment, only fake. // It happens when start and finish are close to each other. // If we want A* stop, we should add |endJoint| to its queue, then A* will see the vertex: |endJoint| // where it has already been and stop working. if (fakeJointSegment.GetSegment(opposite /* start */) == endSegment) { if (isOutgoing) { static auto constexpr kZeroWeight = RouteWeight(0.0); edges.emplace_back(endJoint, kZeroWeight); } else { auto const it = m_savedWeight.find(vertex); CHECK(it != m_savedWeight.cend(), ("Can not find weight for:", vertex)); Weight const & weight = it->second; edges.emplace_back(endJoint, weight); } return {}; } CHECK(fakeJointSegment.GetSegment(!opposite /* start */) == startSegment, ()); parentSegment = fakeJointSegment.GetSegment(opposite /* start */); } else { parentSegment = vertex.GetSegment(opposite /* start */); } return parentSegment; } template <typename Graph> bool IndexGraphStarterJoints<Graph>::FillEdgesAndParentsWeights(JointSegment const & vertex, bool isOutgoing, size_t & firstFakeId, std::vector<JointEdge> & edges, std::vector<Weight> & parentWeights) { // Case of fake start or finish joints. // Note: startJoint and finishJoint are just loops // from start to start or end to end vertex. if (vertex == GetStartJoint()) { edges.insert(edges.end(), m_startOutEdges.begin(), m_startOutEdges.end()); parentWeights.insert(parentWeights.end(), edges.size(), Weight(0.0)); firstFakeId = edges.size(); } else if (vertex == GetFinishJoint()) { edges.insert(edges.end(), m_endOutEdges.begin(), m_endOutEdges.end()); // If vertex is FinishJoint, parentWeight is equal to zero, because the first vertex is zero-weight loop. parentWeights.insert(parentWeights.end(), edges.size(), Weight(0.0)); } else { auto const optional = GetParentSegment(vertex, isOutgoing, edges); if (!optional) return false; Segment parentSegment = optional.value(); std::vector<JointEdge> jointEdges; m_graph.GetEdgeList(vertex, parentSegment, isOutgoing, jointEdges, parentWeights); edges.insert(edges.end(), jointEdges.begin(), jointEdges.end()); firstFakeId = edges.size(); bool const opposite = !isOutgoing; for (size_t i = 0; i < jointEdges.size(); ++i) { size_t prevSize = edges.size(); AddFakeJoints(jointEdges[i].GetTarget().GetSegment(!opposite /* start */), isOutgoing, edges); // If we add fake edge, we should add new parentWeight as "child[i] -> parent". // Because fake edge and current edge (jointEdges[i]) have the same first // segments (differ only the ends), so we add to |parentWeights| the same // value: parentWeights[i]. if (edges.size() != prevSize) { CHECK_LESS(i, parentWeights.size(), ()); parentWeights.emplace_back(parentWeights[i]); } } } return true; } template <typename Graph> void IndexGraphStarterJoints<Graph>::GetEdgeList(JointSegment const & vertex, bool isOutgoing, std::vector<JointEdge> & edges) { CHECK(m_init, ("IndexGraphStarterJoints was not initialized.")); edges.clear(); // This vector needs for backward A* search. Assume, we have parent and child_1, child_2. // In this case we will save next weights: // 1) from child_1 to parent. // 2) from child_2 to parent. // That needs for correct edges weights calculation. std::vector<Weight> parentWeights; size_t firstFakeId = 0; if (!FillEdgesAndParentsWeights(vertex, isOutgoing, firstFakeId, edges, parentWeights)) return; if (!isOutgoing) { // |parentSegment| is parent-vertex from which we search children. // For correct weight calculation we should get weight of JointSegment, that // ends in |parentSegment| and add |parentWeight[i]| to the saved value. auto const it = m_savedWeight.find(vertex); CHECK(it != m_savedWeight.cend(), ("Can not find weight for:", vertex)); Weight const & weight = it->second; for (size_t i = 0; i < edges.size(); ++i) { // Saving weight of current edges for returning in the next iterations. m_savedWeight[edges[i].GetTarget()] = edges[i].GetWeight(); // For parent JointSegment we know its weight without last segment, because for each child // it will differ (child_1 => parent != child_2 => parent), but (!) we save this weight in // |parentWeights[]|. So the weight of an ith edge is a cached "weight of parent JointSegment" + // "parentWeight[i]". CHECK_LESS(i, parentWeights.size(), ()); edges[i].GetWeight() = weight + parentWeights[i]; } // Delete useless weight of parent JointSegment. m_savedWeight.erase(it); } else { // This needs for correct weights calculation of FakeJointSegments during forward A* search. for (size_t i = firstFakeId; i < edges.size(); ++i) edges[i].GetWeight() += parentWeights[i]; } } template <typename Graph> JointSegment IndexGraphStarterJoints<Graph>::CreateFakeJoint(Segment const & from, Segment const & to) { JointSegment jointSegment; jointSegment.ToFake(m_fakeId++); FakeJointSegment fakeJointSegment(from, to); m_fakeJointSegments[jointSegment] = fakeJointSegment; return jointSegment; } template <typename Graph> std::vector<JointEdge> IndexGraphStarterJoints<Graph>::FindFirstJoints(Segment const & startSegment, bool fromStart) { Segment const & endSegment = fromStart ? m_endSegment : m_startSegment; std::queue<Segment> queue; queue.emplace(startSegment); std::map<Segment, Segment> parent; std::map<Segment, RouteWeight> weight; std::vector<JointEdge> result; auto const reconstructPath = [&parent, &startSegment, &endSegment](Segment current, bool forward) { std::vector<Segment> path; // In case we can go from start to finish without joint (e.g. start and finish at // the same long feature), we don't add the last segment to path for correctness // reconstruction of the route. Otherwise last segment will repeat twice. if (current != endSegment) path.emplace_back(current); if (current == startSegment) return path; Segment parentSegment; do { parentSegment = parent[current]; path.emplace_back(parentSegment); current = parentSegment; } while (parentSegment != startSegment); if (forward) std::reverse(path.begin(), path.end()); return path; }; auto const addFake = [&](Segment const & segment, Segment const & beforeConvert) { JointSegment fakeJoint; fakeJoint = fromStart ? CreateFakeJoint(startSegment, segment) : CreateFakeJoint(segment, startSegment); result.emplace_back(fakeJoint, weight[beforeConvert]); std::vector<Segment> path = reconstructPath(beforeConvert, fromStart); m_reconstructedFakeJoints.emplace(fakeJoint, std::move(path)); }; auto const isEndOfSegment = [&](Segment const & fake, Segment const & segment) { CHECK(!IsRealSegment(fake), ()); auto const fakeEnd = m_graph.GetPoint(fake, fake.IsForward()); auto const realEnd = m_graph.GetPoint(segment, segment.IsForward()); static auto constexpr kEps = 1e-5; return base::AlmostEqualAbs(fakeEnd, realEnd, kEps); }; while (!queue.empty()) { Segment segment = queue.front(); queue.pop(); Segment beforeConvert = segment; // Either the segment is fake and it can be converted to real one with |Joint| end (RoadPoint), // or it's the real one and its end (RoadPoint) is |Joint|. if (((!IsRealSegment(segment) && m_graph.ConvertToReal(segment) && isEndOfSegment(beforeConvert, segment)) || IsRealSegment(beforeConvert)) && IsJoint(segment, fromStart)) { addFake(segment, beforeConvert); continue; } if (beforeConvert == endSegment) { addFake(segment, beforeConvert); continue; } std::vector<SegmentEdge> edges; m_graph.GetEdgesList(beforeConvert, fromStart, edges); for (auto const & edge : edges) { Segment child = edge.GetTarget(); auto const & newWeight = weight[beforeConvert] + edge.GetWeight(); if (weight.find(child) == weight.end() || weight[child] > newWeight) { parent[child] = beforeConvert; weight[child] = newWeight; queue.push(child); } } } return result; } template <typename Graph> JointSegment IndexGraphStarterJoints<Graph>::CreateInvisibleJoint(Segment const & segment, bool start) { JointSegment result; result.ToFake(start ? kInvisibleStartId : kInvisibleEndId); m_fakeJointSegments[result] = FakeJointSegment(segment, segment); return result; } template <typename Graph> void IndexGraphStarterJoints<Graph>::Reset() { m_startJoint = JointSegment(); m_endJoint = JointSegment(); m_startSegment = Segment(); m_endSegment = Segment(); m_savedWeight.clear(); m_fakeJointSegments.clear(); m_reconstructedFakeJoints.clear(); m_startOutEdges.clear(); m_endOutEdges.clear(); m_fakeId = 0; m_init = false; } } // namespace routing
35.405705
117
0.670337
seckalou
9c069d07baca0d04d91a6272934606e27d932cee
2,243
cpp
C++
dnn/src/naive/split/split.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
5,168
2020-03-19T06:10:04.000Z
2022-03-31T11:11:54.000Z
dnn/src/naive/split/split.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
286
2020-03-25T01:36:23.000Z
2022-03-31T10:26:33.000Z
dnn/src/naive/split/split.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
515
2020-03-19T06:10:05.000Z
2022-03-30T09:15:59.000Z
/** * \file dnn/src/naive/split/split.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "src/naive/split/opr_impl.h" #include "src/common/utils.h" #include "src/naive/handle.h" #include <numeric> namespace megdnn { namespace naive { template <typename T> void SplitForwardImpl::exec_internal( _megdnn_tensor_in src, const TensorNDArray& dsts, _megdnn_workspace workspace) { size_t A, B, C; size_t* Bv = reinterpret_cast<size_t*>(workspace.raw_ptr); auto dsts_layout = apply_vector<TensorLayout>(m_get_layout, dsts); check_exec(src.layout, dsts_layout, workspace.size); auto dsts_shape = apply_vector<TensorShape>(m_get_shape, dsts_layout); get_ABC(dsts_shape, A, Bv, C); B = std::accumulate(Bv, Bv + dsts.size(), 0u); auto sptr = src.ptr<T>(); rep(a, A) { // dst b index size_t dbi = 0u; // dst b offset size_t dbo = 0u; rep(sb, B) { auto dptr = dsts[dbi].ptr<T>(); rep(c, C) { auto sidx = a * B * C + sb * C + c; auto didx = a * Bv[dbi] * C + dbo * C + c; dptr[didx] = sptr[sidx]; } ++dbo; if (dbo >= Bv[dbi]) { dbo = 0u; ++dbi; } } } } void SplitForwardImpl::exec( _megdnn_tensor_in src, const TensorNDArray& dsts, _megdnn_workspace workspace) { #define cb(DType) \ if (src.layout.dtype.enumv() == DTypeTrait<DType>::enumv) { \ using ctype = typename DTypeTrait<DType>::ctype; \ MEGDNN_DISPATCH_CPU_KERN_OPR(exec_internal<ctype>(src, dsts, workspace)); \ } MEGDNN_FOREACH_COMPUTING_DTYPE(cb) MEGDNN_FOREACH_QUANTIZED_DTYPE(cb) #undef cb } } // namespace naive } // namespace megdnn // vim: syntax=cpp.doxygen
32.507246
89
0.588943
gedoensmax
9c07441de55c192415887232cde2f678a892a56a
17,859
cc
C++
src/runtime/runtime-test-wasm.cc
marsonya/v8
aa13c15f19cdb57643e02b5a2def80162c2200f9
[ "BSD-3-Clause" ]
2
2021-04-19T00:22:26.000Z
2021-04-19T00:23:56.000Z
src/runtime/runtime-test-wasm.cc
marsonya/v8
aa13c15f19cdb57643e02b5a2def80162c2200f9
[ "BSD-3-Clause" ]
5
2021-04-19T10:15:18.000Z
2021-04-28T19:02:36.000Z
src/runtime/runtime-test-wasm.cc
marsonya/v8
aa13c15f19cdb57643e02b5a2def80162c2200f9
[ "BSD-3-Clause" ]
1
2021-03-08T00:27:33.000Z
2021-03-08T00:27:33.000Z
// Copyright 2021 the V8 project 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 "src/base/memory.h" #include "src/base/platform/mutex.h" #include "src/execution/arguments-inl.h" #include "src/execution/frames-inl.h" #include "src/logging/counters.h" #include "src/objects/smi.h" #include "src/runtime/runtime-utils.h" #include "src/trap-handler/trap-handler.h" #include "src/utils/ostreams.h" #include "src/wasm/memory-tracing.h" #include "src/wasm/module-compiler.h" #include "src/wasm/wasm-code-manager.h" #include "src/wasm/wasm-engine.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-objects-inl.h" #include "src/wasm/wasm-serialization.h" namespace v8 { namespace internal { namespace { struct WasmCompileControls { uint32_t MaxWasmBufferSize = std::numeric_limits<uint32_t>::max(); bool AllowAnySizeForAsync = true; }; using WasmCompileControlsMap = std::map<v8::Isolate*, WasmCompileControls>; // We need per-isolate controls, because we sometimes run tests in multiple // isolates concurrently. Methods need to hold the accompanying mutex on access. // To avoid upsetting the static initializer count, we lazy initialize this. DEFINE_LAZY_LEAKY_OBJECT_GETTER(WasmCompileControlsMap, GetPerIsolateWasmControls) base::LazyMutex g_PerIsolateWasmControlsMutex = LAZY_MUTEX_INITIALIZER; bool IsWasmCompileAllowed(v8::Isolate* isolate, v8::Local<v8::Value> value, bool is_async) { base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer()); DCHECK_GT(GetPerIsolateWasmControls()->count(isolate), 0); const WasmCompileControls& ctrls = GetPerIsolateWasmControls()->at(isolate); return (is_async && ctrls.AllowAnySizeForAsync) || (value->IsArrayBuffer() && value.As<v8::ArrayBuffer>()->ByteLength() <= ctrls.MaxWasmBufferSize) || (value->IsArrayBufferView() && value.As<v8::ArrayBufferView>()->ByteLength() <= ctrls.MaxWasmBufferSize); } // Use the compile controls for instantiation, too bool IsWasmInstantiateAllowed(v8::Isolate* isolate, v8::Local<v8::Value> module_or_bytes, bool is_async) { base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer()); DCHECK_GT(GetPerIsolateWasmControls()->count(isolate), 0); const WasmCompileControls& ctrls = GetPerIsolateWasmControls()->at(isolate); if (is_async && ctrls.AllowAnySizeForAsync) return true; if (!module_or_bytes->IsWasmModuleObject()) { return IsWasmCompileAllowed(isolate, module_or_bytes, is_async); } v8::Local<v8::WasmModuleObject> module = v8::Local<v8::WasmModuleObject>::Cast(module_or_bytes); return static_cast<uint32_t>( module->GetCompiledModule().GetWireBytesRef().size()) <= ctrls.MaxWasmBufferSize; } v8::Local<v8::Value> NewRangeException(v8::Isolate* isolate, const char* message) { return v8::Exception::RangeError( v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(message)) .ToLocalChecked()); } void ThrowRangeException(v8::Isolate* isolate, const char* message) { isolate->ThrowException(NewRangeException(isolate, message)); } bool WasmModuleOverride(const v8::FunctionCallbackInfo<v8::Value>& args) { if (IsWasmCompileAllowed(args.GetIsolate(), args[0], false)) return false; ThrowRangeException(args.GetIsolate(), "Sync compile not allowed"); return true; } bool WasmInstanceOverride(const v8::FunctionCallbackInfo<v8::Value>& args) { if (IsWasmInstantiateAllowed(args.GetIsolate(), args[0], false)) return false; ThrowRangeException(args.GetIsolate(), "Sync instantiate not allowed"); return true; } } // namespace // Returns a callable object. The object returns the difference of its two // parameters when it is called. RUNTIME_FUNCTION(Runtime_SetWasmCompileControls) { HandleScope scope(isolate); v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate); CHECK_EQ(args.length(), 2); CONVERT_ARG_HANDLE_CHECKED(Smi, block_size, 0); CONVERT_BOOLEAN_ARG_CHECKED(allow_async, 1); base::MutexGuard guard(g_PerIsolateWasmControlsMutex.Pointer()); WasmCompileControls& ctrl = (*GetPerIsolateWasmControls())[v8_isolate]; ctrl.AllowAnySizeForAsync = allow_async; ctrl.MaxWasmBufferSize = static_cast<uint32_t>(block_size->value()); v8_isolate->SetWasmModuleCallback(WasmModuleOverride); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_SetWasmInstantiateControls) { HandleScope scope(isolate); v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate); CHECK_EQ(args.length(), 0); v8_isolate->SetWasmInstanceCallback(WasmInstanceOverride); return ReadOnlyRoots(isolate).undefined_value(); } namespace { void PrintIndentation(int stack_size) { const int max_display = 80; if (stack_size <= max_display) { PrintF("%4d:%*s", stack_size, stack_size, ""); } else { PrintF("%4d:%*s", stack_size, max_display, "..."); } } int WasmStackSize(Isolate* isolate) { // TODO(wasm): Fix this for mixed JS/Wasm stacks with both --trace and // --trace-wasm. int n = 0; for (StackTraceFrameIterator it(isolate); !it.done(); it.Advance()) { if (it.is_wasm()) n++; } return n; } } // namespace RUNTIME_FUNCTION(Runtime_WasmTraceEnter) { HandleScope shs(isolate); DCHECK_EQ(0, args.length()); PrintIndentation(WasmStackSize(isolate)); // Find the caller wasm frame. wasm::WasmCodeRefScope wasm_code_ref_scope; StackTraceFrameIterator it(isolate); DCHECK(!it.done()); DCHECK(it.is_wasm()); WasmFrame* frame = WasmFrame::cast(it.frame()); // Find the function name. int func_index = frame->function_index(); const wasm::WasmModule* module = frame->wasm_instance().module(); wasm::ModuleWireBytes wire_bytes = wasm::ModuleWireBytes(frame->native_module()->wire_bytes()); wasm::WireBytesRef name_ref = module->lazily_generated_names.LookupFunctionName( wire_bytes, func_index, VectorOf(module->export_table)); wasm::WasmName name = wire_bytes.GetNameOrNull(name_ref); wasm::WasmCode* code = frame->wasm_code(); PrintF(code->is_liftoff() ? "~" : "*"); if (name.empty()) { PrintF("wasm-function[%d] {\n", func_index); } else { PrintF("wasm-function[%d] \"%.*s\" {\n", func_index, name.length(), name.begin()); } return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_WasmTraceExit) { HandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_CHECKED(Smi, value_addr_smi, 0); PrintIndentation(WasmStackSize(isolate)); PrintF("}"); // Find the caller wasm frame. wasm::WasmCodeRefScope wasm_code_ref_scope; StackTraceFrameIterator it(isolate); DCHECK(!it.done()); DCHECK(it.is_wasm()); WasmFrame* frame = WasmFrame::cast(it.frame()); int func_index = frame->function_index(); const wasm::FunctionSig* sig = frame->wasm_instance().module()->functions[func_index].sig; size_t num_returns = sig->return_count(); if (num_returns == 1) { wasm::ValueType return_type = sig->GetReturn(0); switch (return_type.kind()) { case wasm::kI32: { int32_t value = base::ReadUnalignedValue<int32_t>(value_addr_smi.ptr()); PrintF(" -> %d\n", value); break; } case wasm::kI64: { int64_t value = base::ReadUnalignedValue<int64_t>(value_addr_smi.ptr()); PrintF(" -> %" PRId64 "\n", value); break; } case wasm::kF32: { float_t value = base::ReadUnalignedValue<float_t>(value_addr_smi.ptr()); PrintF(" -> %f\n", value); break; } case wasm::kF64: { double_t value = base::ReadUnalignedValue<double_t>(value_addr_smi.ptr()); PrintF(" -> %f\n", value); break; } default: PrintF(" -> Unsupported type\n"); break; } } else { // TODO(wasm) Handle multiple return values. PrintF("\n"); } return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_IsAsmWasmCode) { SealHandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_CHECKED(JSFunction, function, 0); if (!function.shared().HasAsmWasmData()) { return ReadOnlyRoots(isolate).false_value(); } if (function.shared().HasBuiltinId() && function.shared().builtin_id() == Builtins::kInstantiateAsmJs) { // Hasn't been compiled yet. return ReadOnlyRoots(isolate).false_value(); } return ReadOnlyRoots(isolate).true_value(); } namespace { bool DisallowWasmCodegenFromStringsCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { return false; } } // namespace RUNTIME_FUNCTION(Runtime_DisallowWasmCodegen) { SealHandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_BOOLEAN_ARG_CHECKED(flag, 0); v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate); v8_isolate->SetAllowWasmCodeGenerationCallback( flag ? DisallowWasmCodegenFromStringsCallback : nullptr); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_IsWasmCode) { SealHandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_CHECKED(JSFunction, function, 0); bool is_js_to_wasm = function.code().kind() == CodeKind::JS_TO_WASM_FUNCTION || (function.code().is_builtin() && function.code().builtin_index() == Builtins::kGenericJSToWasmWrapper); return isolate->heap()->ToBoolean(is_js_to_wasm); } RUNTIME_FUNCTION(Runtime_IsWasmTrapHandlerEnabled) { DisallowGarbageCollection no_gc; DCHECK_EQ(0, args.length()); return isolate->heap()->ToBoolean(trap_handler::IsTrapHandlerEnabled()); } RUNTIME_FUNCTION(Runtime_IsThreadInWasm) { DisallowGarbageCollection no_gc; DCHECK_EQ(0, args.length()); return isolate->heap()->ToBoolean(trap_handler::IsThreadInWasm()); } RUNTIME_FUNCTION(Runtime_GetWasmRecoveredTrapCount) { HandleScope scope(isolate); DCHECK_EQ(0, args.length()); size_t trap_count = trap_handler::GetRecoveredTrapCount(); return *isolate->factory()->NewNumberFromSize(trap_count); } RUNTIME_FUNCTION(Runtime_GetWasmExceptionId) { HandleScope scope(isolate); DCHECK_EQ(2, args.length()); CONVERT_ARG_HANDLE_CHECKED(WasmExceptionPackage, exception, 0); CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 1); Handle<Object> tag = WasmExceptionPackage::GetExceptionTag(isolate, exception); CHECK(tag->IsWasmExceptionTag()); Handle<FixedArray> exceptions_table(instance->exceptions_table(), isolate); for (int index = 0; index < exceptions_table->length(); ++index) { if (exceptions_table->get(index) == *tag) return Smi::FromInt(index); } UNREACHABLE(); } RUNTIME_FUNCTION(Runtime_GetWasmExceptionValues) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(WasmExceptionPackage, exception, 0); Handle<Object> values_obj = WasmExceptionPackage::GetExceptionValues(isolate, exception); CHECK(values_obj->IsFixedArray()); // Only called with correct input. Handle<FixedArray> values = Handle<FixedArray>::cast(values_obj); return *isolate->factory()->NewJSArrayWithElements(values); } // Wait until the given module is fully tiered up, then serialize it into an // array buffer. RUNTIME_FUNCTION(Runtime_SerializeWasmModule) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(WasmModuleObject, module_obj, 0); wasm::NativeModule* native_module = module_obj->native_module(); native_module->compilation_state()->WaitForTopTierFinished(); DCHECK(!native_module->compilation_state()->failed()); wasm::WasmSerializer wasm_serializer(native_module); size_t byte_length = wasm_serializer.GetSerializedNativeModuleSize(); Handle<JSArrayBuffer> array_buffer = isolate->factory() ->NewJSArrayBufferAndBackingStore(byte_length, InitializedFlag::kUninitialized) .ToHandleChecked(); CHECK(wasm_serializer.SerializeNativeModule( {static_cast<uint8_t*>(array_buffer->backing_store()), byte_length})); return *array_buffer; } // Take an array buffer and attempt to reconstruct a compiled wasm module. // Return undefined if unsuccessful. RUNTIME_FUNCTION(Runtime_DeserializeWasmModule) { HandleScope scope(isolate); DCHECK_EQ(2, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0); CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, wire_bytes, 1); CHECK(!buffer->was_detached()); CHECK(!wire_bytes->WasDetached()); Handle<JSArrayBuffer> wire_bytes_buffer = wire_bytes->GetBuffer(); Vector<const uint8_t> wire_bytes_vec{ reinterpret_cast<const uint8_t*>(wire_bytes_buffer->backing_store()) + wire_bytes->byte_offset(), wire_bytes->byte_length()}; Vector<uint8_t> buffer_vec{ reinterpret_cast<uint8_t*>(buffer->backing_store()), buffer->byte_length()}; // Note that {wasm::DeserializeNativeModule} will allocate. We assume the // JSArrayBuffer backing store doesn't get relocated. MaybeHandle<WasmModuleObject> maybe_module_object = wasm::DeserializeNativeModule(isolate, buffer_vec, wire_bytes_vec, {}); Handle<WasmModuleObject> module_object; if (!maybe_module_object.ToHandle(&module_object)) { return ReadOnlyRoots(isolate).undefined_value(); } return *module_object; } RUNTIME_FUNCTION(Runtime_WasmGetNumberOfInstances) { SealHandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(WasmModuleObject, module_obj, 0); int instance_count = 0; WeakArrayList weak_instance_list = module_obj->script().wasm_weak_instance_list(); for (int i = 0; i < weak_instance_list.length(); ++i) { if (weak_instance_list.Get(i)->IsWeak()) instance_count++; } return Smi::FromInt(instance_count); } RUNTIME_FUNCTION(Runtime_WasmNumCodeSpaces) { DCHECK_EQ(1, args.length()); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, argument, 0); Handle<WasmModuleObject> module; if (argument->IsWasmInstanceObject()) { module = handle(Handle<WasmInstanceObject>::cast(argument)->module_object(), isolate); } else if (argument->IsWasmModuleObject()) { module = Handle<WasmModuleObject>::cast(argument); } size_t num_spaces = module->native_module()->GetNumberOfCodeSpacesForTesting(); return *isolate->factory()->NewNumberFromSize(num_spaces); } RUNTIME_FUNCTION(Runtime_WasmTraceMemory) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_CHECKED(Smi, info_addr, 0); wasm::MemoryTracingInfo* info = reinterpret_cast<wasm::MemoryTracingInfo*>(info_addr.ptr()); // Find the caller wasm frame. wasm::WasmCodeRefScope wasm_code_ref_scope; StackTraceFrameIterator it(isolate); DCHECK(!it.done()); DCHECK(it.is_wasm()); WasmFrame* frame = WasmFrame::cast(it.frame()); uint8_t* mem_start = reinterpret_cast<uint8_t*>( frame->wasm_instance().memory_object().array_buffer().backing_store()); int func_index = frame->function_index(); int pos = frame->position(); // TODO(titzer): eliminate dependency on WasmModule definition here. int func_start = frame->wasm_instance().module()->functions[func_index].code.offset(); wasm::ExecutionTier tier = frame->wasm_code()->is_liftoff() ? wasm::ExecutionTier::kLiftoff : wasm::ExecutionTier::kTurbofan; wasm::TraceMemoryOperation(tier, info, func_index, pos - func_start, mem_start); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_WasmTierUpFunction) { HandleScope scope(isolate); DCHECK_EQ(2, args.length()); CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0); CONVERT_SMI_ARG_CHECKED(function_index, 1); auto* native_module = instance->module_object().native_module(); isolate->wasm_engine()->CompileFunction( isolate, native_module, function_index, wasm::ExecutionTier::kTurbofan); CHECK(!native_module->compilation_state()->failed()); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_WasmTierDown) { HandleScope scope(isolate); DCHECK_EQ(0, args.length()); isolate->wasm_engine()->TierDownAllModulesPerIsolate(isolate); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_WasmTierUp) { HandleScope scope(isolate); DCHECK_EQ(0, args.length()); isolate->wasm_engine()->TierUpAllModulesPerIsolate(isolate); return ReadOnlyRoots(isolate).undefined_value(); } RUNTIME_FUNCTION(Runtime_IsLiftoffFunction) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CHECK(WasmExportedFunction::IsWasmExportedFunction(*function)); Handle<WasmExportedFunction> exp_fun = Handle<WasmExportedFunction>::cast(function); wasm::NativeModule* native_module = exp_fun->instance().module_object().native_module(); uint32_t func_index = exp_fun->function_index(); wasm::WasmCodeRefScope code_ref_scope; wasm::WasmCode* code = native_module->GetCode(func_index); return isolate->heap()->ToBoolean(code && code->is_liftoff()); } RUNTIME_FUNCTION(Runtime_FreezeWasmLazyCompilation) { DCHECK_EQ(1, args.length()); DisallowGarbageCollection no_gc; CONVERT_ARG_CHECKED(WasmInstanceObject, instance, 0); instance.module_object().native_module()->set_lazy_compile_frozen(true); return ReadOnlyRoots(isolate).undefined_value(); } } // namespace internal } // namespace v8
36.521472
80
0.718293
marsonya
9c09634b50cebbf033a4a5fbadd2f270d884a165
18,461
cc
C++
sdk/android/src/jni/pc/peerconnection_jni.cc
ebasdee/webrtc
9b16e2d354e80ca0f2a65ee39464cfc2cf70cbf0
[ "DOC", "BSD-3-Clause" ]
1
2020-06-11T08:50:29.000Z
2020-06-11T08:50:29.000Z
sdk/android/src/jni/pc/peerconnection_jni.cc
ebasdee/webrtc
9b16e2d354e80ca0f2a65ee39464cfc2cf70cbf0
[ "DOC", "BSD-3-Clause" ]
null
null
null
sdk/android/src/jni/pc/peerconnection_jni.cc
ebasdee/webrtc
9b16e2d354e80ca0f2a65ee39464cfc2cf70cbf0
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Lifecycle notes: objects are owned where they will be called; in other words // FooObservers are owned by C++-land, and user-callable objects (e.g. // PeerConnection and VideoTrack) are owned by Java-land. // When this file (or other files in this directory) allocates C++ // RefCountInterfaces it AddRef()s an artificial ref simulating the jlong held // in Java-land, and then Release()s the ref in the respective free call. // Sometimes this AddRef is implicit in the construction of a scoped_refptr<> // which is then .release()d. Any persistent (non-local) references from C++ to // Java must be global or weak (in which case they must be checked before use)! // // Exception notes: pretty much all JNI calls can throw Java exceptions, so each // call through a JNIEnv* pointer needs to be followed by an ExceptionCheck() // call. In this file this is done in CHECK_EXCEPTION, making for much easier // debugging in case of failure (the alternative is to wait for control to // return to the Java frame that called code in this file, at which point it's // impossible to tell which JNI call broke). #include <limits> #include <memory> #include <utility> #include "api/mediaconstraintsinterface.h" #include "api/peerconnectioninterface.h" #include "api/rtpreceiverinterface.h" #include "api/rtpsenderinterface.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "sdk/android/src/jni/classreferenceholder.h" #include "sdk/android/src/jni/jni_helpers.h" #include "sdk/android/src/jni/pc/java_native_conversion.h" #include "sdk/android/src/jni/pc/mediaconstraints_jni.h" #include "sdk/android/src/jni/pc/peerconnectionobserver_jni.h" #include "sdk/android/src/jni/pc/rtcstatscollectorcallbackwrapper.h" #include "sdk/android/src/jni/pc/sdpobserver_jni.h" #include "sdk/android/src/jni/pc/statsobserver_jni.h" namespace webrtc { namespace jni { static rtc::scoped_refptr<PeerConnectionInterface> ExtractNativePC( JNIEnv* jni, jobject j_pc) { jfieldID native_pc_id = GetFieldID(jni, GetObjectClass(jni, j_pc), "nativePeerConnection", "J"); jlong j_p = GetLongField(jni, j_pc, native_pc_id); return rtc::scoped_refptr<PeerConnectionInterface>( reinterpret_cast<PeerConnectionInterface*>(j_p)); } JNI_FUNCTION_DECLARATION(void, PeerConnection_freeObserver, JNIEnv*, jclass, jlong j_p) { PeerConnectionObserverJni* p = reinterpret_cast<PeerConnectionObserverJni*>(j_p); delete p; } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_getLocalDescription, JNIEnv* jni, jobject j_pc) { const SessionDescriptionInterface* sdp = ExtractNativePC(jni, j_pc)->local_description(); return sdp ? NativeToJavaSessionDescription(jni, sdp) : NULL; } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_getRemoteDescription, JNIEnv* jni, jobject j_pc) { const SessionDescriptionInterface* sdp = ExtractNativePC(jni, j_pc)->remote_description(); return sdp ? NativeToJavaSessionDescription(jni, sdp) : NULL; } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_createDataChannel, JNIEnv* jni, jobject j_pc, jstring j_label, jobject j_init) { DataChannelInit init = JavaToNativeDataChannelInit(jni, j_init); rtc::scoped_refptr<DataChannelInterface> channel( ExtractNativePC(jni, j_pc)->CreateDataChannel( JavaToStdString(jni, j_label), &init)); // Mustn't pass channel.get() directly through NewObject to avoid reading its // vararg parameter as 64-bit and reading memory that doesn't belong to the // 32-bit parameter. jlong nativeChannelPtr = jlongFromPointer(channel.get()); if (!nativeChannelPtr) { RTC_LOG(LS_ERROR) << "Failed to create DataChannel"; return nullptr; } jclass j_data_channel_class = FindClass(jni, "org/webrtc/DataChannel"); jmethodID j_data_channel_ctor = GetMethodID(jni, j_data_channel_class, "<init>", "(J)V"); jobject j_channel = jni->NewObject(j_data_channel_class, j_data_channel_ctor, nativeChannelPtr); CHECK_EXCEPTION(jni) << "error during NewObject"; // Channel is now owned by Java object, and will be freed from there. channel->AddRef(); return j_channel; } JNI_FUNCTION_DECLARATION(void, PeerConnection_createOffer, JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) { MediaConstraintsJni* constraints = new MediaConstraintsJni(jni, j_constraints); rtc::scoped_refptr<CreateSdpObserverJni> observer( new rtc::RefCountedObject<CreateSdpObserverJni>(jni, j_observer, constraints)); ExtractNativePC(jni, j_pc)->CreateOffer(observer, constraints); } JNI_FUNCTION_DECLARATION(void, PeerConnection_createAnswer, JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) { MediaConstraintsJni* constraints = new MediaConstraintsJni(jni, j_constraints); rtc::scoped_refptr<CreateSdpObserverJni> observer( new rtc::RefCountedObject<CreateSdpObserverJni>(jni, j_observer, constraints)); ExtractNativePC(jni, j_pc)->CreateAnswer(observer, constraints); } JNI_FUNCTION_DECLARATION(void, PeerConnection_setLocalDescription, JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_sdp) { rtc::scoped_refptr<SetSdpObserverJni> observer( new rtc::RefCountedObject<SetSdpObserverJni>(jni, j_observer, nullptr)); ExtractNativePC(jni, j_pc)->SetLocalDescription( observer, JavaToNativeSessionDescription(jni, j_sdp)); } JNI_FUNCTION_DECLARATION(void, PeerConnection_setRemoteDescription, JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_sdp) { rtc::scoped_refptr<SetSdpObserverJni> observer( new rtc::RefCountedObject<SetSdpObserverJni>(jni, j_observer, nullptr)); ExtractNativePC(jni, j_pc)->SetRemoteDescription( observer, JavaToNativeSessionDescription(jni, j_sdp)); } JNI_FUNCTION_DECLARATION(void, PeerConnection_setAudioPlayout, JNIEnv* jni, jobject j_pc, jboolean playout) { ExtractNativePC(jni, j_pc)->SetAudioPlayout(playout); } JNI_FUNCTION_DECLARATION(void, PeerConnection_setAudioRecording, JNIEnv* jni, jobject j_pc, jboolean recording) { ExtractNativePC(jni, j_pc)->SetAudioRecording(recording); } JNI_FUNCTION_DECLARATION(jboolean, PeerConnection_nativeSetConfiguration, JNIEnv* jni, jobject j_pc, jobject j_rtc_config, jlong native_observer) { // Need to merge constraints into RTCConfiguration again, which are stored // in the observer object. PeerConnectionObserverJni* observer = reinterpret_cast<PeerConnectionObserverJni*>(native_observer); PeerConnectionInterface::RTCConfiguration rtc_config( PeerConnectionInterface::RTCConfigurationType::kAggressive); JavaToNativeRTCConfiguration(jni, j_rtc_config, &rtc_config); CopyConstraintsIntoRtcConfiguration(observer->constraints(), &rtc_config); return ExtractNativePC(jni, j_pc)->SetConfiguration(rtc_config); } JNI_FUNCTION_DECLARATION(jboolean, PeerConnection_nativeAddIceCandidate, JNIEnv* jni, jobject j_pc, jstring j_sdp_mid, jint j_sdp_mline_index, jstring j_candidate_sdp) { std::string sdp_mid = JavaToStdString(jni, j_sdp_mid); std::string sdp = JavaToStdString(jni, j_candidate_sdp); std::unique_ptr<IceCandidateInterface> candidate( CreateIceCandidate(sdp_mid, j_sdp_mline_index, sdp, nullptr)); return ExtractNativePC(jni, j_pc)->AddIceCandidate(candidate.get()); } JNI_FUNCTION_DECLARATION(jboolean, PeerConnection_nativeRemoveIceCandidates, JNIEnv* jni, jobject j_pc, jobjectArray j_candidates) { std::vector<cricket::Candidate> candidates; size_t num_candidates = jni->GetArrayLength(j_candidates); for (size_t i = 0; i < num_candidates; ++i) { jobject j_candidate = jni->GetObjectArrayElement(j_candidates, i); candidates.push_back(JavaToNativeCandidate(jni, j_candidate)); } return ExtractNativePC(jni, j_pc)->RemoveIceCandidates(candidates); } JNI_FUNCTION_DECLARATION(jboolean, PeerConnection_nativeAddLocalStream, JNIEnv* jni, jobject j_pc, jlong native_stream) { return ExtractNativePC(jni, j_pc)->AddStream( reinterpret_cast<MediaStreamInterface*>(native_stream)); } JNI_FUNCTION_DECLARATION(void, PeerConnection_nativeRemoveLocalStream, JNIEnv* jni, jobject j_pc, jlong native_stream) { ExtractNativePC(jni, j_pc)->RemoveStream( reinterpret_cast<MediaStreamInterface*>(native_stream)); } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_nativeCreateSender, JNIEnv* jni, jobject j_pc, jstring j_kind, jstring j_stream_id) { jclass j_rtp_sender_class = FindClass(jni, "org/webrtc/RtpSender"); jmethodID j_rtp_sender_ctor = GetMethodID(jni, j_rtp_sender_class, "<init>", "(J)V"); std::string kind = JavaToStdString(jni, j_kind); std::string stream_id = JavaToStdString(jni, j_stream_id); rtc::scoped_refptr<RtpSenderInterface> sender = ExtractNativePC(jni, j_pc)->CreateSender(kind, stream_id); if (!sender.get()) { return nullptr; } jlong nativeSenderPtr = jlongFromPointer(sender.get()); jobject j_sender = jni->NewObject(j_rtp_sender_class, j_rtp_sender_ctor, nativeSenderPtr); CHECK_EXCEPTION(jni) << "error during NewObject"; // Sender is now owned by the Java object, and will be freed from // RtpSender.dispose(), called by PeerConnection.dispose() or getSenders(). sender->AddRef(); return j_sender; } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_nativeGetSenders, JNIEnv* jni, jobject j_pc) { jclass j_array_list_class = FindClass(jni, "java/util/ArrayList"); jmethodID j_array_list_ctor = GetMethodID(jni, j_array_list_class, "<init>", "()V"); jmethodID j_array_list_add = GetMethodID(jni, j_array_list_class, "add", "(Ljava/lang/Object;)Z"); jobject j_senders = jni->NewObject(j_array_list_class, j_array_list_ctor); CHECK_EXCEPTION(jni) << "error during NewObject"; jclass j_rtp_sender_class = FindClass(jni, "org/webrtc/RtpSender"); jmethodID j_rtp_sender_ctor = GetMethodID(jni, j_rtp_sender_class, "<init>", "(J)V"); auto senders = ExtractNativePC(jni, j_pc)->GetSenders(); for (const auto& sender : senders) { jlong nativeSenderPtr = jlongFromPointer(sender.get()); jobject j_sender = jni->NewObject(j_rtp_sender_class, j_rtp_sender_ctor, nativeSenderPtr); CHECK_EXCEPTION(jni) << "error during NewObject"; // Sender is now owned by the Java object, and will be freed from // RtpSender.dispose(), called by PeerConnection.dispose() or getSenders(). sender->AddRef(); jni->CallBooleanMethod(j_senders, j_array_list_add, j_sender); CHECK_EXCEPTION(jni) << "error during CallBooleanMethod"; } return j_senders; } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_nativeGetReceivers, JNIEnv* jni, jobject j_pc) { jclass j_array_list_class = FindClass(jni, "java/util/ArrayList"); jmethodID j_array_list_ctor = GetMethodID(jni, j_array_list_class, "<init>", "()V"); jmethodID j_array_list_add = GetMethodID(jni, j_array_list_class, "add", "(Ljava/lang/Object;)Z"); jobject j_receivers = jni->NewObject(j_array_list_class, j_array_list_ctor); CHECK_EXCEPTION(jni) << "error during NewObject"; jclass j_rtp_receiver_class = FindClass(jni, "org/webrtc/RtpReceiver"); jmethodID j_rtp_receiver_ctor = GetMethodID(jni, j_rtp_receiver_class, "<init>", "(J)V"); auto receivers = ExtractNativePC(jni, j_pc)->GetReceivers(); for (const auto& receiver : receivers) { jlong nativeReceiverPtr = jlongFromPointer(receiver.get()); jobject j_receiver = jni->NewObject(j_rtp_receiver_class, j_rtp_receiver_ctor, nativeReceiverPtr); CHECK_EXCEPTION(jni) << "error during NewObject"; // Receiver is now owned by Java object, and will be freed from there. receiver->AddRef(); jni->CallBooleanMethod(j_receivers, j_array_list_add, j_receiver); CHECK_EXCEPTION(jni) << "error during CallBooleanMethod"; } return j_receivers; } JNI_FUNCTION_DECLARATION(bool, PeerConnection_nativeOldGetStats, JNIEnv* jni, jobject j_pc, jobject j_observer, jlong native_track) { rtc::scoped_refptr<StatsObserverJni> observer( new rtc::RefCountedObject<StatsObserverJni>(jni, j_observer)); return ExtractNativePC(jni, j_pc)->GetStats( observer, reinterpret_cast<MediaStreamTrackInterface*>(native_track), PeerConnectionInterface::kStatsOutputLevelStandard); } JNI_FUNCTION_DECLARATION(void, PeerConnection_nativeNewGetStats, JNIEnv* jni, jobject j_pc, jobject j_callback) { rtc::scoped_refptr<RTCStatsCollectorCallbackWrapper> callback( new rtc::RefCountedObject<RTCStatsCollectorCallbackWrapper>(jni, j_callback)); ExtractNativePC(jni, j_pc)->GetStats(callback); } JNI_FUNCTION_DECLARATION(jboolean, PeerConnection_setBitrate, JNIEnv* jni, jobject j_pc, jobject j_min, jobject j_current, jobject j_max) { PeerConnectionInterface::BitrateParameters params; jclass j_integer_class = jni->FindClass("java/lang/Integer"); jmethodID int_value_id = GetMethodID(jni, j_integer_class, "intValue", "()I"); if (!IsNull(jni, j_min)) { int min_value = jni->CallIntMethod(j_min, int_value_id); params.min_bitrate_bps = rtc::Optional<int>(min_value); } if (!IsNull(jni, j_current)) { int current_value = jni->CallIntMethod(j_current, int_value_id); params.current_bitrate_bps = rtc::Optional<int>(current_value); } if (!IsNull(jni, j_max)) { int max_value = jni->CallIntMethod(j_max, int_value_id); params.max_bitrate_bps = rtc::Optional<int>(max_value); } return ExtractNativePC(jni, j_pc)->SetBitrate(params).ok(); } JNI_FUNCTION_DECLARATION(bool, PeerConnection_nativeStartRtcEventLog, JNIEnv* jni, jobject j_pc, int file_descriptor, int max_size_bytes) { return ExtractNativePC(jni, j_pc)->StartRtcEventLog(file_descriptor, max_size_bytes); } JNI_FUNCTION_DECLARATION(void, PeerConnection_nativeStopRtcEventLog, JNIEnv* jni, jobject j_pc) { ExtractNativePC(jni, j_pc)->StopRtcEventLog(); } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_signalingState, JNIEnv* jni, jobject j_pc) { PeerConnectionInterface::SignalingState state = ExtractNativePC(jni, j_pc)->signaling_state(); return JavaEnumFromIndexAndClassName(jni, "PeerConnection$SignalingState", state); } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_iceConnectionState, JNIEnv* jni, jobject j_pc) { PeerConnectionInterface::IceConnectionState state = ExtractNativePC(jni, j_pc)->ice_connection_state(); return JavaEnumFromIndexAndClassName(jni, "PeerConnection$IceConnectionState", state); } JNI_FUNCTION_DECLARATION(jobject, PeerConnection_iceGatheringState, JNIEnv* jni, jobject j_pc) { PeerConnectionInterface::IceGatheringState state = ExtractNativePC(jni, j_pc)->ice_gathering_state(); return JavaEnumFromIndexAndClassName(jni, "PeerConnection$IceGatheringState", state); } JNI_FUNCTION_DECLARATION(void, PeerConnection_close, JNIEnv* jni, jobject j_pc) { ExtractNativePC(jni, j_pc)->Close(); return; } } // namespace jni } // namespace webrtc
41.766968
80
0.637994
ebasdee
9c09fccb22c0fe7c44315534f463e667fef7be6f
4,533
hpp
C++
src/ext/pin-2.13-62732-gcc.4.4.7-linux/extras/components/include/atomic/exponential-backoff.hpp
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
645
2016-02-10T19:14:21.000Z
2022-03-20T15:19:08.000Z
src/ext/pin-2.13-62732-gcc.4.4.7-linux/extras/components/include/atomic/exponential-backoff.hpp
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
191
2016-02-10T00:45:50.000Z
2021-02-21T19:18:32.000Z
src/ext/pin-2.13-62732-gcc.4.4.7-linux/extras/components/include/atomic/exponential-backoff.hpp
AlexShypula/stoke
d68dc566d8db5ebd304cbda09710eb7f7d6457e3
[ "ECL-2.0", "Apache-2.0" ]
67
2016-02-09T15:15:28.000Z
2022-03-02T16:33:31.000Z
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL 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. END_LEGAL */ // <ORIGINAL-AUTHOR>: Greg Lueck // <COMPONENT>: atomic // <FILE-TYPE>: component public header #ifndef ATOMIC_EXPONENTIAL_BACKOFF_HPP #define ATOMIC_EXPONENTIAL_BACKOFF_HPP #include "fund.hpp" #include "atomic/nullstats.hpp" #include "atomic/private/backoff-impl.hpp" namespace ATOMIC { /*! @brief Helper object for exponential delays. * * A helper object that implements an exponential backoff algorithm. This is most often * used inside a compare-swap loop to prevent thrashing when there is high contention. * * @param STATS Type of an object that collects statistics. See NULLSTATS for a model. * * @par Example: * \code * #include "atomic/exponential-backoff.hpp" * #include "atomic/ops.hpp" * * void Foo() * { * ATOMIC::EXPONENTIAL_BACKOFF<> backoff; * do { * backoff.Delay(); * oldVal = .... * newVal = .... * } while (!ATOMIC::OPS::CompareAndDidSwap(&val, oldVal, newVal)); * } * \endcode */ template<typename STATS=NULLSTATS> class /*<UTILITY>*/ EXPONENTIAL_BACKOFF { public: /*! * @param[in] freeIterations Number of times through loop before Delay() does anything. * @param[in] stats Object to keep track of statistics, or NULL */ EXPONENTIAL_BACKOFF(FUND::UINT32 freeIterations = 1, STATS *stats = 0) : _freeIterations(freeIterations), _iteration(0), _stats(stats) {} ~EXPONENTIAL_BACKOFF() { if (_stats && _iteration > _freeIterations) _stats->Backoff(_iteration - _freeIterations); } /*! * Reset the object to the first "iteration". */ void Reset() { if (_stats && _iteration > _freeIterations) _stats->Backoff(_iteration - _freeIterations); _iteration = 0; } /*! * Delay for a short period of time and advance to the next "iteration". The delay * time typically grows longer for each successive iteration. */ void Delay() { if (_iteration++ < _freeIterations) return; FUND::UINT32 fixed = 1 << (_iteration - 1 - _freeIterations); FUND::UINT32 mask = fixed - 1; FUND::UINT32 random = (reinterpret_cast<FUND::PTRINT>(&random) >> 4) & mask; FUND::UINT32 delay = fixed + random; ATOMIC_SpinDelay(delay); } /*! * @return The number of times Delay() has been called since the last Reset(). */ FUND::UINT32 GetIterationCount() { return _iteration; } private: const FUND::UINT32 _freeIterations; // number "free" iterations before we start to delay FUND::UINT32 _iteration; // current iteration STATS *_stats; // points to object which collects statistics, or NULL }; } // namespace #endif // file guard
34.869231
100
0.665784
AlexShypula
9c0a247b3ed6e5009c316a1af4a479395c5c508f
4,262
cpp
C++
plugins/community/repos/QuantalAudio/src/MasterMixer.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/QuantalAudio/src/MasterMixer.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/QuantalAudio/src/MasterMixer.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "QuantalAudio.hpp" namespace rack_plugin_QuantalAudio { struct MasterMixer : Module { enum ParamIds { MIX_LVL_PARAM, MONO_PARAM, ENUMS(LVL_PARAM, 2), NUM_PARAMS }; enum InputIds { MIX_CV_INPUT, ENUMS(CH_INPUT, 2), NUM_INPUTS }; enum OutputIds { MIX_OUTPUT, MIX_OUTPUT_2, ENUMS(CH_OUTPUT, 2), NUM_OUTPUTS }; MasterMixer() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {} void step() override { float mix = 0.f; for (int i = 0; i < 2; i++) { float ch = inputs[CH_INPUT + i].value; ch *= powf(params[LVL_PARAM + i].value, 2.f); outputs[CH_OUTPUT + i].value = ch; mix += ch; } mix *= params[MIX_LVL_PARAM].value; bool is_mono = (params[MONO_PARAM].value > 0.0f); float mix_cv = 1.f; if (inputs[MIX_CV_INPUT].active) mix_cv = clamp(inputs[MIX_CV_INPUT].value / 10.f, 0.f, 1.f); if (!is_mono && (inputs[CH_INPUT + 0].active && inputs[CH_INPUT + 1].active)) { // If the ch 2 jack is active use stereo mode float attenuate = params[MIX_LVL_PARAM].value * mix_cv; outputs[MIX_OUTPUT].value = outputs[CH_OUTPUT + 0].value * attenuate; outputs[MIX_OUTPUT_2].value = outputs[CH_OUTPUT + 1].value * attenuate; } else { // Otherwise use mono->stereo mode mix *= mix_cv; outputs[MIX_OUTPUT].value = mix; outputs[MIX_OUTPUT_2].value = mix; } } }; struct MasterMixerWidget : ModuleWidget { MasterMixerWidget(MasterMixer *module) : ModuleWidget(module) { setPanel(SVG::load(assetPlugin(plugin, "res/MasterMixer.svg"))); // Screws addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); // Level & CV addParam(ParamWidget::create<RoundLargeBlackKnob>(Vec(RACK_GRID_WIDTH * 2.5 - (38.0/2), 52.0), module, MasterMixer::MIX_LVL_PARAM, 0.0, 2.0, 1.0)); addInput(Port::create<PJ301MPort>(Vec(RACK_GRID_WIDTH * 2.5 - (25.0/2), 96.0), Port::INPUT, module, MasterMixer::MIX_CV_INPUT)); // Mono/stereo switch addParam(ParamWidget::create<CKSS>(Vec(RACK_GRID_WIDTH * 2.5 - 7.0, 162.0), module, MasterMixer::MONO_PARAM, 0.0f, 1.0f, 1.0f)); // LEDs addParam(ParamWidget::create<LEDSliderGreen>(Vec(RACK_GRID_WIDTH * 2.5 - (21.0 + 7.0), 130.4), module, MasterMixer::LVL_PARAM + 0, 0.0, 1.0, 1.0)); addParam(ParamWidget::create<LEDSliderGreen>(Vec(RACK_GRID_WIDTH * 2.5 + 7.0, 130.4), module, MasterMixer::LVL_PARAM + 1, 0.0, 1.0, 1.0)); // Channel inputs addInput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) - (25.0 + 5.0), 232.0), Port::INPUT, module, MasterMixer::CH_INPUT + 0)); addInput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) + 5.0, 232.0), Port::INPUT, module, MasterMixer::CH_INPUT + 1)); // Channel outputs addOutput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) - (25.0 + 5.0), 276.0), Port::OUTPUT, module, MasterMixer::CH_OUTPUT + 0)); addOutput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) + 5.0, 276.0), Port::OUTPUT, module, MasterMixer::CH_OUTPUT + 1)); // Mix outputs addOutput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) - (25.0 + 5.0), 320.0), Port::OUTPUT, module, MasterMixer::MIX_OUTPUT)); addOutput(Port::create<PJ301MPort>(Vec((RACK_GRID_WIDTH * 2.5) + 5.0, 320.0), Port::OUTPUT, module, MasterMixer::MIX_OUTPUT_2)); } }; } // namespace rack_plugin_QuantalAudio using namespace rack_plugin_QuantalAudio; RACK_PLUGIN_MODEL_INIT(QuantalAudio, MasterMixer) { Model *modelMasterMixer = Model::create<MasterMixer, MasterMixerWidget>("QuantalAudio", "Mixer2", "Mixer 2 | Mono->Stereo | 5HP", MIXER_TAG, AMPLIFIER_TAG); return modelMasterMixer; }
43.050505
159
0.627405
guillaume-plantevin
9c0ada9cd56768f5143633c87da83d0f3f61dd4b
1,382
hpp
C++
include/boost/simd/arch/x86/sse1/simd/function/load.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/x86/sse1/simd/function/load.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/x86/sse1/simd/function/load.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2015 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_LOAD_HPP_INCLUDED #define BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_LOAD_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/dispatch/adapted/common/pointer.hpp> namespace boost { namespace simd { namespace ext { namespace bd = ::boost::dispatch; namespace bs = ::boost::simd; //------------------------------------------------------------------------------------------------ // load from a pointer of single BOOST_DISPATCH_OVERLOAD ( load_ , (typename Target, typename Pointer) , bs::sse_ , bd::pointer_<bd::scalar_<bd::single_<Pointer>>,1u> , bd::target_<bs::pack_<bd::single_<Target>,bs::sse_>> ) { using target_t = typename Target::type; BOOST_FORCEINLINE target_t operator()(Pointer p, Target const&) const { return _mm_loadu_ps(p); } }; } } } #endif
33.707317
100
0.502171
yaeldarmon
9c0d7b921afc4f93e539e6d6e063de2cc33870fe
1,876
cpp
C++
Source/ExampleGame/DynamicTextureStaticMeshActor.cpp
uetopia/ExampleGame
b05364987163255ad54334420852ccbb7bff87dd
[ "Apache-2.0" ]
34
2019-10-19T17:53:57.000Z
2022-03-31T17:50:34.000Z
Source/ExampleGame/DynamicTextureStaticMeshActor.cpp
uetopia/ExampleGame
b05364987163255ad54334420852ccbb7bff87dd
[ "Apache-2.0" ]
null
null
null
Source/ExampleGame/DynamicTextureStaticMeshActor.cpp
uetopia/ExampleGame
b05364987163255ad54334420852ccbb7bff87dd
[ "Apache-2.0" ]
15
2019-11-25T03:58:19.000Z
2021-11-22T20:39:10.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "DynamicTextureStaticMeshActor.h" #include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h" #include "Runtime/Engine/Classes/Materials/MaterialInstanceDynamic.h" // Sets default values ADynamicTextureStaticMeshActor::ADynamicTextureStaticMeshActor(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { RootComponent = GetStaticMeshComponent(); if (!IsRunningDedicatedServer()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [ADynamicTextureStaticMeshActor] Construct - Not a Dedicated server.")); // For some reason the dedicated server can't load the material, but it does not need it. // The Material needs a Texture Sample 2d parameter named "BaseColor" static ConstructorHelpers::FObjectFinder<UMaterial> MatFinder(TEXT("Material'/Game/Display/m_16x9_display.m_16x9_display'")); // Material'/Game/Fantasy_Armory_GreatHall/Materials/Props/Interior/M_Banners.M_Banners' if (MatFinder.Succeeded()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [ADynamicTextureStaticMeshActor] [Construct] Found Material ")); Material = MatFinder.Object; //MaterialInstance = UMaterialInstanceDynamic::Create(Material, NULL); //GetStaticMeshComponent()->SetMaterial(0, MaterialInstance); //MaterialInstance = GetStaticMeshComponent()->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Material); } } //bReplicates = true; //bReplicateMovement = true; } void ADynamicTextureStaticMeshActor::BeginPlay() { Super::BeginPlay(); // Only run this on client if (!IsRunningDedicatedServer()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [ADynamicTextureStaticMeshActor] BeginPlay - Not a Dedicated server.")); MaterialInstance = UMaterialInstanceDynamic::Create(Material, NULL); GetStaticMeshComponent()->SetMaterial(0, MaterialInstance); } }
36.784314
127
0.779851
uetopia
9c0f5c5de6bfe5889e0e7a9c7aaab616d590b5ce
661
cxx
C++
src/test/dblclient/test_version.cxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
null
null
null
src/test/dblclient/test_version.cxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
null
null
null
src/test/dblclient/test_version.cxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
1
2018-10-09T06:30:03.000Z
2018-10-09T06:30:03.000Z
#include "utils/test.hxx" #include <string> #include <memory> #include <iostream> int main(int argc, char** argv) { using namespace test; using dblclient::Session; UnitTest unit_test; std::unique_ptr<Server> server(new Server()); std::string address = server->get_address(); int port = server->get_port(); unit_test.test_case( "Test version", [&address, &port](TestCase& test) { Session session; session.open(address, port); std::string version = session.get_server_version(); test.assert_true(version.length() > 0, "Got version"); } ); ProcessTest proc_test(std::move(server), unit_test); return proc_test.run(argc, argv); }
21.322581
57
0.698941
mcptr
9c0f773ed7d78d525525a98df6f54cbc42d1e50e
2,120
cc
C++
chrome/browser/content_settings/chrome_content_settings_utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/content_settings/chrome_content_settings_utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/content_settings/chrome_content_settings_utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/content_settings/chrome_content_settings_utils.h" #include "base/metrics/histogram_macros.h" #if !defined(OS_ANDROID) #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #endif namespace content_settings { void RecordPluginsAction(PluginsAction action) { UMA_HISTOGRAM_ENUMERATION("ContentSettings.Plugins", action, PLUGINS_ACTION_COUNT); } void RecordPopupsAction(PopupsAction action) { UMA_HISTOGRAM_ENUMERATION("ContentSettings.Popups", action, POPUPS_ACTION_COUNT); } void UpdateLocationBarUiForWebContents(content::WebContents* web_contents) { #if !defined(OS_ANDROID) Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return; if (browser->tab_strip_model()->GetActiveWebContents() != web_contents) return; LocationBar* location_bar = browser->window()->GetLocationBar(); if (location_bar) location_bar->UpdateContentSettingsIcons(); #endif } #if !defined(OS_ANDROID) std::u16string GetPermissionDetailString(Profile* profile, ContentSettingsType content_type, const GURL& url) { if (!url.is_valid()) return {}; switch (content_type) { case ContentSettingsType::FILE_HANDLING: return web_app::GetFileTypeAssociationsHandledByWebAppsForDisplay(profile, url); default: return {}; } } #endif } // namespace content_settings
32.121212
80
0.701887
zealoussnow
9c10af8e01ebf7237c8d5fac4e991053993dc9ec
8,144
cpp
C++
rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp
miraiworks/rviz
c53e307332a62805bf4b4ee275c008011b51a970
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp
miraiworks/rviz
c53e307332a62805bf4b4ee275c008011b51a970
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/image/image_display.cpp
miraiworks/rviz
c53e307332a62805bf4b4ee275c008011b51a970
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * Copyright (c) 2012, Willow Garage, Inc. * Copyright (c) 2017, Bosch Software Innovations GmbH. * 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 Willow Garage, Inc. 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. */ #include <memory> #include <string> #include <utility> #include <OgreCamera.h> #include <OgreManualObject.h> #include <OgreMaterialManager.h> #include <OgreRectangle2D.h> #include <OgreRenderSystem.h> #include <OgreRenderWindow.h> #include <OgreRoot.h> #include <OgreSceneNode.h> #include <OgreTechnique.h> #include <OgreTextureManager.h> #include <OgreViewport.h> #include "sensor_msgs/image_encodings.hpp" #include "rviz_common/display_context.hpp" #include "rviz_common/frame_manager_iface.hpp" #include "rviz_common/render_panel.hpp" #include "rviz_common/validate_floats.hpp" #include "rviz_common/uniform_string_stream.hpp" #include "rviz_rendering/material_manager.hpp" #include "rviz_rendering/render_window.hpp" #include "rviz_default_plugins/displays/image/ros_image_texture.hpp" #include "rviz_default_plugins/displays/image/image_display.hpp" #include "rviz_default_plugins/displays/image/ros_image_texture_iface.hpp" namespace rviz_default_plugins { namespace displays { ImageDisplay::ImageDisplay() : ImageDisplay(std::make_unique<ROSImageTexture>()) {} ImageDisplay::ImageDisplay(std::unique_ptr<ROSImageTextureIface> texture) : queue_size_property_(std::make_unique<rviz_common::QueueSizeProperty>(this, 10)), texture_(std::move(texture)) { normalize_property_ = new rviz_common::properties::BoolProperty( "Normalize Range", true, "If set to true, will try to estimate the range of possible values from the received images.", this, SLOT(updateNormalizeOptions())); min_property_ = new rviz_common::properties::FloatProperty( "Min Value", 0.0, "Value which will be displayed as black.", this, SLOT(updateNormalizeOptions())); max_property_ = new rviz_common::properties::FloatProperty( "Max Value", 1.0, "Value which will be displayed as white.", this, SLOT(updateNormalizeOptions())); median_buffer_size_property_ = new rviz_common::properties::IntProperty( "Median window", 5, "Window size for median filter used for computing min/max.", this, SLOT(updateNormalizeOptions())); got_float_image_ = false; } void ImageDisplay::onInitialize() { MFDClass::onInitialize(); updateNormalizeOptions(); setupScreenRectangle(); setupRenderPanel(); render_panel_->getRenderWindow()->setupSceneAfterInit( [this](Ogre::SceneNode * scene_node) { scene_node->attachObject(screen_rect_.get()); }); } ImageDisplay::~ImageDisplay() = default; void ImageDisplay::onEnable() { MFDClass::subscribe(); } void ImageDisplay::onDisable() { MFDClass::unsubscribe(); clear(); } void ImageDisplay::updateNormalizeOptions() { if (got_float_image_) { bool normalize = normalize_property_->getBool(); normalize_property_->setHidden(false); min_property_->setHidden(normalize); max_property_->setHidden(normalize); median_buffer_size_property_->setHidden(!normalize); texture_->setNormalizeFloatImage( normalize, min_property_->getFloat(), max_property_->getFloat()); texture_->setMedianFrames(median_buffer_size_property_->getInt()); } else { normalize_property_->setHidden(true); min_property_->setHidden(true); max_property_->setHidden(true); median_buffer_size_property_->setHidden(true); } } void ImageDisplay::clear() { texture_->clear(); } void ImageDisplay::update(float wall_dt, float ros_dt) { (void) wall_dt; (void) ros_dt; try { texture_->update(); // make sure the aspect ratio of the image is preserved float win_width = render_panel_->width(); float win_height = render_panel_->height(); float img_width = texture_->getWidth(); float img_height = texture_->getHeight(); if (img_width != 0 && img_height != 0 && win_width != 0 && win_height != 0) { float img_aspect = img_width / img_height; float win_aspect = win_width / win_height; if (img_aspect > win_aspect) { screen_rect_->setCorners( -1.0f, 1.0f * win_aspect / img_aspect, 1.0f, -1.0f * win_aspect / img_aspect, false); } else { screen_rect_->setCorners( -1.0f * img_aspect / win_aspect, 1.0f, 1.0f * img_aspect / win_aspect, -1.0f, false); } } } catch (UnsupportedImageEncoding & e) { setStatus(rviz_common::properties::StatusProperty::Error, "Image", e.what()); } } void ImageDisplay::reset() { MFDClass::reset(); clear(); } /* This is called by incomingMessage(). */ void ImageDisplay::processMessage(sensor_msgs::msg::Image::ConstSharedPtr msg) { bool got_float_image = msg->encoding == sensor_msgs::image_encodings::TYPE_32FC1 || msg->encoding == sensor_msgs::image_encodings::TYPE_16UC1 || msg->encoding == sensor_msgs::image_encodings::TYPE_16SC1 || msg->encoding == sensor_msgs::image_encodings::MONO16; if (got_float_image != got_float_image_) { got_float_image_ = got_float_image; updateNormalizeOptions(); } texture_->addMessage(msg); } void ImageDisplay::setupScreenRectangle() { static int count = 0; rviz_common::UniformStringStream ss; ss << "ImageDisplayObject" << count++; screen_rect_ = std::make_unique<Ogre::Rectangle2D>(true); screen_rect_->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1); screen_rect_->setCorners(-1.0f, 1.0f, 1.0f, -1.0f); ss << "Material"; material_ = rviz_rendering::MaterialManager::createMaterialWithNoLighting(ss.str()); material_->setSceneBlending(Ogre::SBT_REPLACE); material_->setDepthWriteEnabled(false); material_->setDepthCheckEnabled(false); Ogre::TextureUnitState * tu = material_->getTechnique(0)->getPass(0)->createTextureUnitState(); tu->setTextureName(texture_->getName()); tu->setTextureFiltering(Ogre::TFO_NONE); material_->setCullingMode(Ogre::CULL_NONE); Ogre::AxisAlignedBox aabInf; aabInf.setInfinite(); screen_rect_->setBoundingBox(aabInf); screen_rect_->setMaterial(material_); } void ImageDisplay::setupRenderPanel() { render_panel_ = std::make_unique<rviz_common::RenderPanel>(); render_panel_->resize(640, 480); render_panel_->initialize(context_); setAssociatedWidget(render_panel_.get()); static int count = 0; render_panel_->getRenderWindow()->setObjectName( "ImageDisplayRenderWindow" + QString::number(count++)); } } // namespace displays } // namespace rviz_default_plugins #include <pluginlib/class_list_macros.hpp> // NOLINT PLUGINLIB_EXPORT_CLASS(rviz_default_plugins::displays::ImageDisplay, rviz_common::Display)
31.937255
98
0.73502
miraiworks
9c114f20f5d5619740ed46712919f88e5f653d3e
4,235
cpp
C++
lte/gateway/c/oai/tasks/sctp/sctpd_uplink_server.cpp
remo5000/magma
1d1dd9a23800a8e07b1ce016776d93e12430ec15
[ "BSD-3-Clause" ]
3
2019-08-16T17:03:09.000Z
2019-08-23T21:57:48.000Z
lte/gateway/c/oai/tasks/sctp/sctpd_uplink_server.cpp
remo5000/magma
1d1dd9a23800a8e07b1ce016776d93e12430ec15
[ "BSD-3-Clause" ]
14
2019-11-15T12:01:18.000Z
2019-12-12T14:37:42.000Z
lte/gateway/c/oai/tasks/sctp/sctpd_uplink_server.cpp
119Vik/magma-1
107a7b374466a837fc0a49b283ba9d6ff1d702e3
[ "BSD-3-Clause" ]
3
2019-11-15T15:56:25.000Z
2019-11-21T10:34:59.000Z
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ extern "C" { #include "sctpd_uplink_server.h" // #include "assertions.h" #include "bstrlib.h" #include "log.h" #include "sctp_defs.h" #include "sctp_itti_messaging.h" } #include <memory> #include <grpcpp/grpcpp.h> #include <lte/protos/sctpd.grpc.pb.h> namespace magma { namespace mme { using grpc::ServerContext; using grpc::Status; using magma::sctpd::CloseAssocReq; using magma::sctpd::CloseAssocRes; using magma::sctpd::NewAssocReq; using magma::sctpd::NewAssocRes; using magma::sctpd::SctpdUplink; using magma::sctpd::SendUlReq; using magma::sctpd::SendUlRes; class SctpdUplinkImpl final : public SctpdUplink::Service { public: SctpdUplinkImpl(); Status SendUl(ServerContext *context, const SendUlReq *req, SendUlRes *res) override; Status NewAssoc( ServerContext *context, const NewAssocReq *req, NewAssocRes *res) override; Status CloseAssoc( ServerContext *context, const CloseAssocReq *req, CloseAssocRes *res) override; }; SctpdUplinkImpl::SctpdUplinkImpl() {} Status SctpdUplinkImpl::SendUl( ServerContext *context, const SendUlReq *req, SendUlRes *res) { bstring payload; uint32_t assoc_id; uint16_t stream; payload = blk2bstr(req->payload().c_str(), req->payload().size()); if (payload == NULL) { OAILOG_ERROR(LOG_SCTP, "failed to allocate bstr for SendUl\n"); return Status::OK; } assoc_id = req->assoc_id(); stream = req->stream(); if (sctp_itti_send_new_message_ind(&payload, assoc_id, stream) < 0) { OAILOG_ERROR(LOG_SCTP, "failed to send new_message_ind for SendUl\n"); return Status::OK; } return Status::OK; } #include <assert.h> Status SctpdUplinkImpl::NewAssoc( ServerContext *context, const NewAssocReq *req, NewAssocRes *res) { uint32_t assoc_id; uint16_t instreams; uint16_t outstreams; assoc_id = req->assoc_id(); instreams = req->instreams(); outstreams = req->outstreams(); if (sctp_itti_send_new_association(assoc_id, instreams, outstreams) < 0) { OAILOG_ERROR(LOG_SCTP, "failed to send new_association for NewAssoc\n"); return Status::OK; } return Status::OK; } Status SctpdUplinkImpl::CloseAssoc( ServerContext *context, const CloseAssocReq *req, CloseAssocRes *res) { uint32_t assoc_id; bool reset; assoc_id = req->assoc_id(); reset = req->is_reset(); if (sctp_itti_send_com_down_ind(assoc_id, reset) < 0) { OAILOG_ERROR(LOG_SCTP, "failed to send com_down_ind for CloseAssoc\n"); return Status::OK; } return Status::OK; } } // namespace mme } // namespace magma using grpc::Server; using grpc::ServerBuilder; using magma::mme::SctpdUplinkImpl; std::shared_ptr<SctpdUplinkImpl> _service = nullptr; std::unique_ptr<Server> _server = nullptr; int start_sctpd_uplink_server(void) { _service = std::make_shared<SctpdUplinkImpl>(); ServerBuilder builder; builder.AddListeningPort(UPSTREAM_SOCK, grpc::InsecureServerCredentials()); builder.RegisterService(_service.get()); _server = builder.BuildAndStart(); return 0; } void stop_sctpd_uplink_server(void) { if (_server != nullptr) { _server->Shutdown(); _server->Wait(); _server = nullptr; } _service = nullptr; }
24.622093
81
0.713813
remo5000
9c15e855d38d2e17cd8eec66d4d57842d0d686c4
1,758
hpp
C++
rosbag2_transport/src/rosbag2_transport/formatter.hpp
albtam/rosbag2
e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8
[ "Apache-2.0" ]
1
2020-05-22T13:40:13.000Z
2020-05-22T13:40:13.000Z
rosbag2_transport/src/rosbag2_transport/formatter.hpp
albtam/rosbag2
e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8
[ "Apache-2.0" ]
7
2019-10-22T17:24:35.000Z
2020-01-03T16:28:36.000Z
rosbag2_transport/src/rosbag2_transport/formatter.hpp
albtam/rosbag2
e4ce24cdfa7e24c6d2c025ecc38ab1157a0eecc8
[ "Apache-2.0" ]
8
2020-04-08T11:11:25.000Z
2020-11-16T15:55:24.000Z
// Copyright 2018, Bosch Software Innovations GmbH. // // 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 ROSBAG2_TRANSPORT__FORMATTER_HPP_ #define ROSBAG2_TRANSPORT__FORMATTER_HPP_ #include <chrono> #include <sstream> #include <string> #include <unordered_map> #include <vector> #include "rosbag2_storage/bag_metadata.hpp" namespace rosbag2_transport { class Formatter { public: static void format_bag_meta_data(const rosbag2_storage::BagMetadata & metadata); static std::unordered_map<std::string, std::string> format_duration( std::chrono::high_resolution_clock::duration duration); static std::string format_time_point(std::chrono::high_resolution_clock::duration time_point); static std::string format_file_size(uint64_t file_size); static void format_file_paths( const std::vector<std::string> & paths, std::stringstream & info_stream, int indentation_spaces); static void format_topics_with_type( const std::vector<rosbag2_storage::TopicInformation> & topics, std::stringstream & info_stream, int indentation_spaces); private: static void indent(std::stringstream & info_stream, int number_of_spaces); }; } // namespace rosbag2_transport #endif // ROSBAG2_TRANSPORT__FORMATTER_HPP_
30.310345
96
0.770193
albtam
9c1611b336777d85b788ac690f91083e28d56834
776
hpp
C++
src/stan/math/prim/mat/meta/is_constant.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/math/prim/mat/meta/is_constant.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/math/prim/mat/meta/is_constant.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_MAT_META_IS_CONSTANT_HPP #define STAN_MATH_PRIM_MAT_META_IS_CONSTANT_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/meta/is_eigen.hpp> #include <stan/math/prim/scal/meta/bool_constant.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <type_traits> namespace stan { /** * Defines a public enum named value and sets it to true * if the type of the elements in the provided Eigen Matrix * is constant, false otherwise. This is used in * the is_constant_all metaprogram. * * @tparam T type of the Eigen Matrix */ template <typename T> struct is_constant<T, std::enable_if_t<is_eigen<T>::value>> : bool_constant<is_constant<typename std::decay_t<T>::Scalar>::value> {}; } // namespace stan #endif
31.04
77
0.761598
alashworth
9c169e50478d5970fd0c45fe062f9ce268c7653c
73,895
cpp
C++
hive/app/dna-cgi/ion-cgi.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
hive/app/dna-cgi/ion-cgi.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
hive/app/dna-cgi/ion-cgi.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
/* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * 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 <violin/violin.hpp> #include <slib/utils/json/parser.hpp> enum enumIonCommands { eIonNcbiTax, eIonTaxInfo, eIonTaxDownInfo, eIonTaxParent, eIonTaxPathogenInfo, eIonAnnotInfo, eIonAnnotIdMap, eIonTaxidCollapse, eIonTaxidByName, eIonCodonDB, eExtendCodonTable, eIonWander }; //const char * listIonCommands= // "ionncbiTax" _ "ionTaxInfo" _ "ionTaxDownInfo" _ // "ionAnnotInfo" _ "ionAnnotIdMap" _ // _; idx extractIonQueryfromTable(sIonWander &iWander, sTxtTbl &tbl, const char *ionQuery, const char *defaultValue = 0, bool parseiWander = true) { // parse ionQuery to understand the dictionary idx cntRows = tbl.rows(); idx cntCols = tbl.cols(); sVec<idx> icols; if (parseiWander){ iWander.traverseCompile(ionQuery); } icols.add(iWander.parametricArguments.dim()); idx plen; for(idx ipa = 0; ipa < iWander.parametricArguments.dim(); ++ipa) { const char *param = ((const char *) iWander.parametricArguments.id(ipa, &plen)); ++param; --plen; idx colArg = sNotIdx; if( isdigit(param[0]) ) { // It is a column //char *end = (char *)param+plen; colArg = atoidx(param); } else { idx clen; for(idx icol = 0; icol < cntCols; ++icol) { const char * cell = tbl.cell(-1, icol, &clen); if( (plen == clen) && memcmp(param, cell, plen) == 0 ) { colArg = icol; break; } } } icols[ipa] = colArg; } idx oldLength = sNotIdx; sStr cbuf; for(idx i = 0; i < cntRows; i++) { cbuf.cut(0); bool need_unquote = false; for(idx j = 0; j < icols.dim(); ++j) { // get the pointers of the dictionary idx plen; const char * pid = (const char *) iWander.parametricArguments.id(j, &plen); idx *toModify = (idx*) iWander.getSearchDictionaryPointer(pid, plen); // get the value from the table //cbuf.cut(0); idx cell_len = 0; const char * cell = tbl.cell(i, icols[j], &cell_len); if( cell && cell_len ) { if( cell[0] == '"' ) { // temporary: cbuf can be realloced, so store offset and -123 guard value, // fix up in next pass toModify[0] = cbuf.length(); toModify[1] = -123; // fix up in next loop need_unquote = true; tbl.printCell(cbuf, i, icols[j]); cbuf.add0(); } else { toModify[0] = sConvPtr2Int(cell); toModify[1] = cell_len; } } else { toModify[0] = 0; toModify[1] = 0; } } if( need_unquote ) { for(idx j = 0; j < icols.dim(); ++j) { const char * pid = (const char *) iWander.parametricArguments.id(j, &plen); idx *toModify = (idx*) iWander.getSearchDictionaryPointer(pid, plen); if( toModify[1] == -123 ) { const char * unquoted_cell = cbuf.ptr(toModify[0]); toModify[0] = sConvPtr2Int(unquoted_cell); toModify[1] = sLen(unquoted_cell); } } } iWander.traverse(); // Get the result in if( defaultValue && ((oldLength == iWander.traverseBuf.length()) || (iWander.traverseBuf.length() == 0)) ) { // Check the filter: iWander.traverseBuf.addString(defaultValue); if( *iWander.traverseRecordSeparator == 0 ) { iWander.traverseBuf.add0(); } else { iWander.traverseBuf.addString(iWander.traverseRecordSeparator); } } oldLength = iWander.traverseBuf.length(); } return 0; } idx parseFilters(sTxtTbl &tbl, idx *colArg, const char *filterStr, const char *filterCol) { idx cntCols = tbl.cols(); if (!cntCols){ return 0; } if (!filterStr || !filterCol){ return 0; } idx clen; idx plen = sLen (filterCol); bool isFound = false; for(idx icol = 0; icol < cntCols; ++icol) { const char * cell = tbl.cell(-1, icol, &clen); if( (plen == clen) && memcmp(filterCol, cell, plen) == 0 ) { *colArg = icol; isFound = true; break; } } return isFound ? sLen(filterStr) : 0; } // Needed because objs2() only searches by meaning=x OR version=y static bool findDatabaseId(sHiveId & result, const sUsr & user, idx lookfordb = 0) { switch(lookfordb) { case 0: return sviolin::SpecialObj::findTaxDb(result, user, "2"); case 1: return sviolin::SpecialObj::findTaxDb(result, user, "3"); case 2: return sviolin::SpecialObj::find(result, user, "ionCodon", "2"); } result = sHiveId::zero; return false; } namespace { class FilterList00 : public sStr { public: //! inp is JSON array of strings or raw, unquoted string FilterList00(const char * inp) { if( inp && inp[0] == '[' ) { sJSONParser parser; if( parser.parse(inp) && parser.result().isList() ) { for(idx i = 0; i < parser.result().dim(); i++) { addString(parser.result().getListElt(i)->asString()); add0(); } } } else { addString(inp); } add0(2); } }; }; //static bool findcodonDBRecordsid(sHiveId & result, const sUsr & user) //{ // sUsrObjRes obj_res; // user.objs2("special", obj_res, 0, "meaning,version", "^ncbiTaxonomy$,^2\\.", "meaning,version"); // for(sUsrObjRes::IdIter it = obj_res.first(); obj_res.has(it); obj_res.next(it)) { // const sUsrObjRes::TObjProp * o = obj_res.get(it); // const char * meaning = obj_res.getValue(obj_res.get(*o, "meaning")); // const char * version = obj_res.getValue(obj_res.get(*o, "version")); // if( meaning && version && !strcmp(meaning, "ncbiTaxonomy") && !strncmp(version, "2.", 2) ) { // result = *obj_res.id(it); // return true; // } // } // result = sHiveId::zero; // return false; //} idx DnaCGI::CmdIon(idx cmd) { /******************************** * CGI command for ionAnnot files ********/ // const char * ionObjIDs = pForm->value("objs",0); // const char * ionType=pForm->value("ionType","u-ionAnnot"); // const char * fileNameTemplate=pForm->value("file",0); sIonWander iWander; /* if( !sHiveIon::InitalizeIonWander(user, &iWander, ionObjIDs, ionType,fileName )) return 0; // {ops !} */ sStr statement; // Read Database from TaxIon sStr myPath; sStr ionP, error_log; if( !sviolin::SpecialObj::findTaxDbIonPath(ionP, *user, 0, 0, &error_log) ) { error(error_log.ptr()); outHtml(); return 1; } iWander.addIon(0)->ion->init(ionP.ptr(), sMex::fReadonly); // iWander.addIon(0)->ion->init("/home/vsim/data-stage/tax/dst/ncbiTaxonomy",sMex::fReadonly); // ionPath.printf(0,"/home/vsim/data-stage/tax/dst/ncbiTaxonomy"); sIonWander genericWander; switch(cmd) { /******************************** * Developer Note: javascript viewers are dependable of how the data is * generated by dna.cgi of eIonNcbiTax and eIonTaxPathogenInfo commands, they * need to have the same taxid information in the same row. * Any questions with Kate, thx ********/ case eIonWander :{ // open working ions if any sVec<sHiveId> ionObjs; sHiveId::parseRangeSet(ionObjs, pForm->value("objs")); const char * ionFile = pForm->value("ionfile","ion.ion"); if (!sHiveIon::loadIonFile(user,ionObjs,genericWander, ionFile)) { error("Could not find the objects having this name [%s]",ionFile); outHtml(); return 1; } // set query sDic < sMex::Pos > bigD; idx qrylen;const char * query=pForm->value("query",0,&qrylen); if (!qrylen) { error("No query to run"); outHtml(); return 1; } genericWander.traverseCompile(query, qrylen, this, true); genericWander.maxNumberResults=pForm->ivalue("maxCnt",200); genericWander.setSepar(pForm->value("sepField"),pForm->value("sepRecord")); genericWander.debug=pForm->ivalue("debug"); genericWander.retrieveParametricWander(pForm,0); genericWander.bigDicCumulator=&bigD; // ddict func genericWander.traverse(); genericWander.traverseViewBigDic2D(); // reomve header of not idx hdr = pForm->ivalue("hdr",1); idx repos = 0; if (bigD.dim() && !hdr) { for (idx ip=0; ip < genericWander.traverseBuf.length(); ++ip) { if (genericWander.traverseBuf.ptr(ip)[0]=='\n') { repos=ip; break; } } } // Outputing dataForm.printf("%s", (genericWander.traverseBuf.length() == 0) ? "no result": genericWander.traverseBuf.ptr(repos)); outHtml(); return 1; } case eIonNcbiTax: { // Read Parameters sHiveId screenId(pForm->value("screenId")); const char * screenType = pForm->value("screenType", 0); const char * screenResult = pForm->value("screenResult", 0); bool showPercentage = pForm->ivalue("percentage", 0) == 1 ? true : false; idx accession = pForm->ivalue("accession", 0); // Load Table sTxtTbl tbl; sStr err, objname; bool success = loadScreeningFile(&tbl, screenId, screenType, screenResult, &err, &objname); if( !success ) { error("%s", err.ptr(0)); outHtml(); return 1; } const char *a = 0; iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseFieldSeparator = ":"; // load first ionQuery sStr ionQuery; ionQuery.addString( "\ o=find.taxid_name(taxid=='$taxid', tag='scientific name'); \ b=find.taxid_parent(taxid==o.taxid); \ d=count.taxid_parent(parent==b.parent); \ e=find.taxid_name(taxid==b.parent, tag='scientific name'); \ f=find.taxid_parent(taxid==e.taxid);\ print(e.name,e.taxid,f.rank,d.#,'//'); \ jump!.b(e.taxid,1); "); // iWander.debug = true; extractIonQueryfromTable(iWander, tbl, ionQuery.ptr(), "NONE"); sStr col2; col2.addString(iWander.traverseBuf, iWander.traverseBuf.length()); iWander.resetCompileBuf(); iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseFieldSeparator = ","; sStr ionQuery2; ionQuery2.addString("\ o=find.taxid_name(taxid=='$taxid', tag='scientific name'); \ a=find.taxid_parent(taxid==o.taxid); \ printCSV(o.name,a.rank);"); extractIonQueryfromTable(iWander, tbl, ionQuery2.ptr(), "no match,no rank"); sStr col1; col1.addString(iWander.traverseBuf, iWander.traverseBuf.length()); // I should have all the results in col1 and col2 to produce the exit sStr preOut, cbuf, dst, tstr; sStr tablename; real percRatio; if( accession == 1 ) { // printing the header if( showPercentage ) { preOut.printf("accession,taxid,matchname,rank,path,matchCnt,matchCnt_pct,min,min_pct,max,max_pct,mean,mean_pct,stddev,intval\n"); } else { preOut.printf("accession,taxid,matchname,rank,path,matchCnt,matchCnt_pct,min,max,mean,stddev,intval\n"); } tablename.addString("dnaAccessionBasedResult.csv"); } else { // printing the header if( showPercentage ) { preOut.printf("taxid,matchname,rank,path,matchCnt,matchCnt_pct,min,min_pct,max,max_pct,mean,mean_pct,stddev,intval\n"); } else { preOut.printf("taxid,matchname,rank,path,matchCnt,matchCnt_pct,min,max,mean,stddev,intval\n"); } tablename.addString("dnaTaxidBasedResult.csv"); } char * co1 = col1.ptr(0); char * co2 = col2.ptr(0); idx shiftCol = 0; for(idx i = 0; i < tbl.rows(); i++) { idx icols = 0; if( accession == 1 ) { // // print accession // cbuf.cut(0); // tbl.printCell(cbuf, i, icols++); // if( strcmp(cbuf.ptr(), "-1") == 0 ) { // cbuf.printf(0, "\"n/a\""); // } // preOut.printf("%s,", cbuf.ptr()); // print accession cbuf.cut(0); tbl.printCell(cbuf, i, icols++); if( strcmp(cbuf.ptr(), "-1") == 0 ) { cbuf.printf(0, "\"n/a\""); } preOut.printf("%s,", cbuf.ptr()); sVariant mean, perc; tbl.val(mean, i, 7, false); tbl.val(perc, i, 4, false); percRatio = perc.asReal() / mean.asReal(); icols++; shiftCol = 2; // Skip second column as well } else { sVariant mean, perc; tbl.val(mean, i, 5, false); tbl.val(perc, i, 2, false); percRatio = perc.asReal() / mean.asReal(); shiftCol = 0; } // taxid and matchname and rank cbuf.cut(0); tbl.printCell(cbuf, i, icols++); if( strncmp(cbuf.ptr(), "-1", 2) == 0 ) { preOut.printf("n/a,unaligned reads,no rank,"); } else { preOut.printf("%s,%s,", cbuf.ptr(), co1); } // path if( co2 && (strncmp(co2, "NONE", 4) == 0) ) { preOut.addString("\"/no:1:no rank:0/\","); } else { dst.cut(0); tstr.cut(0); sString::searchandInvertStrings(&tstr, co2, 0, "://", "/"); sString::searchAndReplaceStrings(&dst, tstr.ptr(0), tstr.length(), "root" _ "/:" __, "all" _ "/" __, 0, false); *(dst.ptr(0)) = '/'; preOut.printf("\"%s/\",", dst.ptr(0)); } //matchcount and percentage for(; icols < tbl.cols(); ++icols) { if( icols == (7 + shiftCol) ) { if( pForm->uvalue("downloadCSVFile", 0) ) { preOut.printf("%0.1f+/-%0.2f", tbl.rval(i, icols - 2), tbl.rval(i, icols)); } else { preOut.printf("%0.1f\302\261%0.2f", tbl.rval(i, icols - 2), tbl.rval(i, icols)); } } else { cbuf.cut(0); if( showPercentage && icols > (2 + shiftCol) && icols <= (5 + shiftCol) ) { sVariant value; tbl.val(value, i, icols, false); cbuf.printf("%s,%0.2f", value.asString(), value.asReal() * percRatio); } else { tbl.printCell(cbuf, i, icols); } preOut.addString(cbuf.ptr(), cbuf.length()); preOut.add(",", 1); } } preOut.cut(preOut.length() - 1); // Remove the last comma preOut.add("\n", 1); co1 = sString::next00(co1); co2 = sString::next00(co2); } outBin(preOut.ptr(), preOut.length(), 0, true, "%s-%" DEC "-%s", objname.ptr(0), screenId.objId(), tablename.ptr()); return 1; } case eIonTaxInfo: { const char * taxidInput = pForm->value("taxid", 0); if( strncmp(taxidInput, "NO_INFO", 7) == 0 ) { dataForm.printf("id,name,path,value\n"); dataForm.printf("1,taxid,,0\n"); dataForm.printf("1,parentid,,0\n"); dataForm.printf("1,rank,,no rank\n"); dataForm.printf("1,taxName,0,no name\n"); // dataForm.printf("1,bioprojectID,,0\n"); dataForm.printf("1,path,,no path\n"); outHtml(); return 1; } sStr path, altnames, info; sStr ionQuery1; ionQuery1.printf( "\ o=find.taxid_name(taxid=='%s', tag='scientific name'); \ b=find.taxid_parent(taxid==o.taxid); \ d=count.taxid_parent(parent==b.parent); \ e=find.taxid_name(taxid==b.parent, tag='scientific name'); \ printCSV(e.name,e.taxid, d.#,'//'); \ jump!.b(e.taxid,1); ", taxidInput); iWander.traverseFieldSeparator = ":"; iWander.traverseCompile(ionQuery1); iWander.traverse(); path.addString(iWander.traverseBuf, iWander.traverseBuf.length()); if( path.length() == 0 ) { path.addString("/no path"); } else { sStr pdst; // char *cont00 = path.ptr(0); // while(*cont00){cont00++;} // *cont00 = '0'; sString::searchandInvertStrings(&pdst, path.ptr(0), 0, "://", "/"); path.cut(1); sString::searchAndReplaceStrings(&path, pdst.ptr(0), pdst.length(), "root" _ "/:" __, "all" _ "/" __, 0, false); *(path.ptr(0)) = '/'; } iWander.resetCompileBuf(); sStr ionQuery2; ionQuery2.printf("\ o=find.taxid_name(taxid=='%s');\ printCSV(o.name);", taxidInput); const char *a = 0; iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseCompile(ionQuery2); iWander.traverse(); altnames.addString(iWander.traverseBuf, iWander.traverseBuf.length()); altnames.add0(2); iWander.resetCompileBuf(); sStr ionQuery3; ionQuery3.printf("\ o=find.taxid_name(taxid=='%s',tag=='scientific name');\ a=find.taxid_parent(taxid==o.taxid);\ printCSV(o.taxid,a.parent,a.rank,o.name);", taxidInput); iWander.traverseCompile(ionQuery3); iWander.traverse(); sString::searchAndReplaceStrings(&info, iWander.traverseBuf.ptr(0), iWander.traverseBuf.length(), "," __, 0, 0, false); // Generate the Output // taxid, parentid, rank, taxName, bioprojectID, path idx irow = 1; dataForm.printf("id,name,path,value\n"); dataForm.printf("%" DEC ",taxid,,%s\n", irow, info.ptr(0)); const char *parentid = sString::next00(info); dataForm.printf("%" DEC ",parentid,,%s\n", irow, parentid); const char *rank = sString::next00(parentid); dataForm.printf("%" DEC ",rank,,%s\n", irow, rank); idx iname = 0; for(const char *p = altnames; p; p = sString::next00(p)) { dataForm.printf("%" DEC ",taxName,%" DEC ",\"%s\"\n", irow, iname++, p); } // dataForm.printf("%" DEC ",bioprojectID,,0\n", irow); dataForm.printf("%" DEC ",path,,%s/\n", irow, path.ptr(0)); outHtml(); return 1; } case eIonTaxDownInfo: { const char *taxidInput = pForm->value("taxid", 0); idx level = pForm->ivalue("level",1); idx cnt = pForm->ivalue("cnt",1000); idx start = pForm->ivalue("start",0); if( taxidInput && strncmp(taxidInput, "NO_INFO", 7) == 0 ) { return 1; } sStr preOut; sStr outInfo; preOut.printf("taxid,parent,rank,name,numChild\n"); sTaxIon taxIon(ionP.ptr()); preOut.printf("%s\n",taxIon.getTaxIdInfo(taxidInput)); taxIon.getTaxTreeChildrenInfo(taxidInput, 0, &outInfo); idx curlevel = 1; idx nextround = outInfo.length(); idx printCount = 0; idx startCount = 0; for(char *tc = outInfo; tc && (printCount < cnt); tc = sString::next00(tc)) { // extract taxid from tc char *ptr = tc; while( *ptr != ',' ) {++ptr;} idx ptrlen = ptr - tc; ++ptr; char *parptr = ptr; while( *parptr != ',' ) {++parptr;} idx parptrlen = parptr - ptr; if ( (ptrlen == parptrlen) && (strncmp(tc, ptr, ptrlen) == 0)){ continue; } idx pos = tc - outInfo.ptr(0); if (pos >= nextround){ nextround = outInfo.length(); if (curlevel >= level){ break; } ++curlevel; } taxIon.getTaxTreeChildrenInfo(tc, ptrlen, &outInfo); tc = outInfo.ptr(pos); // update tc, as the outInfo buffer changed it's location in memory ++startCount; if (startCount > start){ preOut.printf("%s\n", tc); ++printCount; } } dataForm.addString(preOut.ptr(), preOut.length()); outHtml(); return 1; } case eIonTaxParent: { const char * taxidForm = pForm->value("taxid", 0); idx parent = pForm->ivalue("parent", 1); const char * name = pForm->value("name", 0); bool findParent = pForm->boolvalue("commonParent", 0); sStr path; sTaxIon taxIon(ionP.ptr()); sStr taxidList; taxidList.cut(0); if (taxidForm){ sString::searchAndReplaceSymbols(&taxidList, taxidForm, 0, ",", 0, 0, true, true, true, true); } if (findParent){ // I will loop through all taxid's to find the common ancestor const char * taxidstring = taxidList.ptr(0); idx taxid = 0; sscanf(taxidstring, "%" DEC, &taxid); if( taxid == 0 ) { break; } taxIon.filterbyParent(1, taxid, &path, true); // Path contains all the taxid's to the root of the first element taxidstring = sString::next00(taxidstring); const char *parentPath = path.ptr(0); idx taxParent = 1; sscanf(parentPath, "%" DEC, &taxParent); sStr tmpPath; for(; taxidstring && (taxParent != 1); taxidstring = sString::next00(taxidstring)) { tmpPath.cut(0); idx taxId = atoidx((const char *)taxidstring); bool success = taxIon.filterbyParent(taxParent, taxId, &tmpPath, true); tmpPath.add0(); if (!success){ // we will have to find the common taxid of: parentPath and tmpPath parentPath = sString::next00(parentPath); for(; parentPath; parentPath = sString::next00(parentPath)) { idx result = sString::compareChoice(parentPath, tmpPath.ptr(0), 0, false, 0, true, 0); if (result != -1){ sscanf(parentPath, "%" DEC, &taxParent); break;// Look } } } } parent = taxParent; } dataForm.addString("taxid,parent,rank,name,numChild\n"); if(taxidList.length()){ bool printFirstRow = true; for(const char * taxidstring = taxidList.ptr(0); taxidstring; taxidstring = sString::next00(taxidstring)) { idx taxid = 0; sscanf(taxidstring, "%" DEC, &taxid); if (taxid == 0){ continue; } path.cut(0); // Analyze path taxIon.filterbyParent(parent, taxid, &path); path.add0(); // Invert the order of the taxonomy output idx numRows = sString::cnt00(path.ptr()); idx offset = printFirstRow ? 0 : 1; for(idx irow = numRows-(1+offset); irow >= 0; --irow) { const char *ptr = sString::next00(path.ptr(0), irow); dataForm.addString(ptr); dataForm.add("\n", 1); printFirstRow = false; } } } else if (name){ idx limit = pForm->ivalue("limit", 20); sStr ionResults00; ionResults00.cut(0); taxIon.getTaxIdsByName(name, 0, &ionResults00); char *r00 = ionResults00.ptr(0); sString::searchAndReplaceSymbols(r00, 0, "\n", 0, 0, true, true, true, true); idx prevTaxid = 0; idx cnt = 0; bool printFirstRow = true; for(const char *tc = ionResults00.ptr(0); tc && cnt < limit; tc = sString::next00(tc)) { // Extract taxid, and find path to parent idx localTaxid = atoidx(tc); if (prevTaxid != localTaxid){ path.cut(0); // Analyze path bool success = taxIon.filterbyParent(parent, localTaxid, &path); if (success){ // Invert the order of the taxonomy output idx numRows = sString::cnt00(path.ptr()); idx offset = printFirstRow ? 0 : 1; for(idx irow = numRows-(1+offset); irow >= 0; --irow) { const char *ptr = sString::next00(path.ptr(0), irow); dataForm.addString(ptr); dataForm.add("\n", 1); printFirstRow = false; } // dataForm.addString(path.ptr(0), path.length()); ++cnt; } prevTaxid = localTaxid; } } } dataForm.add0cut(); outHtml(); return 1; } case eIonTaxPathogenInfo: { // Read Parameters sHiveId screenId(pForm->value("screenId")); const char * screenType = pForm->value("screenType", 0); const char * screenResult = pForm->value("screenResult", 0); // Load Table sTxtTbl tbl; sStr err, objname; bool success = loadScreeningFile(&tbl, screenId, screenType, screenResult, &err, &objname); if( !success ) { error("%s", err.ptr(0)); outHtml(); return 1; } const char *a = 0; iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseFieldSeparator = ","; // load first ionQuery sStr ionQuery; ionQuery.addString( "\ a=find.taxid_name(taxid=='$taxid', tag='scientific name');\ o=find.taxid_pathogen(taxid==a.taxid); \ printCSV(o.taxid,a.name,o.pathogen,o.pathogenic,o.severity,o.transmission_food, o.transmission_air, o.transmission_blood, o.human_host); \ "); // iWander.debug = true; extractIonQueryfromTable(iWander, tbl, ionQuery.ptr(), "NONE"); sStr col, buf; sStr preOut, tablename; col.addString(iWander.traverseBuf, iWander.traverseBuf.length()); // Table Header preOut.printf("taxid,name,pathogen,pathogenic,severity,transmission_food,transmission_air,transmission_blood,human_host\n"); char * co1 = col.ptr(0); for(idx i = 0; i < tbl.rows(); i++) { buf.cut(0); if( co1 && (strncmp(co1, "NONE", 4) == 0) ) { tbl.printCell(buf, i, 0); preOut.printf("%s,,,,,,,,", buf.ptr()); } else { preOut.printf("%s", co1); } preOut.add("\n", 1); co1 = sString::next00(co1); } tablename.addString("dnaTaxPathogenTable.csv"); outBin(preOut.ptr(), preOut.length(), 0, true, "%s-%" DEC "-%s", objname.ptr(0), screenId.objId(), tablename.ptr()); return 1; } case eIonAnnotInfo: { statement.printf("a=foreach(9606,2); b=find.taxid_parent(taxid==a.); print(b.taxid,b.parent,b.rank); "); } break; case eIonAnnotIdMap: { statement.printf("a=foreach(9606,2); b=find.taxid_parent(taxid==a.); print(b.taxid,b.parent,b.rank); "); } break; case eIonTaxidCollapse: { // Read Parameters // cmd=ionTaxidCollapse&svcType=svc-refseq-processor&fileSource=archaea_all_species.tab&taxid=2172&searchDeep=true sStr localBuf; localBuf.cut(0); // sHiveId objId(pForm->value("objId", &localBuf)); sVec <sHiveId> subIDs; sHiveId::parseRangeSet(subIDs, pForm->value("objId")); if (subIDs.dim() == 0){ const char * svcType = pForm->value("svcType", "svc-refseq-processor"); if (!svcType){ error("can't find objId's to get the source files in ionTaxidCollapse"); outHtml(); return 1; } sUsrObjRes subIDList; user->objs2(svcType, subIDList, 0, 0, 0, 0, false, 0, 0); subIDs.add(subIDList.dim()); idx i = 0; for(sUsrObjRes::IdIter it = subIDList.first(); subIDList.has(it); subIDList.next(it)) { subIDs[i++] = *subIDList.id(it); } if (subIDs.dim() == 0){ error("can't find objId's based on svctype: %s", svcType); outHtml(); return 1; } } const char * sourceFile = pForm->value("fileSource", 0); const char * outFile = pForm->value("outputFile", 0); // const char * ginumber = pForm->value("ginumber", 0); const char * accessionnumber = pForm->value("accessionnumber", 0); const char * taxidInput = pForm->value("taxid", 0); bool searchTree = pForm->boolvalue("searchDeep", false); sTaxIon taxIon(ionP.ptr()); if (!taxidInput && accessionnumber){ taxidInput = taxIon.getTaxIdsByAccession(accessionnumber); } // load first ionQuery sStr ionQuery; if (searchTree == false){ ionQuery.printf(0,"\ o=find.taxid_name(taxid=='$Taxid', tag='scientific name');\ f=print(o.taxid);"); } else { ionQuery.printf(0,"\ o=find.taxid_name(taxid=='$Taxid', tag='scientific name'); \ e=jump.f(o.taxid, '%s'); \ b=find.taxid_parent(taxid==o.taxid); \ e=find.taxid_name(taxid==b.parent, tag='scientific name'); \ jump.f(e.taxid, '%s'); \ jump!.b(e.taxid,1); \ f=print(e.taxid);", taxidInput, taxidInput); } // Iterate over sHiveIds sDic<idx> codonDict; idx plen = 3; idx collapseTaxids = 0; bool firstTime = true; for (idx iter = 0; iter < subIDs.dim(); ++iter){ // Load Table sTxtTbl tbl; sStr err, objname; bool success = loadScreeningFile(&tbl, subIDs[iter], sourceFile, outFile ? outFile : 0, &err, &objname, true); if( !success ) { continue; error("%s", err.ptr(0)); outHtml(); return 1; } const char *a = 0; iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseFieldSeparator = ","; iWander.traverseBuf.cut(0); extractIonQueryfromTable(iWander, tbl, ionQuery.ptr(), "NONE", firstTime); firstTime = false; // Parse traverseBuf for each row sStr col, buf; sStr tablename; col.addString(iWander.traverseBuf, iWander.traverseBuf.length()); if (codonDict.dim() == 0){ // Create a dictionary out of the codon's idx clen = 0; for(idx icol = 0; icol < tbl.cols(); ++icol) { const char * hdr = tbl.cell(-1, icol, &clen); if( plen == clen ) { idx isvalid = true; const char *codon = hdr; unsigned char let; for(idx ilet = 0; ilet < plen; ++codon, ++ilet) { let = sBioseq::mapATGC[(idx) (*codon)]; if( let < 0 || let > 3 ) { isvalid = false; } } if( isvalid ) { // Create a dictionary out of the id idx *cnt = codonDict.set(hdr, plen); *cnt = 0; } } } } char * co1 = col.ptr(0); idx lencolumn = 0; idx lentaxid = sLen (taxidInput); FilterList00 filterIn(pForm->value("filterIn", 0)); FilterList00 filterInCol(pForm->value("filterInColName", 0)); FilterList00 filterOut(pForm->value("filterOut", 0)); FilterList00 filterOutCol(pForm->value("filterOutColName", 0)); sStr csv_buf; sVec<idx> icolInFilters, icolOutFilters; for(const char * colname = filterInCol.ptr(); colname && colname[0]; colname = sString::next00(colname)) { *icolInFilters.add(1) = tbl.colId(colname); } for(const char * colname = filterOutCol.ptr(); colname && colname[0]; colname = sString::next00(colname)) { *icolOutFilters.add(1) = tbl.colId(colname); } for(idx i = 0; i < tbl.rows(); i++) { buf.cut(0); lencolumn = sLen(co1); if( co1 && (lencolumn == lentaxid) && (strncmp(co1, taxidInput, lencolumn) == 0) ) { // I found it and collapse bool isValid = true; const char * filt = 0; idx ifilt = 0; for(ifilt = 0, filt = filterIn.ptr(); ifilt < icolInFilters.dim(); ifilt++, filt = filt && filt[0] ? sString::next00(filt) : 0) { csv_buf.cut0cut(); tbl.printCell(csv_buf, i, icolInFilters[ifilt]); if( strcmp(filt ? filt : sStr::zero, csv_buf.ptr()) == 0 ) { isValid = true; } else { isValid = false; break; } } if( isValid ) { for(ifilt = 0, filt = filterOut.ptr(); ifilt < icolOutFilters.dim(); ifilt++, filt = filt && filt[0] ? sString::next00(filt) : 0) { csv_buf.cut0cut(); tbl.printCell(csv_buf, i, icolOutFilters[ifilt]); if( strcmp(filt ? filt : sStr::zero, csv_buf.ptr()) == 0 ) { isValid = false; break; } else { isValid = true; } } } if (isValid){ // Go for all the columns and find its id and value ++collapseTaxids; for(idx icol = 0; icol < tbl.cols(); ++icol) { csv_buf.cut0cut(); tbl.printCell(csv_buf, -1, icol); idx * isCodon = codonDict.get(csv_buf.ptr(), csv_buf.length()); if( isCodon ) { idx resultCount = tbl.ival(i, icol); (*isCodon) = (*isCodon) + resultCount; } } } } else if( co1 && (strncmp(co1, "NONE", 4) == 0) ) { // const char *ccell = tbl.cell(i, 2, &clen); // ::printf("%.*s\n", clen, ccell); } co1 = sString::next00(co1); } } // We have everything accumulated in the dictionary // Let's prepare the output table idx totCnt = 0; idx gcCnt = 0; idx gc[3] = { 0, 0, 0 }; // plen should be three for(idx i = 0; i < codonDict.dim(); ++i) { idx codoncnt = *codonDict.ptr(i); const char * key = (const char *) (codonDict.id(i)); totCnt += codoncnt; const char *codon = key; unsigned char let; idx containsGC = 0; for(idx ilet = 0; ilet < plen; ++codon, ++ilet) { let = sBioseq::mapATGC[(idx) (*codon)]; if( let == 1 || let == 2 ) { gc[ilet] += codoncnt; ++containsGC; } } gcCnt += (codoncnt * containsGC); } // Generate the Output dataForm.printf("id,value\n"); dataForm.printf("taxid,%s\n", taxidInput); dataForm.printf("collapse,%" DEC "\n", collapseTaxids); dataForm.printf("\"#codon\",%" DEC "\n", totCnt); dataForm.printf("\"GC%%\",%0.2lf\n", totCnt ? (real)(gcCnt*100)/(3*totCnt) : 0); dataForm.printf("\"GC1%%\",%0.2lf\n", totCnt ? (real)(gc[0]*100)/(totCnt) : 0); dataForm.printf("\"GC2%%\",%0.2lf\n", totCnt ? (real)(gc[1]*100)/(totCnt) : 0); dataForm.printf("\"GC3%%\",%0.2lf\n", totCnt ? (real)(gc[2]*100)/(totCnt) : 0); idx idlen; for(idx i = 0; i < codonDict.dim(); ++i) { const char *id = (const char *) (codonDict.id(i, &idlen)); dataForm.printf("%.*s,%" DEC "\n", (int)idlen, id, *codonDict.ptr(i)); } outHtml(); return 1; } case eIonTaxidByName:{ const char * name = pForm->value("name", 0); idx parent = pForm->ivalue("parent", 0); idx limit = pForm->ivalue("limit", 20); // bool filterbyParent = ? true : false; sTaxIon taxIon(ionP.ptr()); sStr ionResults00; ionResults00.cut(0); dataForm.printf("id,value\n"); if (!parent){ taxIon.getTaxIdsByName(name, limit, &ionResults00); for(const char *tc = ionResults00.ptr(0); tc; tc = sString::next00(tc)) { dataForm.printf("%s\n", tc); } } else { taxIon.getTaxIdsByName(name, 0, &ionResults00); // Filter by Parent sStr aux1; idx cnt = 0; char *r00 = ionResults00.ptr(0); sString::searchAndReplaceSymbols(r00, 0, "\n", 0, 0, true, true, true, true); idx prevTaxid = -1; for(const char *tc = ionResults00.ptr(0); tc && cnt < limit; tc = sString::next00(tc)) { aux1.cut(0); sString::copyUntil(&aux1, tc, 0, ","); idx taxId = atoidx((const char *)aux1.ptr()); if (prevTaxid == taxId){ // to prevent looking for repeated prevTaxid's from the original search continue; } if (taxIon.filterbyParent(parent, taxId)){ dataForm.printf("%s\n", tc); ++cnt; } prevTaxid = taxId; } } outHtml(); return 1; } case eIonCodonDB:{ sHiveId codID(pForm->value("id")); if( !codID && !findDatabaseId(codID, *user, 2) ) { error("codon Database is missing"); outHtml(); return 1; } sUsrObj * codonObj = user->objFactory(codID); if( !codonObj || !codonObj->Id() ) { error("codon database ID is invalid"); outHtml(); delete codonObj; return 1; } sStr ioncodonPath; codonObj->getFilePathname(ioncodonPath, pForm->value("ionCodon", "ionCodon.ion")); if( !ioncodonPath ) { error("Incorrect codon ionDB files"); outHtml(); delete codonObj; return 1; } if( ioncodonPath.length() > 4 && sIsExactly(ioncodonPath.ptr(ioncodonPath.length() - 4), ".ion") ) { ioncodonPath.cut0cut(ioncodonPath.length() - 4); // remove '.ion' extension from the string - sIonWander requires basename } sIonWander cWander; cWander.addIon(0)->ion->init(ioncodonPath.ptr(), sMex::fReadonly); const char *type = pForm->value("type", 0); const char *name = pForm->value("name", 0); const char *taxid = pForm->value("taxid", 0); const char *assembly = pForm->value("assembly", 0); bool boolRegex = pForm->boolvalue("regex", 1); const char *regex = boolRegex ? "regex:" : ""; // idx start = pForm->ivalue("start", 0); // idx cnt = pForm->ivalue("cnt", 0); if (!type || !(name || taxid || assembly)){ error("can't find query to search"); outHtml(); delete codonObj; return 1; } const char *column = taxid ? "taxid" : (name ? "name" : "assembly"); const char *value = taxid ? taxid : name ? name : assembly; // Validate column and value sStr t1val, tval, cval; sString::cleanEnds(&cval, column, 0, "\"" sString_symbolsBlank, true); column = cval.ptr(0); sString::cleanEnds(&tval, value, 0, "\"" sString_symbolsBlank, true); // Protect single quotes from the value sString::searchAndReplaceStrings(&t1val, tval, tval.length(), "\'" __, "\\'" __, 0, true); value = t1val.ptr(0); if (boolRegex){ regex_t preg; if( regcomp(&preg, value, REG_EXTENDED) == 0 ) { regfree(&preg); } else { error("Invalid regular expression syntax in query\n"); outHtml(); delete codonObj; return 1; } } cWander.resetCompileBuf(); sStr ionQuery; ionQuery.printf(0, "\ a=search.row(name=%s,value='%s%s'); \ b=find.row(#R=a.#R,name='%s');\ c=find.row(#R=b.#R,name='taxid');\ d=find.row(#R=b.#R,name='assembly');\ e=find.row(#R=b.#R,name='name');\ printCSV(c.value,d.value,e.value); ", column, regex, value, type); cWander.traverseFieldSeparator = ","; cWander.traverseCompile(ionQuery); cWander.traverse(); dataForm.printf("taxid,assembly,name\n"); dataForm.printf("%s", (cWander.traverseBuf.length() == 0) ? "0,0,0": cWander.traverseBuf.ptr()); outHtml(); delete codonObj; return 1; } case eExtendCodonTable: { sVec <sHiveId> subIDs; sHiveId::parseRangeSet(subIDs, pForm->value("objId")); const char * srcName = pForm->value("srcName"); if (subIDs.dim() == 0){ error("can't find objId"); outHtml(); return 1; } // Get the output Filename sUsrFile sf(subIDs[0], user); sStr outfilePathname; if( sf.Id() ) { sf.makeFilePathname(outfilePathname, "codonDB.csv"); } sTxtTbl tbl; sStr err; bool success = loadScreeningFile(&tbl, subIDs[0], srcName, 0, &err, 0, false); if( !success ) { error("%s", err.ptr(0)); outHtml(); return 1; } // Identify the right columns to work with: idx cntRows = tbl.rows(); idx cntCols = tbl.cols(); enum enumColumns { cTaxid, cDivision, cType, cAssembly, cName, cLast = cName }; idx plen; idx icols[cLast + 1]; for(idx ipa = 0; ipa < sDim(icols); ipa++) { icols[ipa] = -sIdxMax; } sStr colname; for(idx icol = 0; icol < cntCols; ++icol) { colname.cut0cut(); tbl.printCell(colname, -1, icol); if( sIsExactly(colname.ptr(), "taxid") ) { icols[cTaxid] = icol; } else if( sIsExactly(colname.ptr(), "division") ) { icols[cDivision] = icol; } else if( sIsExactly(colname.ptr(), "type") || sIsExactly(colname.ptr(), "organellar") ) { icols[cType] = icol; } else if( sIsExactly(colname.ptr(), "assembly") ) { icols[cAssembly] = icol; } else if( sIsExactly(colname.ptr(), "name") || sIsExactly(colname.ptr(), "species") ) { icols[cName] = icol; } } // We need to collapse the parent nodes // Each parent Node contains: // - unique taxid // - type, merge the different types under the node // - division, merge different division types as well enum enumType { genomic = 0x1, mitochondrion = 0x2, chloroplast = 0x4, plastid = 0x8, leucoplast = 0x10, chromoplast = 0x20 }; typedef struct { enumType eType; const char *nametype; const char letterType; } CodonKnownTypes; CodonKnownTypes c_types[] = { { genomic, "genomic" __, 'G' }, { mitochondrion, "mitochondrion" __, 'M' }, { chloroplast, "chloroplast" __, 'C' }, { plastid, "plastid", 'P' }, { leucoplast, "leucoplast" __, 'L' }, { chromoplast, "chromoplast" __, 'O' } }; idx numtypes = 0; while(c_types[++numtypes].nametype); enum enumDivision { genbank = 0x1, refseq = 0x2 }; idx divisions[2] = {genbank, refseq}; const char *listDivision = "genbank" _ "refseq" __; sDic <idx> parents; sStr cbuf, tbuf, dbuf; sStr taxCurrent, taxParent; sStr auxout; auxout.cut(0); sTaxIon taxIon(ionP.ptr()); idx taxId; sStr buf1; sStr buf2; for (idx irow = 0; irow < cntRows; ++irow){ taxCurrent.cut(0); tbl.printCell(taxCurrent, irow, icols[cTaxid]); // Construct typedivision idx const char * stringtype = tbl.printCell(tbuf, irow, icols[cType]); idx type1 = 0; idx typeID; for(typeID = 0; typeID < numtypes; ++typeID) { if (strcmp(c_types[typeID].nametype, stringtype) == 0){ type1 = c_types[typeID].eType; break; } } const char * stringdivision = tbl.printCell(dbuf, irow, icols[cDivision]); idx aux2; sString::compareChoice(stringdivision, listDivision, &aux2, false, 0, true, 0); udx typedivision = (divisions[aux2] == genbank) ?(udx)type1 << 32 : (udx) type1 && 0xFFFFFFFF; //((udx) types[aux1] << 32) | (divisions[aux2]); if ((divisions[aux2] == refseq)){ buf1.cut(0); buf2.cut(0); tbl.printCell(buf1, irow, icols[cAssembly]); tbl.printCell(buf2, irow, icols[cName]); for(idx typeID = 0; typeID < numtypes; ++typeID) { auxout.add(",", 1); } for(idx typeID = 0; typeID < numtypes; ++typeID) { if ((c_types[typeID].eType & type1)){ auxout.add("1", 1); } auxout.add(",", 1); } auxout.add0cut(); auxout.printf("%.*s,%s,%s\n", (int)taxCurrent.length(), taxCurrent.ptr(), buf2.ptr(), buf1.ptr()); } do { taxId = atoidx((const char *)taxCurrent.ptr()); // Check the current taxid in the dictionary idx *value = parents.get(taxCurrent, taxCurrent.length()); if (!value){ // Add the taxid value = parents.set(taxCurrent, taxCurrent.length()); *value = typedivision; } else { // Check if the value changes udx locValue = (divisions[aux2] == genbank) ? (udx)*value&0xFFFFFFFF00000000 : (udx)*value&0xFFFFFFFF; udx result = locValue | typedivision ; if (result == locValue){ // We don't update taxId = 1; } else { // we must update *value = (divisions[aux2] == genbank) ? (result)|(*value&0xFFFFFFFF) : (*value&0xFFFFFFFF00000000)|(result&0xFFFFFFFF); } } // Get the next Parent taxParent.cut(0); taxIon.getParentTaxIds(taxCurrent.ptr(0), &taxParent); taxCurrent.cut(0); taxCurrent.addString(taxParent.ptr(0), taxParent.length()); } while (taxId > 1); } // Prepare a new ionquery to extract the name based on taxid sStr ionQuery; ionQuery.printf(0, "\ o=find.taxid_name(taxid=='$Taxid', tag='scientific name');\ f=printCSV(o.name);"); const char *a = 0; iWander.traverseRecordSeparator = (const char *) &a; iWander.traverseFieldSeparator = 0; iWander.traverseCompile(ionQuery); const char * pid = (const char *) iWander.parametricArguments.id(0, &plen); idx *toModify = (idx*) iWander.getSearchDictionaryPointer(pid, plen); // Add the information to the new table // We should have everything in the dictionary idx keylen; sFil outTable(outfilePathname); outTable.empty(); if (!outTable.ok()){ // Complain error("can't write in the output filename"); outHtml(); return 1; } // construct table header for(idx idiv = 0; idiv < 2; ++idiv) { char letDivision = idiv == 0 ? 'G' : 'R'; for(idx typeID = 0; typeID < numtypes; ++typeID) { outTable.add("t",1); outTable.add(&letDivision,1); outTable.add(&c_types[typeID].letterType, 1); outTable.add(",",1); } } outTable.addString("taxid,name,assembly\n"); for(idx i = 0; i < parents.dim(); ++i) { udx val = *parents.ptr(i); const char *key = (const char *) (parents.id(i, &keylen)); idx typeGenbank = val >> 32; idx typeRefseq = val & 0xFFFFFFFF; toModify[0] = sConvPtr2Int(key); toModify[1] = keylen; iWander.traverseBuf.cut(0); iWander.traverse(); iWander.traverseBuf.shrink00(); if (iWander.traverseBuf.length()){ for(idx typeID = 0; typeID < numtypes; ++typeID) { if ((c_types[typeID].eType & typeGenbank)){ outTable.add("1", 1); } outTable.add(",", 1); } // outTable.addNum(typeGenbank); // typeGenbank for(idx typeID = 0; typeID < numtypes; ++typeID) { if ((c_types[typeID].eType & typeRefseq)){ outTable.add("1", 1); } outTable.add(",", 1); } // outTable.addNum(typeRefseq); // typeRefseq outTable.add(key, keylen); // taxid outTable.add(",",1); outTable.add(iWander.traverseBuf.ptr(0), iWander.traverseBuf.length()); // name outTable.add(",0\n",3); } } outTable.add(auxout.ptr(),auxout.length()); outTable.add0cut(); return 1; } break; default: { //outPutLine.printf("Nothing found"); } break; } //iWander.debug=1; iWander.traverseCompile(statement.ptr()); //sStr t;iWander.printPrecompiled(&t);//::printf("%s\n\n",t.ptr()); iWander.traverse(); //sStr outPutLine; //outBin(outPutLine.ptr(), outPutLine.length(), 0, true, dtaBlobName.ptr(0)); return 1; // let the underlying Management code to deal with untreated commands } enum enumIonBioCommands { eIonGenBankAnnotPosMap, eIonAnnotTypes, eIonAnnotInfoAll }; idx lookForAlternativeSeqID(const char * seqID, sHiveIonSeq & hiWander, const char * wandername, idx cnt, idx cntStart, sStr & output, idx wanderIndex=-1) { sIonWander * iWander = &hiWander.wanderList[wandername]; const char * nxt; for( const char * p=seqID; p && *p && !strchr(sString_symbolsSpace,*p); p=nxt+1 ){ // scan until pipe | separated types and ids are there //const char * curType=p; nxt=strpbrk(p,"| "); // find the separator if(!nxt || *nxt==' ') break; const char * curId=nxt+1; nxt=strpbrk(nxt+1," |"); // find the separator if(!nxt) // if not more ... put it to thee end of the id line nxt=seqID+sLen(seqID);/// nxt=seqid+id1Id[1]; if(*nxt==' ') break; iWander->setSearchTemplateVariable("$seqid",6, curId, nxt-curId); hiWander.standardTraverse(output, 0, cnt, cntStart,false,wanderIndex); if (output.length()) { return 0; } else { const char * dot = strpbrk(curId,"."); if (dot){ iWander->setSearchTemplateVariable("$seqid",6, curId, dot-curId); hiWander.standardTraverse(output, 0, cnt, cntStart,false,wanderIndex); if (output.length()) { return 0; } if (iWander->cntResults) { return 0; } } } } return 0; } idx DnaCGI::CmdIonBio(idx cmd) { sStr blobName("result.csv"); sStr outPutContent; sStr seqID; formValue("seqID", &seqID, 0); idx iSub = formIValue("mySubID", -1) -1; idx fromComputation = formIValue("fromComputation", 1); idx sequenceLength = 0; std::auto_ptr < sUsrObj > al; if( !seqID && fromComputation ) { // used from alignment or heptagon if( !objs.dim() ) { return 1; } if (iSub==-2) { outPutContent.printf("no sequence identifier's specified"); outBin(outPutContent.ptr(), outPutContent.length(), 0, true, blobName.ptr(0)); return 1; } sUsrObj& obj = objs[0]; sVec < sHiveId > parent_proc_ids; obj.propGetHiveIds("parent_proc_ids", parent_proc_ids); al.reset(user->objFactory(parent_proc_ids.dim() ? parent_proc_ids[0] : sHiveId::zero)); if( !al.get() || !al->Id() ) { return 1; } sStr parentAlignmentPath; al->getFilePathname00(parentAlignmentPath, "alignment.hiveal" _ "alignment.vioal" __); if( !parentAlignmentPath ) { return 1; } sHiveal hiveal(user, parentAlignmentPath); sHiveseq Sub(user, al->propGet00("subject", 0, ";"), hiveal.getSubMode()); //seqID = Sub.id(iSub-1); // because iSub (retrieved from front-end is 1 based) seqID.printf(0, "%s", Sub.id(iSub)); sequenceLength = Sub.len(iSub); } if( !seqID.length() && fromComputation ) { outPutContent.printf("no sequence identifier's specified"); outBin(outPutContent.ptr(), outPutContent.length(), 0, true, blobName.ptr(0)); return 1; } idx cntStart = pForm->ivalue("start", 0); idx cnt = pForm->ivalue("cnt", 20); if( cnt == -1 ) cnt = sIdxMax; idx pos_start = pForm->ivalue("pos_start", 1); idx pos_end = pForm->ivalue("pos_end", 0); if (pos_start==-1){ pos_end=sIdxMax; } if (!pos_end && sequenceLength) pos_end = sequenceLength; if( !pos_end ) pos_end = pos_start + 10000; const char * ionObjIDs = pForm->value("ionObjs", 0); if (!ionObjIDs) { ionObjIDs = pForm->value("ids",0); } const char * ionType = pForm->value("ionType", "u-ionAnnot"); const char * fileNameTemplate = pForm->value("file", "ion"); const char * feature = pForm->value("features", ""); sStr featureSplitByZero; sStr featureStatement("foreach"); if (sLen(feature) > 0){ sString::searchAndReplaceSymbols(&featureSplitByZero, feature, 0, ",", 0, 0, true, true, true, true); featureStatement.addString("(", 1); idx icomma = 0; for(const char *p = featureSplitByZero.ptr(0); p; p = sString::next00(p)) { if( icomma ) featureStatement.addString(",", 1); featureStatement.addString("\"",1); featureStatement.addString(p, sLen(p)); featureStatement.addString("\"",1); ++icomma; } featureStatement.addString(")", 1); } else featureStatement.addString(".type(\"\")"); switch(cmd) { case eIonAnnotInfoAll: { outPutContent.printf("running ion annot info all"); } break; case eIonGenBankAnnotPosMap: { if (!ionObjIDs || !sLen(ionObjIDs)){ outPutContent.printf("no object ids specified !!!\n"); outBin(outPutContent.ptr(), outPutContent.length(), 0, true, blobName.ptr(0)); return 1; } sHiveId mutualAlObjID(formValue("multipleAlObjID")); sUsrFile mutualAlignmentObj(mutualAlObjID, sQPride::user); sBioal * multipleAl=0; sStr mutualAlignmentPath; if( mutualAlignmentObj.Id() ) { mutualAlignmentObj.getFilePathname00(mutualAlignmentPath,"alignment.vioalt" _ "alignment.vioal" _ "alignment.hiveal" __); } bool isMutAl = mutualAlignmentPath.ok(); sHiveal mutAl(user, mutualAlignmentPath); const sBioseq::EBioMode mutualAlMode = sBioseq::eBioModeLong; sHiveseq Sub_mut(sQPride::user, isMutAl ? al->propGet00("subject", 0, ";") : 0 ,mutualAlMode);//Sub.reindex(); if( isMutAl ) { multipleAl=&mutAl; multipleAl->Qry = &Sub_mut; sBioseqAlignment::Al * hdr; sVec<idx> uncompM(sMex::fSetZero); idx * matchTrain = 0, iMutS = 0; for( iMutS = 0 ; iMutS < mutAl.dimAl(); ++iMutS ) { hdr = mutAl.getAl(iMutS); if( hdr->idQry() == iSub ) { matchTrain = mutAl.getMatch(iMutS); uncompM.resize(hdr->lenAlign()*2); sBioseqAlignment::uncompressAlignment(hdr,matchTrain,uncompM); break; } } if( iMutS < mutAl.dimAl() ) { pos_start = sBioseqAlignment::remapSubjectPosition( hdr,uncompM.ptr(),pos_start ) ; if (pos_end < sequenceLength){ pos_end = sBioseqAlignment::remapSubjectPosition(hdr,uncompM.ptr(),pos_end ) ; } } } sHiveIonSeq hi(user, ionObjIDs, ionType, fileNameTemplate); sStr ionQry1; //ionQry1.printf(0, "seq=foreach($id);a=find.annot(#range,seq.1,%" DEC ":%" DEC ",seq.1,%" DEC ":%" DEC ");", pos_start, pos_start, pos_end, pos_end); // #range=possort-max ionQry1.printf(0, "seq=foreach($id);a=find.annot(#range=possort-max,seq.1,%" DEC ":%" DEC ",seq.1,%" DEC ":%" DEC ");", pos_start, pos_start, pos_end, pos_end); ionQry1.printf("unique.1(a.record);f=%s;c=find.annot(seqID=a.seqID,record=a.record,id=f.1);", featureStatement.ptr(0)); //ionQry1.printf("d=find.annot(record=c.record);printCSV(d.seqID,d.pos,d.type,d.id);"); ionQry1.printf("printCSV(c.seqID,c.pos,c.type,c.id);"); if (pos_start==-1) { ionQry1.printf(0,"seq=foreach($id);a=find.annot(seqID=seq.1);printCSV(a.seqID,a.pos,a.type,a.id)"); } hi.addIonWander("seqPositionLookUp", ionQry1.ptr(0)); sStr ionQry2; // ionQry2.printf(0, "seq=foreach($id);a=find.annot(#range,seq.1,%" DEC ":%" DEC ",seq.1,%" DEC ":%" DEC ");", pos_start, pos_start, pos_end, pos_end); // #range=possort-max ionQry2.printf(0, "seq=foreach($id);a=find.annot(#range=possort-max,seq.1,%" DEC ":%" DEC ",seq.1,%" DEC ":%" DEC ");", pos_start, pos_start, pos_end, pos_end); ionQry2.printf("unique.1(a.record);f=%s;c=find.annot(seqID=a.seqID,record=a.record,type=f.1);", featureStatement.ptr(0)); //ionQry2.printf("unique.1(c.id);printCSV(c.seqID,c.pos,c.type,c.id);"); ionQry2.printf("printCSV(c.seqID,c.pos,c.type,c.id);"); hi.addIonWander("seqPositionLookUp_1", ionQry2.ptr(0)); sStr ionQry3; ionQry3.printf(0,"a=find.annot(id='$id', type='$type'); unique.1(a.seqID);dict(a.seqID,1);"); hi.addIonWander("idTypePositionLookUp", ionQry3.ptr(0)); sDic < sStr > dic; hi.annotMapPosition(&outPutContent, &dic, seqID.ptr(0), pos_start, pos_end, cnt, cntStart,0,multipleAl); } break; case eIonAnnotTypes: { sHiveIonSeq hi(user, ionObjIDs, ionType, fileNameTemplate); sStr ionQry1; const char * refGenomeList = pForm->value("refGenomeList", 0); sHiveseq ref(user, refGenomeList); const char * recordTypes = pForm->value("recordTypes", 0); const char * searchId = pForm->value("search",0); const char * searchType = pForm->value("searchType",0); outPutContent.cut(0); if (ref.dim()) { //sDic < idx > idList; sStr wandername, tmpOut; idx curIndex = 0, tmpStart =0; sStr mySeqID; ionQry1.printf(0, "relation=find.annot(seqID=$seqid);p=print(relation.seqID,relation.pos,relation.type,relation.id);"); if (searchId && searchType) { //ionQry1.printf(0,"a=search.annot(id=%s,type=%s);relation=find.annot(seqID=$seqid,record=a.record,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId,searchType); ionQry1.printf(0,"a=search.annot(id='regex:%s',type=%s);relation=find.annot(seqID=$seqid,type=a.type,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId,searchType); } else if (searchId) { ionQry1.printf(0,"a=search.annot(id='regex:%s');relation=find.annot(seqID=$seqid,record=a.record,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId); } else if (searchType) { ionQry1.printf(0,"a=search.annot(type=%s);relation=find.annot(seqID=$seqid,record=a.record,type=a.type);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchType); } wandername.printf(0,"lookUp"); sIonWander * hiWander = hi.addIonWander(wandername.ptr(), ionQry1.ptr(0)); for ( idx iSub=0 ; iSub<ref.dim() ; ++iSub ) { /* Start loop for the iSub*/ tmpStart = cntStart - curIndex; const char * mySeqID=ref.id(iSub); // mySeqID.printf(0,"%s",ref.id(iSub)); tmpOut.cut(0); //*idList.set(mySeqID)=num; //if(mySeqID[0]=='>')++mySeqID; hiWander->resetResultBuf(); hiWander->setSearchTemplateVariable("$seqid",6, mySeqID, sLen(mySeqID)); if (tmpStart<=0) tmpStart=0; hi.standardTraverse(tmpOut, 0, cnt, tmpStart,false); if (!tmpOut.length()){ lookForAlternativeSeqID(mySeqID,hi, wandername.ptr(), cnt, tmpStart, tmpOut); } curIndex += hiWander->cntResults; if (tmpOut.length()) { outPutContent.addString(tmpOut.ptr(), tmpOut.length()); cnt -= (hiWander->cntResults - tmpStart); } } } else { if (recordTypes && strcmp(recordTypes,"seqID")==0){ ionQry1.printf(0, "seq=foreach.seqID('');printLimit=print(seq.1);"); } else if (recordTypes && strcmp(recordTypes,"relation")==0){ ionQry1.printf(0, "seq=foreach.seqID('');relation=find.annot(seqID=seq.1);p=print(relation.seqID,relation.pos,relation.type,relation.id);"); if (searchId && searchType) { //ionQry1.printf(0,"seq=foreach.seqID('');a=search.annot(id=%s,type=%s);relation=find.annot(seqID=seq.1,record=a.record,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId,searchType); ionQry1.printf(0,"seq=foreach.seqID('');a=search.annot(id=%s,type=%s);relation=find.annot(seqID=seq.1,type=a.type,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId,searchType); } else if (searchId) { ionQry1.printf(0,"seq=foreach.seqID('');a=search.annot(id=%s);relation=find.annot(seqID=seq.1,record=a.record,id=a.id);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchId); } else if (searchType) { ionQry1.printf(0,"seq=foreach.seqID('');a=search.annot(type=%s);relation=find.annot(seqID=seq.1,record=a.record,type=a.type);p=print(relation.seqID,relation.pos,relation.type,relation.id);",searchType); } } else { // by default: TYPE ionQry1.printf(0, "type=foreach.type('');printLimit=print(type.1);"); } hi.addIonWander("lookUp", ionQry1.ptr(0)); hi.standardTraverse(outPutContent, 0, cnt, cntStart); } } break; default: break; } outBin(outPutContent.ptr(), outPutContent.length(), 0, true, blobName.ptr(0)); return 1; }
41.397759
239
0.474132
syntheticgio
9c171112ed84d97e7e7cef4373009c84055eb7b0
4,613
hpp
C++
external/boost_1_60_0/qsboost/phoenix/core/expression.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/phoenix/core/expression.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/phoenix/core/expression.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
#if !QSBOOST_PHOENIX_IS_ITERATING #ifndef QSBOOST_PHOENIX_CORE_EXPRESSION_HPP #define QSBOOST_PHOENIX_CORE_EXPRESSION_HPP #include <qsboost/phoenix/core/limits.hpp> #include <qsboost/call_traits.hpp> #include <qsboost/fusion/sequence/intrinsic/at.hpp> #include <qsboost/phoenix/core/as_actor.hpp> #include <qsboost/phoenix/core/detail/expression.hpp> #include <qsboost/phoenix/core/domain.hpp> #include <qsboost/phoenix/support/iterate.hpp> #include <qsboost/preprocessor/comparison/equal.hpp> #include <qsboost/proto/domain.hpp> #include <qsboost/proto/make_expr.hpp> #include <qsboost/proto/transform/pass_through.hpp> #if !defined(QSBOOST_PHOENIX_DONT_USE_PREPROCESSED_FILES) #include <qsboost/phoenix/core/preprocessed/expression.hpp> #else #if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/expression_" QSBOOST_PHOENIX_LIMIT_STR ".hpp") #endif /*============================================================================= Copyright (c) 2005-2010 Joel de Guzman Copyright (c) 2010 Eric Niebler Copyright (c) 2010 Thomas Heller 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) ==============================================================================*/ #if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace qsboost { namespace phoenix { template <typename Expr> struct actor; template < template <typename> class Actor , typename Tag , QSBOOST_PHOENIX_typename_A_void(QSBOOST_PHOENIX_COMPOSITE_LIMIT) , typename Dummy = void> struct expr_ext; template < typename Tag , QSBOOST_PHOENIX_typename_A_void(QSBOOST_PHOENIX_COMPOSITE_LIMIT) , typename Dummy = void > struct expr : expr_ext<actor, Tag, QSBOOST_PHOENIX_A(QSBOOST_PHOENIX_COMPOSITE_LIMIT)> {}; #define M0(Z, N, D) \ QSBOOST_PP_COMMA_IF(N) \ typename proto::detail::uncvref<typename call_traits<QSBOOST_PP_CAT(A, N)>::value_type>::type #define M1(Z, N, D) \ QSBOOST_PP_COMMA_IF(N) typename call_traits<QSBOOST_PP_CAT(A, N)>::param_type QSBOOST_PP_CAT(a, N) #define QSBOOST_PHOENIX_ITERATION_PARAMS \ (3, (1, QSBOOST_PHOENIX_COMPOSITE_LIMIT, \ <qsboost/phoenix/core/expression.hpp>)) \ /**/ #include QSBOOST_PHOENIX_ITERATE() #undef M0 #undef M1 }} #if defined(__WAVE__) && defined(QSBOOST_PHOENIX_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // PHOENIX_DONT_USE_PREPROCESSED_FILES #endif #else template <template <typename> class Actor, typename Tag, QSBOOST_PHOENIX_typename_A> struct expr_ext<Actor, Tag, QSBOOST_PHOENIX_A> : proto::transform<expr_ext<Actor, Tag, QSBOOST_PHOENIX_A>, int> { typedef typename proto::result_of::make_expr< Tag , phoenix_default_domain //proto::basic_default_domain , QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, M0, _) >::type base_type; typedef Actor<base_type> type; typedef typename proto::nary_expr<Tag, QSBOOST_PHOENIX_A>::proto_grammar proto_grammar; static type make(QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, M1, _)) { //?? actor or Actor?? //Actor<base_type> const e = actor<base_type> const e = { proto::make_expr< Tag , phoenix_default_domain // proto::basic_default_domain >(QSBOOST_PHOENIX_a) }; return e; } template<typename Expr, typename State, typename Data> struct impl : proto::pass_through<expr_ext>::template impl<Expr, State, Data> {}; typedef Tag proto_tag; #define QSBOOST_PHOENIX_ENUM_CHILDREN(_, N, __) \ typedef QSBOOST_PP_CAT(A, N) QSBOOST_PP_CAT(proto_child, N); \ /**/ QSBOOST_PP_REPEAT(QSBOOST_PHOENIX_ITERATION, QSBOOST_PHOENIX_ENUM_CHILDREN, _) #undef QSBOOST_PHOENIX_ENUM_CHILDREN }; #endif
34.94697
110
0.620204
wouterboomsma
9c19f5efe66502016882f3258595b5af6719725e
102
hpp
C++
contracts/eosiolib/stdlib.hpp
celes-dev/celesos
b2877d64915bb027b9d86a7a692c6e91f23328b0
[ "MIT" ]
null
null
null
contracts/eosiolib/stdlib.hpp
celes-dev/celesos
b2877d64915bb027b9d86a7a692c6e91f23328b0
[ "MIT" ]
null
null
null
contracts/eosiolib/stdlib.hpp
celes-dev/celesos
b2877d64915bb027b9d86a7a692c6e91f23328b0
[ "MIT" ]
null
null
null
#pragma once #include <initializer_list> #include <iterator> #include <memory> #define DEBUG 1
14.571429
28
0.715686
celes-dev
9c1cfcdcce7dcc27a9170dafc83d0afa6e118049
2,044
cpp
C++
Luogu/P1619.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-09-11T13:17:28.000Z
2020-09-11T13:17:28.000Z
Luogu/P1619.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:36:23.000Z
2020-10-22T13:36:23.000Z
Luogu/P1619.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:33:11.000Z
2020-10-22T13:33:11.000Z
/* Problem: P1619 Time: 2020/10/14 20:35:55 Author: Insouciant21 Status: Accepted */ #include <bits/stdc++.h> using namespace std; const int maxn = int(1e7) * 4 + 1; bitset<maxn> numList; map<int, int> q; int prime[2433655]; int cnt; void prepare() { numList[0] = numList[1] = 1; for (int i = 2; i < maxn; i++) { if (!numList[i]) { prime[++cnt] = i; for (int j = 2; i * j < maxn; j++) numList[i * j] = 1; } } } long long get() { string in; long long num = 0; int cnt = 0; getline(cin, in); for (int i = 0; i < in.length() && num < maxn; i++) { if (in[i] >= '0' && in[i] <= '9') { num = num * 10 + (in[i] - '0'); cnt++; } } if (cnt == 0) exit(0); return num; } int main() { prepare(); ios::sync_with_stdio(false); while (true) { long long num; cout << "Enter the number="; num = get(); long long re = num; cout << endl << "Prime? "; if (num >= maxn) { cout << "No!\n"; cout << "The number is too large!\n" << endl; continue; } else if (!numList[num]) { cout << "Yes!" << endl << endl; continue; } else if (num < 2) { cout << "No!\n" << endl; continue; } else cout << "No!" << endl; for (int i = 1; prime[i] <= num / 2; i++) { while (num >= prime[i]) { if (num % prime[i] == 0) { q[prime[i]]++; num /= prime[i]; } else break; } } if (num != 1) q[num]++; string ans; for (auto iter = q.begin(); iter != q.end(); iter++) ans += to_string(iter->first) + "^" + to_string(iter->second) + "*"; ans.pop_back(); cout << re << "=" << ans << endl << endl; q.clear(); } return 0; }
22.966292
80
0.395793
Insouciant21
9c1e2865c00182de878ee3f78dcc572f223b33ce
33,768
cpp
C++
src/Bindings/LuaState.cpp
p-mcgowan/MCServer
46bdc6c2c621a27c40e11c7af701f3ce50148e01
[ "Apache-2.0" ]
null
null
null
src/Bindings/LuaState.cpp
p-mcgowan/MCServer
46bdc6c2c621a27c40e11c7af701f3ce50148e01
[ "Apache-2.0" ]
null
null
null
src/Bindings/LuaState.cpp
p-mcgowan/MCServer
46bdc6c2c621a27c40e11c7af701f3ce50148e01
[ "Apache-2.0" ]
null
null
null
// LuaState.cpp // Implements the cLuaState class representing the wrapper over lua_State *, provides associated helper functions #include "Globals.h" #include "LuaState.h" extern "C" { #include "lua/src/lualib.h" } #undef TOLUA_TEMPLATE_BIND #include "tolua++/include/tolua++.h" #include "Bindings.h" #include "ManualBindings.h" #include "DeprecatedBindings.h" #include "../Entities/Entity.h" #include "../BlockEntities/BlockEntity.h" // fwd: SQLite/lsqlite3.c extern "C" { int luaopen_lsqlite3(lua_State * L); } // fwd: LuaExpat/lxplib.c: extern "C" { int luaopen_lxp(lua_State * L); } const cLuaState::cRet cLuaState::Return = {}; //////////////////////////////////////////////////////////////////////////////// // cLuaState: cLuaState::cLuaState(const AString & a_SubsystemName) : m_LuaState(nullptr), m_IsOwned(false), m_SubsystemName(a_SubsystemName), m_NumCurrentFunctionArgs(-1) { } cLuaState::cLuaState(lua_State * a_AttachState) : m_LuaState(a_AttachState), m_IsOwned(false), m_SubsystemName("<attached>"), m_NumCurrentFunctionArgs(-1) { } cLuaState::~cLuaState() { if (IsValid()) { if (m_IsOwned) { Close(); } else { Detach(); } } } void cLuaState::Create(void) { if (m_LuaState != nullptr) { LOGWARNING("%s: Trying to create an already-existing LuaState, ignoring.", __FUNCTION__); return; } m_LuaState = lua_open(); luaL_openlibs(m_LuaState); m_IsOwned = true; } void cLuaState::RegisterAPILibs(void) { tolua_AllToLua_open(m_LuaState); ManualBindings::Bind(m_LuaState); DeprecatedBindings::Bind(m_LuaState); luaopen_lsqlite3(m_LuaState); luaopen_lxp(m_LuaState); } void cLuaState::Close(void) { if (m_LuaState == nullptr) { LOGWARNING("%s: Trying to close an invalid LuaState, ignoring.", __FUNCTION__); return; } if (!m_IsOwned) { LOGWARNING( "%s: Detected mis-use, calling Close() on an attached state (0x%p). Detaching instead.", __FUNCTION__, m_LuaState ); Detach(); return; } lua_close(m_LuaState); m_LuaState = nullptr; m_IsOwned = false; } void cLuaState::Attach(lua_State * a_State) { if (m_LuaState != nullptr) { LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, m_LuaState); if (m_IsOwned) { Close(); } else { Detach(); } } m_LuaState = a_State; m_IsOwned = false; } void cLuaState::Detach(void) { if (m_LuaState == nullptr) { return; } if (m_IsOwned) { LOGWARNING( "%s: Detected a mis-use, calling Detach() when the state is owned. Closing the owned state (0x%p).", __FUNCTION__, m_LuaState ); Close(); return; } m_LuaState = nullptr; } void cLuaState::AddPackagePath(const AString & a_PathVariable, const AString & a_Path) { // Get the current path: lua_getfield(m_LuaState, LUA_GLOBALSINDEX, "package"); // Stk: <package> lua_getfield(m_LuaState, -1, a_PathVariable.c_str()); // Stk: <package> <package.path> size_t len = 0; const char * PackagePath = lua_tolstring(m_LuaState, -1, &len); // Append the new path: AString NewPackagePath(PackagePath, len); NewPackagePath.append(LUA_PATHSEP); NewPackagePath.append(a_Path); // Set the new path to the environment: lua_pop(m_LuaState, 1); // Stk: <package> lua_pushlstring(m_LuaState, NewPackagePath.c_str(), NewPackagePath.length()); // Stk: <package> <NewPackagePath> lua_setfield(m_LuaState, -2, a_PathVariable.c_str()); // Stk: <package> lua_pop(m_LuaState, 1); lua_pop(m_LuaState, 1); // Stk: - } bool cLuaState::LoadFile(const AString & a_FileName) { ASSERT(IsValid()); // Load the file: int s = luaL_loadfile(m_LuaState, a_FileName.c_str()); if (ReportErrors(s)) { LOGWARNING("Can't load %s because of an error in file %s", m_SubsystemName.c_str(), a_FileName.c_str()); return false; } // Execute the globals: s = lua_pcall(m_LuaState, 0, LUA_MULTRET, 0); if (ReportErrors(s)) { LOGWARNING("Error in %s in file %s", m_SubsystemName.c_str(), a_FileName.c_str()); return false; } return true; } bool cLuaState::HasFunction(const char * a_FunctionName) { if (!IsValid()) { // This happens if cPlugin::Initialize() fails with an error return false; } lua_getglobal(m_LuaState, a_FunctionName); bool res = (!lua_isnil(m_LuaState, -1) && lua_isfunction(m_LuaState, -1)); lua_pop(m_LuaState, 1); return res; } bool cLuaState::PushFunction(const char * a_FunctionName) { ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack if (!IsValid()) { // This happens if cPlugin::Initialize() fails with an error return false; } // Push the error handler for lua_pcall() lua_pushcfunction(m_LuaState, &ReportFnCallErrors); lua_getglobal(m_LuaState, a_FunctionName); if (!lua_isfunction(m_LuaState, -1)) { LOGWARNING("Error in %s: Could not find function %s()", m_SubsystemName.c_str(), a_FunctionName); lua_pop(m_LuaState, 2); return false; } m_CurrentFunctionName.assign(a_FunctionName); m_NumCurrentFunctionArgs = 0; return true; } bool cLuaState::PushFunction(int a_FnRef) { ASSERT(IsValid()); ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack // Push the error handler for lua_pcall() lua_pushcfunction(m_LuaState, &ReportFnCallErrors); lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, a_FnRef); // same as lua_getref() if (!lua_isfunction(m_LuaState, -1)) { lua_pop(m_LuaState, 2); return false; } m_CurrentFunctionName = "<callback>"; m_NumCurrentFunctionArgs = 0; return true; } bool cLuaState::PushFunction(const cTableRef & a_TableRef) { ASSERT(IsValid()); ASSERT(m_NumCurrentFunctionArgs == -1); // If not, there's already something pushed onto the stack // Push the error handler for lua_pcall() lua_pushcfunction(m_LuaState, &ReportFnCallErrors); lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, a_TableRef.GetTableRef()); // Get the table ref if (!lua_istable(m_LuaState, -1)) { // Not a table, bail out lua_pop(m_LuaState, 2); return false; } lua_getfield(m_LuaState, -1, a_TableRef.GetFnName()); if (lua_isnil(m_LuaState, -1) || !lua_isfunction(m_LuaState, -1)) { // Not a valid function, bail out lua_pop(m_LuaState, 3); return false; } // Pop the table off the stack: lua_remove(m_LuaState, -2); Printf(m_CurrentFunctionName, "<table-callback %s>", a_TableRef.GetFnName()); m_NumCurrentFunctionArgs = 0; return true; } void cLuaState::PushNil(void) { ASSERT(IsValid()); lua_pushnil(m_LuaState); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const AString & a_String) { ASSERT(IsValid()); lua_pushlstring(m_LuaState, a_String.data(), a_String.size()); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const AStringVector & a_Vector) { ASSERT(IsValid()); lua_createtable(m_LuaState, (int)a_Vector.size(), 0); int newTable = lua_gettop(m_LuaState); int index = 1; for (AStringVector::const_iterator itr = a_Vector.begin(), end = a_Vector.end(); itr != end; ++itr, ++index) { tolua_pushstring(m_LuaState, itr->c_str()); lua_rawseti(m_LuaState, newTable, index); } m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const cCraftingGrid * a_Grid) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Grid, "cCraftingGrid"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const cCraftingRecipe * a_Recipe) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Recipe, "cCraftingRecipe"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const char * a_Value) { ASSERT(IsValid()); tolua_pushstring(m_LuaState, a_Value); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const cItems & a_Items) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)&a_Items, "cItems"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const cPlayer * a_Player) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Player, "cPlayer"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const HTTPRequest * a_Request) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Request, "HTTPRequest"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const HTTPTemplateRequest * a_Request) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Request, "HTTPTemplateRequest"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const Vector3d & a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)&a_Vector, "Vector3<double>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const Vector3d * a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Vector, "Vector3<double>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const Vector3i & a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)&a_Vector, "Vector3<int>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(const Vector3i * a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, (void *)a_Vector, "Vector3<int>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(bool a_Value) { ASSERT(IsValid()); tolua_pushboolean(m_LuaState, a_Value ? 1 : 0); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cBlockEntity * a_BlockEntity) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_BlockEntity, (a_BlockEntity == nullptr) ? "cBlockEntity" : a_BlockEntity->GetClass()); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cChunkDesc * a_ChunkDesc) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_ChunkDesc, "cChunkDesc"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cClientHandle * a_Client) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Client, "cClientHandle"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cEntity * a_Entity) { ASSERT(IsValid()); if (a_Entity == nullptr) { lua_pushnil(m_LuaState); } else { switch (a_Entity->GetEntityType()) { case cEntity::etMonster: { // Don't push specific mob types, as those are not exported in the API: tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); break; } case cEntity::etPlayer: { tolua_pushusertype(m_LuaState, a_Entity, "cPlayer"); break; } case cEntity::etPickup: { tolua_pushusertype(m_LuaState, a_Entity, "cPickup"); break; } case cEntity::etTNT: { tolua_pushusertype(m_LuaState, a_Entity, "cTNTEntity"); break; } case cEntity::etProjectile: { tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass()); break; } case cEntity::etFloater: { tolua_pushusertype(m_LuaState, a_Entity, "cFloater"); break; } case cEntity::etEntity: case cEntity::etEnderCrystal: case cEntity::etFallingBlock: case cEntity::etMinecart: case cEntity::etBoat: case cEntity::etExpOrb: case cEntity::etItemFrame: case cEntity::etPainting: { // Push the generic entity class type: tolua_pushusertype(m_LuaState, a_Entity, "cEntity"); } } // switch (EntityType) } m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cHopperEntity * a_Hopper) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Hopper, "cHopperEntity"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cItem * a_Item) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Item, "cItem"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cItems * a_Items) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Items, "cItems"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cLuaServerHandle * a_ServerHandle) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_ServerHandle, "cServerHandle"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cLuaTCPLink * a_TCPLink) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_TCPLink, "cTCPLink"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cLuaUDPEndpoint * a_UDPEndpoint) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_UDPEndpoint, "cUDPEndpoint"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cMonster * a_Monster) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Monster, "cMonster"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cPickup * a_Pickup) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Pickup, "cPickup"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cPlayer * a_Player) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Player, "cPlayer"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cPlugin * a_Plugin) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Plugin, "cPlugin"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cPluginLua * a_Plugin) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Plugin, "cPluginLua"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cProjectileEntity * a_ProjectileEntity) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_ProjectileEntity, "cProjectileEntity"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cTNTEntity * a_TNTEntity) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_TNTEntity, "cTNTEntity"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cWebAdmin * a_WebAdmin) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_WebAdmin, "cWebAdmin"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cWindow * a_Window) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Window, "cWindow"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(cWorld * a_World) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_World, "cWorld"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(double a_Value) { ASSERT(IsValid()); tolua_pushnumber(m_LuaState, a_Value); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(int a_Value) { ASSERT(IsValid()); tolua_pushnumber(m_LuaState, a_Value); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(TakeDamageInfo * a_TDI) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_TDI, "TakeDamageInfo"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(Vector3d * a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Vector, "Vector3<double>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(Vector3i * a_Vector) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Vector, "Vector3<int>"); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(void * a_Ptr) { UNUSED(a_Ptr); ASSERT(IsValid()); // Investigate the cause of this - what is the callstack? // One code path leading here is the OnHookExploding / OnHookExploded with exotic parameters. Need to decide what to do with them LOGWARNING("Lua engine: attempting to push a plain pointer, pushing nil instead."); LOGWARNING("This indicates an unimplemented part of MCS bindings"); LogStackTrace(); lua_pushnil(m_LuaState); m_NumCurrentFunctionArgs += 1; } void cLuaState::Push(std::chrono::milliseconds a_Value) { ASSERT(IsValid()); tolua_pushnumber(m_LuaState, static_cast<lua_Number>(a_Value.count())); m_NumCurrentFunctionArgs += 1; } void cLuaState::PushUserType(void * a_Object, const char * a_Type) { ASSERT(IsValid()); tolua_pushusertype(m_LuaState, a_Object, a_Type); m_NumCurrentFunctionArgs += 1; } void cLuaState::GetStackValue(int a_StackPos, AString & a_Value) { size_t len = 0; const char * data = lua_tolstring(m_LuaState, a_StackPos, &len); if (data != nullptr) { a_Value.assign(data, len); } } void cLuaState::GetStackValue(int a_StackPos, BLOCKTYPE & a_ReturnedVal) { if (lua_isnumber(m_LuaState, a_StackPos)) { a_ReturnedVal = static_cast<BLOCKTYPE>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)); } } void cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal) { a_ReturnedVal = (tolua_toboolean(m_LuaState, a_StackPos, a_ReturnedVal ? 1 : 0) > 0); } void cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref) { a_Ref.RefStack(*this, a_StackPos); } void cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal) { if (lua_isnumber(m_LuaState, a_StackPos)) { a_ReturnedVal = tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal); } } void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal) { if (!lua_isnumber(m_LuaState, a_StackPos)) { return; } a_ReturnedVal = static_cast<eWeather>(Clamp( static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)), static_cast<int>(wSunny), static_cast<int>(wThunderstorm)) ); } void cLuaState::GetStackValue(int a_StackPos, int & a_ReturnedVal) { if (lua_isnumber(m_LuaState, a_StackPos)) { a_ReturnedVal = static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)); } } void cLuaState::GetStackValue(int a_StackPos, pBlockArea & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cBlockArea", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cBlockArea **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cBoundingBox", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cBoundingBox **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pMapManager & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cMapManager", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cMapManager **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pPluginManager & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cPluginManager", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cPluginManager **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pRoot & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cRoot", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cRoot **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pScoreboard & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cScoreboard", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cScoreboard **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cWorld", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cWorld **>(lua_touserdata(m_LuaState, a_StackPos))); } } void cLuaState::GetStackValue(int a_StackPos, pClientHandle & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { a_ReturnedVal = nullptr; return; } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cClientHandle", false, &err)) { a_ReturnedVal = *(reinterpret_cast<cClientHandle **>(lua_touserdata(m_LuaState, a_StackPos))); } } bool cLuaState::CallFunction(int a_NumResults) { ASSERT (m_NumCurrentFunctionArgs >= 0); // A function must be pushed to stack first ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 1)); // The function to call ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 2)); // The error handler // Save the current "stack" state and reset, in case the callback calls another function: AString CurrentFunctionName; std::swap(m_CurrentFunctionName, CurrentFunctionName); int NumArgs = m_NumCurrentFunctionArgs; m_NumCurrentFunctionArgs = -1; // Call the function: int s = lua_pcall(m_LuaState, NumArgs, a_NumResults, -NumArgs - 2); if (s != 0) { // The error has already been printed together with the stacktrace LOGWARNING("Error in %s calling function %s()", m_SubsystemName.c_str(), CurrentFunctionName.c_str()); return false; } // Remove the error handler from the stack: lua_remove(m_LuaState, -a_NumResults - 1); return true; } bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } tolua_Error tolua_err; for (int i = a_StartParam; i <= a_EndParam; i++) { if (tolua_isusertable(m_LuaState, i, a_UserTable, 0, &tolua_err)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } tolua_Error tolua_err; for (int i = a_StartParam; i <= a_EndParam; i++) { if (tolua_isusertype(m_LuaState, i, a_UserType, 0, &tolua_err)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } tolua_Error tolua_err; for (int i = a_StartParam; i <= a_EndParam; i++) { if (tolua_istable(m_LuaState, i, 0, &tolua_err)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } tolua_Error tolua_err; for (int i = a_StartParam; i <= a_EndParam; i++) { if (tolua_isnumber(m_LuaState, i, 0, &tolua_err)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } tolua_Error tolua_err; for (int i = a_StartParam; i <= a_EndParam; i++) { if (tolua_isstring(m_LuaState, i, 0, &tolua_err)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } for (int i = a_StartParam; i <= a_EndParam; i++) { if (lua_isfunction(m_LuaState, i)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam) { ASSERT(IsValid()); if (a_EndParam < 0) { a_EndParam = a_StartParam; } for (int i = a_StartParam; i <= a_EndParam; i++) { if (lua_isfunction(m_LuaState, i) || lua_isnil(m_LuaState, i)) { continue; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param // All params checked ok return true; } bool cLuaState::CheckParamEnd(int a_Param) { tolua_Error tolua_err; if (tolua_isnoobj(m_LuaState, a_Param, &tolua_err)) { return true; } // Not the correct parameter lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } bool cLuaState::IsParamUserType(int a_Param, AString a_UserType) { ASSERT(IsValid()); tolua_Error tolua_err; return tolua_isusertype(m_LuaState, a_Param, a_UserType.c_str(), 0, &tolua_err); } bool cLuaState::IsParamNumber(int a_Param) { ASSERT(IsValid()); tolua_Error tolua_err; return tolua_isnumber(m_LuaState, a_Param, 0, &tolua_err); } bool cLuaState::ReportErrors(int a_Status) { return ReportErrors(m_LuaState, a_Status); } bool cLuaState::ReportErrors(lua_State * a_LuaState, int a_Status) { if (a_Status == 0) { // No error to report return false; } LOGWARNING("LUA: %d - %s", a_Status, lua_tostring(a_LuaState, -1)); lua_pop(a_LuaState, 1); return true; } void cLuaState::LogStackTrace(int a_StartingDepth) { LogStackTrace(m_LuaState, a_StartingDepth); } void cLuaState::LogStackTrace(lua_State * a_LuaState, int a_StartingDepth) { LOGWARNING("Stack trace:"); lua_Debug entry; int depth = a_StartingDepth; while (lua_getstack(a_LuaState, depth, &entry)) { lua_getinfo(a_LuaState, "Sln", &entry); LOGWARNING(" %s(%d): %s", entry.short_src, entry.currentline, entry.name ? entry.name : "(no name)"); depth++; } LOGWARNING("Stack trace end"); } AString cLuaState::GetTypeText(int a_StackPos) { return lua_typename(m_LuaState, lua_type(m_LuaState, a_StackPos)); } int cLuaState::CallFunctionWithForeignParams( const AString & a_FunctionName, cLuaState & a_SrcLuaState, int a_SrcParamStart, int a_SrcParamEnd ) { ASSERT(IsValid()); ASSERT(a_SrcLuaState.IsValid()); // Store the stack position before any changes int OldTop = lua_gettop(m_LuaState); // Push the function to call, including the error handler: if (!PushFunction(a_FunctionName.c_str())) { LOGWARNING("Function '%s' not found", a_FunctionName.c_str()); lua_settop(m_LuaState, OldTop); return -1; } // Copy the function parameters to the target state if (CopyStackFrom(a_SrcLuaState, a_SrcParamStart, a_SrcParamEnd) < 0) { // Something went wrong, fix the stack and exit lua_settop(m_LuaState, OldTop); m_NumCurrentFunctionArgs = -1; m_CurrentFunctionName.clear(); return -1; } // Call the function, with an error handler: int s = lua_pcall(m_LuaState, a_SrcParamEnd - a_SrcParamStart + 1, LUA_MULTRET, OldTop + 1); if (ReportErrors(s)) { LOGWARN("Error while calling function '%s' in '%s'", a_FunctionName.c_str(), m_SubsystemName.c_str()); // Reset the stack: lua_settop(m_LuaState, OldTop); // Reset the internal checking mechanisms: m_NumCurrentFunctionArgs = -1; m_CurrentFunctionName.clear(); // Make Lua think everything is okay and return 0 values, so that plugins continue executing. // The failure is indicated by the zero return values. return 0; } // Reset the internal checking mechanisms: m_NumCurrentFunctionArgs = -1; m_CurrentFunctionName.clear(); // Remove the error handler from the stack: lua_remove(m_LuaState, OldTop + 1); // Return the number of return values: return lua_gettop(m_LuaState) - OldTop; } int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_SrcEnd) { /* // DEBUG: LOGD("Copying stack values from %d to %d", a_SrcStart, a_SrcEnd); a_SrcLuaState.LogStack("Src stack before copying:"); LogStack("Dst stack before copying:"); */ for (int i = a_SrcStart; i <= a_SrcEnd; ++i) { int t = lua_type(a_SrcLuaState, i); switch (t) { case LUA_TNIL: { lua_pushnil(m_LuaState); break; } case LUA_TSTRING: { AString s; a_SrcLuaState.ToString(i, s); Push(s); break; } case LUA_TBOOLEAN: { bool b = (tolua_toboolean(a_SrcLuaState, i, false) != 0); Push(b); break; } case LUA_TNUMBER: { lua_Number d = tolua_tonumber(a_SrcLuaState, i, 0); Push(d); break; } case LUA_TUSERDATA: { // Get the class name: const char * type = nullptr; if (lua_getmetatable(a_SrcLuaState, i) == 0) { LOGWARNING("%s: Unknown class in pos %d, cannot copy.", __FUNCTION__, i); lua_pop(m_LuaState, i - a_SrcStart); return -1; } lua_rawget(a_SrcLuaState, LUA_REGISTRYINDEX); // Stack +1 type = lua_tostring(a_SrcLuaState, -1); lua_pop(a_SrcLuaState, 1); // Stack -1 // Copy the value: void * ud = tolua_touserdata(a_SrcLuaState, i, nullptr); tolua_pushusertype(m_LuaState, ud, type); break; } default: { LOGWARNING("%s: Unsupported value: '%s' at stack position %d. Can only copy numbers, strings, bools and classes!", __FUNCTION__, lua_typename(a_SrcLuaState, t), i ); a_SrcLuaState.LogStack("Stack where copying failed:"); lua_pop(m_LuaState, i - a_SrcStart); return -1; } } } return a_SrcEnd - a_SrcStart + 1; } void cLuaState::ToString(int a_StackPos, AString & a_String) { size_t len; const char * s = lua_tolstring(m_LuaState, a_StackPos, &len); if (s != nullptr) { a_String.assign(s, len); } } void cLuaState::LogStack(const char * a_Header) { LogStack(m_LuaState, a_Header); } void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header) { // Format string consisting only of %s is used to appease the compiler LOG("%s", (a_Header != nullptr) ? a_Header : "Lua C API Stack contents:"); for (int i = lua_gettop(a_LuaState); i > 0; i--) { AString Value; int Type = lua_type(a_LuaState, i); switch (Type) { case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break; case LUA_TLIGHTUSERDATA: Printf(Value, "%p", lua_touserdata(a_LuaState, i)); break; case LUA_TNUMBER: Printf(Value, "%f", (double)lua_tonumber(a_LuaState, i)); break; case LUA_TSTRING: Printf(Value, "%s", lua_tostring(a_LuaState, i)); break; case LUA_TTABLE: Printf(Value, "%p", lua_topointer(a_LuaState, i)); break; default: break; } LOGD(" Idx %d: type %d (%s) %s", i, Type, lua_typename(a_LuaState, Type), Value.c_str()); } // for i - stack idx } int cLuaState::ReportFnCallErrors(lua_State * a_LuaState) { LOGWARNING("LUA: %s", lua_tostring(a_LuaState, -1)); LogStackTrace(a_LuaState, 1); return 1; // We left the error message on the stack as the return value } //////////////////////////////////////////////////////////////////////////////// // cLuaState::cRef: cLuaState::cRef::cRef(void) : m_LuaState(nullptr), m_Ref(LUA_REFNIL) { } cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) : m_LuaState(nullptr), m_Ref(LUA_REFNIL) { RefStack(a_LuaState, a_StackPos); } cLuaState::cRef::cRef(cRef && a_FromRef): m_LuaState(a_FromRef.m_LuaState), m_Ref(a_FromRef.m_Ref) { a_FromRef.m_LuaState = nullptr; a_FromRef.m_Ref = LUA_REFNIL; } cLuaState::cRef::~cRef() { if (m_LuaState != nullptr) { UnRef(); } } void cLuaState::cRef::RefStack(cLuaState & a_LuaState, int a_StackPos) { ASSERT(a_LuaState.IsValid()); if (m_LuaState != nullptr) { UnRef(); } m_LuaState = &a_LuaState; lua_pushvalue(a_LuaState, a_StackPos); // Push a copy of the value at a_StackPos onto the stack m_Ref = luaL_ref(a_LuaState, LUA_REGISTRYINDEX); } void cLuaState::cRef::UnRef(void) { ASSERT(m_LuaState->IsValid()); // The reference should be destroyed before destroying the LuaState if (IsValid()) { luaL_unref(*m_LuaState, LUA_REGISTRYINDEX, m_Ref); } m_LuaState = nullptr; m_Ref = LUA_REFNIL; }
18.801782
130
0.695037
p-mcgowan
9c1fc7ff7e13775acd6cdfa54f5003fece69d869
1,995
cpp
C++
emulator/src/mame/machine/ng_memcard.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/machine/ng_memcard.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/machine/ng_memcard.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Miodrag Milanovic /********************************************************************* ng_memcard.c NEOGEO Memory card functions. *********************************************************************/ #include "emu.h" #include "emuopts.h" #include "ng_memcard.h" // device type definition DEFINE_DEVICE_TYPE(NG_MEMCARD, ng_memcard_device, "ng_memcard", "NeoGeo Memory Card") //------------------------------------------------- // ng_memcard_device - constructor //------------------------------------------------- ng_memcard_device::ng_memcard_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, NG_MEMCARD, tag, owner, clock) , device_image_interface(mconfig, *this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void ng_memcard_device::device_start() { save_item(NAME(m_memcard_data)); } /*------------------------------------------------- memcard_insert - insert an existing memory card with the given index -------------------------------------------------*/ image_init_result ng_memcard_device::call_load() { if(length() != 0x800) return image_init_result::FAIL; fseek(0, SEEK_SET); size_t ret = fread(m_memcard_data, 0x800); if(ret != 0x800) return image_init_result::FAIL; return image_init_result::PASS; } void ng_memcard_device::call_unload() { fseek(0, SEEK_SET); fwrite(m_memcard_data, 0x800); } image_init_result ng_memcard_device::call_create(int format_type, util::option_resolution *format_options) { memset(m_memcard_data, 0, 0x800); size_t ret = fwrite(m_memcard_data, 0x800); if(ret != 0x800) return image_init_result::FAIL; return image_init_result::PASS; } READ8_MEMBER(ng_memcard_device::read) { return m_memcard_data[offset]; } WRITE8_MEMBER(ng_memcard_device::write) { m_memcard_data[offset] = data; }
23.470588
117
0.585464
rjw57
9c2043431ea7af9b93719f4033a39a944e12bf49
12,861
cpp
C++
src/mongo/scripting/v8-3.25_utils.cpp
EshaMaharishi/mongo
7fb52123c945b85866258fdb491c683c5aa54651
[ "Apache-2.0" ]
1
2015-11-06T05:42:37.000Z
2015-11-06T05:42:37.000Z
src/mongo/scripting/v8-3.25_utils.cpp
baiyanghese/mongo
89fcbab94c7103105e8c72f654a5774a066bdb90
[ "Apache-2.0" ]
null
null
null
src/mongo/scripting/v8-3.25_utils.cpp
baiyanghese/mongo
89fcbab94c7103105e8c72f654a5774a066bdb90
[ "Apache-2.0" ]
null
null
null
// v8_utils.cpp /* Copyright 2014 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/scripting/v8-3.25_utils.h" #include <boost/smart_ptr.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/xtime.hpp> #include <iostream> #include <map> #include <sstream> #include <vector> #include "mongo/platform/cstdint.h" #include "mongo/scripting/engine_v8-3.25.h" #include "mongo/scripting/v8-3.25_db.h" #include "mongo/util/mongoutils/str.h" using namespace std; namespace mongo { std::string toSTLString(const v8::Local<v8::Value>& o) { return StringData(V8String(o)).toString(); } /** Get the properties of an object (and its prototype) as a comma-delimited string */ std::string v8ObjectToString(const v8::Local<v8::Object>& o) { v8::Local<v8::Array> properties = o->GetPropertyNames(); v8::String::Utf8Value str(properties); massert(16696 , "error converting js type to Utf8Value", *str); return std::string(*str, str.length()); } std::ostream& operator<<(std::ostream& s, const v8::Local<v8::Value>& o) { v8::String::Utf8Value str(o); s << *str; return s; } std::ostream& operator<<(std::ostream& s, const v8::TryCatch* try_catch) { v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::String::Utf8Value exceptionText(try_catch->Exception()); v8::Local<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { s << *exceptionText << endl; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); cout << *filename << ":" << linenum << " " << *exceptionText << endl; v8::String::Utf8Value sourceline(message->GetSourceLine()); cout << *sourceline << endl; int start = message->GetStartColumn(); for (int i = 0; i < start; i++) cout << " "; int end = message->GetEndColumn(); for (int i = start; i < end; i++) cout << "^"; cout << endl; } return s; } class JSThreadConfig { public: JSThreadConfig(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args, bool newScope = false) : _started(), _done(), _newScope(newScope) { jsassert(args.Length() > 0, "need at least one argument"); jsassert(args[0]->IsFunction(), "first argument must be a function"); // arguments need to be copied into the isolate, go through bson BSONObjBuilder b; for(int i = 0; i < args.Length(); ++i) { scope->v8ToMongoElement(b, "arg" + BSONObjBuilder::numStr(i), args[i]); } _args = b.obj(); } ~JSThreadConfig() { } void start() { jsassert(!_started, "Thread already started"); JSThread jt(*this); _thread.reset(new boost::thread(jt)); _started = true; } void join() { jsassert(_started && !_done, "Thread not running"); _thread->join(); _done = true; } BSONObj returnData() { if (!_done) join(); return _returnData; } private: class JSThread { public: JSThread(JSThreadConfig& config) : _config(config) {} void operator()() { try { _config._scope.reset(static_cast<V8Scope*>(globalScriptEngine->newScope())); v8::Locker v8lock(_config._scope->getIsolate()); v8::Isolate::Scope iscope(_config._scope->getIsolate()); v8::HandleScope handle_scope(_config._scope->getIsolate()); v8::Context::Scope context_scope(_config._scope->getContext()); BSONObj args = _config._args; v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast( v8::Local<v8::Value>( _config._scope->mongoToV8Element(args.firstElement(), true))); int argc = args.nFields() - 1; // TODO SERVER-8016: properly allocate handles on the stack v8::Local<v8::Value> argv[24]; BSONObjIterator it(args); it.next(); for(int i = 0; i < argc && i < 24; ++i) { argv[i] = v8::Local<v8::Value>::New( _config._scope->getIsolate(), _config._scope->mongoToV8Element(*it, true)); it.next(); } v8::TryCatch try_catch; v8::Local<v8::Value> ret = f->Call(_config._scope->getGlobal(), argc, argv); if (ret.IsEmpty() || try_catch.HasCaught()) { string e = _config._scope->v8ExceptionToSTLString(&try_catch); log() << "js thread raised js exception: " << e << endl; ret = v8::Undefined(_config._scope->getIsolate()); // TODO propagate exceptions (or at least the fact that an exception was // thrown) to the calling js on either join() or returnData(). } // ret is translated to BSON to switch isolate BSONObjBuilder b; _config._scope->v8ToMongoElement(b, "ret", ret); _config._returnData = b.obj(); } catch (const DBException& e) { // Keeping behavior the same as for js exceptions. log() << "js thread threw c++ exception: " << e.toString(); _config._returnData = BSON("ret" << BSONUndefined); } catch (const std::exception& e) { log() << "js thread threw c++ exception: " << e.what(); _config._returnData = BSON("ret" << BSONUndefined); } catch (...) { log() << "js thread threw c++ non-exception"; _config._returnData = BSON("ret" << BSONUndefined); } } private: JSThreadConfig& _config; }; bool _started; bool _done; bool _newScope; BSONObj _args; scoped_ptr<boost::thread> _thread; scoped_ptr<V8Scope> _scope; BSONObj _returnData; }; v8::Local<v8::Value> ThreadInit(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Local<v8::Object> it = args.This(); // NOTE I believe the passed JSThreadConfig will never be freed. If this // policy is changed, JSThread may no longer be able to store JSThreadConfig // by reference. it->SetHiddenValue(v8::String::NewFromUtf8(scope->getIsolate(), "_JSThreadConfig"), v8::External::New(scope->getIsolate(), new JSThreadConfig(scope, args))); return v8::Undefined(scope->getIsolate()); } v8::Local<v8::Value> ScopedThreadInit(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Local<v8::Object> it = args.This(); // NOTE I believe the passed JSThreadConfig will never be freed. If this // policy is changed, JSThread may no longer be able to store JSThreadConfig // by reference. it->SetHiddenValue(v8::String::NewFromUtf8(scope->getIsolate(), "_JSThreadConfig"), v8::External::New(scope->getIsolate(), new JSThreadConfig(scope, args, true))); return v8::Undefined(scope->getIsolate()); } JSThreadConfig *thisConfig(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Local<v8::External> c = v8::Local<v8::External>::Cast( args.This()->GetHiddenValue(v8::String::NewFromUtf8(scope->getIsolate(), "_JSThreadConfig"))); JSThreadConfig *config = (JSThreadConfig *)(c->Value()); return config; } v8::Local<v8::Value> ThreadStart(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { thisConfig(scope, args)->start(); return v8::Undefined(scope->getIsolate()); } v8::Local<v8::Value> ThreadJoin(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { thisConfig(scope, args)->join(); return v8::Undefined(scope->getIsolate()); } v8::Local<v8::Value> ThreadReturnData(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { BSONObj data = thisConfig(scope, args)->returnData(); return scope->mongoToV8Element(data.firstElement(), true); } v8::Local<v8::Value> ThreadInject(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { v8::EscapableHandleScope handle_scope(args.GetIsolate()); jsassert(args.Length() == 1, "threadInject takes exactly 1 argument"); jsassert(args[0]->IsObject(), "threadInject needs to be passed a prototype"); v8::Local<v8::Object> o = args[0]->ToObject(); // install method on the Thread object scope->injectV8Function("init", ThreadInit, o); scope->injectV8Function("start", ThreadStart, o); scope->injectV8Function("join", ThreadJoin, o); scope->injectV8Function("returnData", ThreadReturnData, o); return handle_scope.Escape(v8::Local<v8::Value>()); } v8::Local<v8::Value> ScopedThreadInject(V8Scope* scope, const v8::FunctionCallbackInfo<v8::Value>& args) { v8::EscapableHandleScope handle_scope(args.GetIsolate()); jsassert(args.Length() == 1, "threadInject takes exactly 1 argument"); jsassert(args[0]->IsObject(), "threadInject needs to be passed a prototype"); v8::Local<v8::Object> o = args[0]->ToObject(); scope->injectV8Function("init", ScopedThreadInit, o); // inheritance takes care of other member functions return handle_scope.Escape(v8::Local<v8::Value>()); } void installFork(V8Scope* scope, v8::Local<v8::Object> global, v8::Local<v8::Context> context) { scope->injectV8Function("_threadInject", ThreadInject, global); scope->injectV8Function("_scopedThreadInject", ScopedThreadInject, global); } v8::Local<v8::Value> v8AssertionException(const char* errorMessage) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); return isolate->ThrowException( v8::Exception::Error(v8::String::NewFromUtf8(isolate, errorMessage))); } v8::Local<v8::Value> v8AssertionException(const std::string& errorMessage) { return v8AssertionException(errorMessage.c_str()); } }
42.87
97
0.563409
EshaMaharishi
9c22e8f396d8abad1795dd7125eae11f3b2d7fff
23,992
cc
C++
components/invalidation/impl/per_user_topic_subscription_manager.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
components/invalidation/impl/per_user_topic_subscription_manager.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
components/invalidation/impl/per_user_topic_subscription_manager.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/invalidation/impl/per_user_topic_subscription_manager.h" #include <stdint.h> #include <algorithm> #include <cstddef> #include <iterator> #include <memory> #include <string> #include <utility> #include "base/bind.h" #include "base/metrics/histogram_functions.h" #include "base/rand_util.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "components/gcm_driver/instance_id/instance_id_driver.h" #include "components/invalidation/public/identity_provider.h" #include "components/invalidation/public/invalidation_util.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "google_apis/gaia/gaia_constants.h" namespace invalidation { namespace { const char kTypeSubscribedForInvalidationsDeprecated[] = "invalidation.registered_for_invalidation"; const char kTypeSubscribedForInvalidations[] = "invalidation.per_sender_registered_for_invalidation"; const char kActiveRegistrationTokenDeprecated[] = "invalidation.active_registration_token"; const char kActiveRegistrationTokens[] = "invalidation.per_sender_active_registration_tokens"; const char kInvalidationRegistrationScope[] = "https://firebaseperusertopics-pa.googleapis.com"; // Note: Taking |topic| and |private_topic_name| by value (rather than const // ref) because the caller (in practice, SubscriptionEntry) may be destroyed by // the callback. // This is a RepeatingCallback because in case of failure, the request will get // retried, so it might actually run multiple times. using SubscriptionFinishedCallback = base::RepeatingCallback<void( Topic topic, Status code, std::string private_topic_name, PerUserTopicSubscriptionRequest::RequestType type)>; static const net::BackoffEntry::Policy kBackoffPolicy = { // Number of initial errors (in sequence) to ignore before applying // exponential back-off rules. 0, // Initial delay for exponential back-off in ms. 2000, // Factor by which the waiting time will be multiplied. 2, // Fuzzing percentage. ex: 10% will spread requests randomly // between 90%-100% of the calculated time. 0.2, // 20% // Maximum amount of time we are willing to delay our request in ms. 1000 * 3600 * 4, // 4 hours. // Time to keep an entry from being discarded even when it // has no significant state, -1 to never discard. -1, // Don't use initial delay unless the last request was an error. false, }; class PerProjectDictionaryPrefUpdate { public: explicit PerProjectDictionaryPrefUpdate(PrefService* prefs, const std::string& project_id) : update_(prefs, kTypeSubscribedForInvalidations) { per_sender_pref_ = update_->FindDictKey(project_id); if (!per_sender_pref_) { update_->SetDictionary(project_id, std::make_unique<base::DictionaryValue>()); per_sender_pref_ = update_->FindDictKey(project_id); } DCHECK(per_sender_pref_); } base::Value& operator*() { return *per_sender_pref_; } base::Value* operator->() { return per_sender_pref_; } private: DictionaryPrefUpdate update_; base::Value* per_sender_pref_; }; // Added in M76. void MigratePrefs(PrefService* prefs, const std::string& project_id) { if (!prefs->HasPrefPath(kActiveRegistrationTokenDeprecated)) { return; } { DictionaryPrefUpdate token_update(prefs, kActiveRegistrationTokens); token_update->SetString( project_id, prefs->GetString(kActiveRegistrationTokenDeprecated)); } auto* old_subscriptions = prefs->GetDictionary(kTypeSubscribedForInvalidationsDeprecated); { PerProjectDictionaryPrefUpdate update(prefs, project_id); *update = old_subscriptions->Clone(); } prefs->ClearPref(kActiveRegistrationTokenDeprecated); prefs->ClearPref(kTypeSubscribedForInvalidationsDeprecated); } } // namespace // static void PerUserTopicSubscriptionManager::RegisterProfilePrefs( PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kTypeSubscribedForInvalidationsDeprecated); registry->RegisterStringPref(kActiveRegistrationTokenDeprecated, std::string()); registry->RegisterDictionaryPref(kTypeSubscribedForInvalidations); registry->RegisterDictionaryPref(kActiveRegistrationTokens); } // static void PerUserTopicSubscriptionManager::RegisterPrefs( PrefRegistrySimple* registry) { // Same as RegisterProfilePrefs; see comment in the header. RegisterProfilePrefs(registry); } // State of the instance ID token when subscription is requested. // Used by UMA histogram, so entries shouldn't be reordered or removed. enum class PerUserTopicSubscriptionManager::TokenStateOnSubscriptionRequest { kTokenWasEmpty = 0, kTokenUnchanged = 1, kTokenChanged = 2, kTokenCleared = 3, kMaxValue = kTokenCleared, }; struct PerUserTopicSubscriptionManager::SubscriptionEntry { SubscriptionEntry(const Topic& topic, SubscriptionFinishedCallback completion_callback, PerUserTopicSubscriptionRequest::RequestType type, bool topic_is_public = false); // Destruction of this object causes cancellation of the request. ~SubscriptionEntry(); void SubscriptionFinished(const Status& code, const std::string& private_topic_name); // The object for which this is the status. const Topic topic; const bool topic_is_public; SubscriptionFinishedCallback completion_callback; PerUserTopicSubscriptionRequest::RequestType type; base::OneShotTimer request_retry_timer_; net::BackoffEntry request_backoff_; std::unique_ptr<PerUserTopicSubscriptionRequest> request; std::string last_request_access_token; bool has_retried_on_auth_error = false; DISALLOW_COPY_AND_ASSIGN(SubscriptionEntry); }; PerUserTopicSubscriptionManager::SubscriptionEntry::SubscriptionEntry( const Topic& topic, SubscriptionFinishedCallback completion_callback, PerUserTopicSubscriptionRequest::RequestType type, bool topic_is_public) : topic(topic), topic_is_public(topic_is_public), completion_callback(std::move(completion_callback)), type(type), request_backoff_(&kBackoffPolicy) {} PerUserTopicSubscriptionManager::SubscriptionEntry::~SubscriptionEntry() = default; void PerUserTopicSubscriptionManager::SubscriptionEntry::SubscriptionFinished( const Status& code, const std::string& topic_name) { completion_callback.Run(topic, code, topic_name, type); } PerUserTopicSubscriptionManager::PerUserTopicSubscriptionManager( IdentityProvider* identity_provider, PrefService* pref_service, network::mojom::URLLoaderFactory* url_loader_factory, const std::string& project_id, bool migrate_prefs) : pref_service_(pref_service), identity_provider_(identity_provider), url_loader_factory_(url_loader_factory), project_id_(project_id), migrate_prefs_(migrate_prefs), request_access_token_backoff_(&kBackoffPolicy) {} PerUserTopicSubscriptionManager::~PerUserTopicSubscriptionManager() = default; // static std::unique_ptr<PerUserTopicSubscriptionManager> PerUserTopicSubscriptionManager::Create( IdentityProvider* identity_provider, PrefService* pref_service, network::mojom::URLLoaderFactory* url_loader_factory, const std::string& project_id, bool migrate_prefs) { return std::make_unique<PerUserTopicSubscriptionManager>( identity_provider, pref_service, url_loader_factory, project_id, migrate_prefs); } void PerUserTopicSubscriptionManager::Init() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (migrate_prefs_) { MigratePrefs(pref_service_, project_id_); } PerProjectDictionaryPrefUpdate update(pref_service_, project_id_); if (update->DictEmpty()) { return; } std::vector<std::string> keys_to_remove; // Load subscribed topics from prefs. for (const auto& it : update->DictItems()) { Topic topic = it.first; std::string private_topic_name; if (it.second.GetAsString(&private_topic_name) && !private_topic_name.empty()) { topic_to_private_topic_[topic] = private_topic_name; private_topic_to_topic_[private_topic_name] = topic; } else { // Couldn't decode the pref value; remove it. keys_to_remove.push_back(topic); } } // Delete prefs, which weren't decoded successfully. for (const std::string& key : keys_to_remove) { update->RemoveKey(key); } } void PerUserTopicSubscriptionManager::UpdateSubscribedTopics( const Topics& topics, const std::string& instance_id_token) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); instance_id_token_ = instance_id_token; DropAllSavedSubscriptionsOnTokenChange(); for (const auto& topic : topics) { auto it = pending_subscriptions_.find(topic.first); if (it != pending_subscriptions_.end() && it->second->type == PerUserTopicSubscriptionRequest::SUBSCRIBE) { // Do not update SubscriptionEntry if there is no changes, to not loose // backoff timer. continue; } // If the topic isn't subscribed yet, schedule the subscription. if (topic_to_private_topic_.find(topic.first) == topic_to_private_topic_.end()) { // If there was already a pending unsubscription request for this topic, // it'll get destroyed and replaced by the new one. pending_subscriptions_[topic.first] = std::make_unique<SubscriptionEntry>( topic.first, base::BindRepeating( &PerUserTopicSubscriptionManager::SubscriptionFinishedForTopic, base::Unretained(this)), PerUserTopicSubscriptionRequest::SUBSCRIBE, topic.second.is_public); } } // There may be subscribed topics which need to be unsubscribed. // Schedule unsubscription and immediately remove from // |topic_to_private_topic_| and |private_topic_to_topic_|. for (auto it = topic_to_private_topic_.begin(); it != topic_to_private_topic_.end();) { Topic topic = it->first; if (topics.find(topic) == topics.end()) { // Unsubscription request may only replace pending subscription request, // because topic immediately deleted from |topic_to_private_topic_| when // unsubsciption request scheduled. DCHECK(pending_subscriptions_.count(topic) == 0 || pending_subscriptions_[topic]->type == PerUserTopicSubscriptionRequest::SUBSCRIBE); // If there was already a pending request for this topic, it'll get // destroyed and replaced by the new one. pending_subscriptions_[topic] = std::make_unique<SubscriptionEntry>( topic, base::BindRepeating( &PerUserTopicSubscriptionManager::SubscriptionFinishedForTopic, base::Unretained(this)), PerUserTopicSubscriptionRequest::UNSUBSCRIBE); private_topic_to_topic_.erase(it->second); it = topic_to_private_topic_.erase(it); // The decision to unsubscribe from invalidations for |topic| was // made, the preferences should be cleaned up immediately. PerProjectDictionaryPrefUpdate update(pref_service_, project_id_); update->RemoveKey(topic); } else { // Topic is still wanted, nothing to do. ++it; } } // There might be pending subscriptions for topics which are no longer // needed, but they could be in half-completed state (i.e. request already // sent to the server). To reduce subscription leaks they are allowed to // proceed and unsubscription requests will be scheduled by the next // UpdateSubscribedTopics() call after they successfully completed. if (!pending_subscriptions_.empty()) { // Kick off the process of actually processing the (un)subscriptions we just // scheduled. RequestAccessToken(); } else { // No work to be done, emit ENABLED. NotifySubscriptionChannelStateChange(SubscriptionChannelState::ENABLED); } } void PerUserTopicSubscriptionManager::ClearInstanceIDToken() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); instance_id_token_.clear(); DropAllSavedSubscriptionsOnTokenChange(); } void PerUserTopicSubscriptionManager::StartPendingSubscriptions() { for (const auto& pending_subscription : pending_subscriptions_) { StartPendingSubscriptionRequest(pending_subscription.first); } } void PerUserTopicSubscriptionManager::StartPendingSubscriptionRequest( const Topic& topic) { auto it = pending_subscriptions_.find(topic); if (it == pending_subscriptions_.end()) { NOTREACHED() << "StartPendingSubscriptionRequest called on " << topic << " which is not in the registration map"; return; } if (it->second->request_retry_timer_.IsRunning()) { // A retry is already scheduled for this request; nothing to do. return; } if (it->second->request && it->second->last_request_access_token == access_token_) { // The request with the same access token was already sent; nothing to do. return; } PerUserTopicSubscriptionRequest::Builder builder; it->second->last_request_access_token = access_token_; it->second->request = builder.SetInstanceIdToken(instance_id_token_) .SetScope(kInvalidationRegistrationScope) .SetPublicTopicName(topic) .SetAuthenticationHeader(base::StringPrintf( "Bearer %s", access_token_.c_str())) .SetProjectId(project_id_) .SetType(it->second->type) .SetTopicIsPublic(it->second->topic_is_public) .Build(); it->second->request->Start( base::BindOnce(&PerUserTopicSubscriptionManager::SubscriptionEntry:: SubscriptionFinished, base::Unretained(it->second.get())), url_loader_factory_); } void PerUserTopicSubscriptionManager::ActOnSuccessfulSubscription( const Topic& topic, const std::string& private_topic_name, PerUserTopicSubscriptionRequest::RequestType type) { auto it = pending_subscriptions_.find(topic); it->second->request_backoff_.InformOfRequest(true); pending_subscriptions_.erase(it); if (type == PerUserTopicSubscriptionRequest::SUBSCRIBE) { // If this was a subscription, update the prefs now (if it was an // unsubscription, we've already updated the prefs when scheduling the // request). { PerProjectDictionaryPrefUpdate update(pref_service_, project_id_); update->SetKey(topic, base::Value(private_topic_name)); topic_to_private_topic_[topic] = private_topic_name; private_topic_to_topic_[private_topic_name] = topic; } pref_service_->CommitPendingWrite(); } // Check if there are any other subscription (not unsubscription) requests // pending. bool all_subscriptions_completed = true; for (const auto& entry : pending_subscriptions_) { if (entry.second->type == PerUserTopicSubscriptionRequest::SUBSCRIBE) { all_subscriptions_completed = false; } } // Emit ENABLED once all requests have finished. if (all_subscriptions_completed) { NotifySubscriptionChannelStateChange(SubscriptionChannelState::ENABLED); } } void PerUserTopicSubscriptionManager::ScheduleRequestForRepetition( const Topic& topic) { pending_subscriptions_[topic]->request_backoff_.InformOfRequest(false); // Schedule RequestAccessToken() to ensure that request is performed with // fresh access token. There should be no redundant request: the identity // code requests new access token from the network only if the old one // expired; StartPendingSubscriptionRequest() guarantees that no redundant // (un)subscribe requests performed. pending_subscriptions_[topic]->request_retry_timer_.Start( FROM_HERE, pending_subscriptions_[topic]->request_backoff_.GetTimeUntilRelease(), base::BindOnce(&PerUserTopicSubscriptionManager::RequestAccessToken, base::Unretained(this))); } void PerUserTopicSubscriptionManager::SubscriptionFinishedForTopic( Topic topic, Status code, std::string private_topic_name, PerUserTopicSubscriptionRequest::RequestType type) { if (code.IsSuccess()) { ActOnSuccessfulSubscription(topic, private_topic_name, type); return; } auto it = pending_subscriptions_.find(topic); // Reset |request| to make sure it will be rescheduled during the next // attempt. it->second->request.reset(); // If this is the first auth error we've encountered, then most likely the // access token has just expired. Get a new one and retry immediately. if (code.IsAuthFailure() && !it->second->has_retried_on_auth_error) { it->second->has_retried_on_auth_error = true; // Invalidate previous token if it's not already refreshed, otherwise // the identity provider will return the same token again. if (!access_token_.empty() && it->second->last_request_access_token == access_token_) { identity_provider_->InvalidateAccessToken({GaiaConstants::kFCMOAuthScope}, access_token_); access_token_.clear(); } // Re-request access token and try subscription requests again. RequestAccessToken(); return; } // If one of the subscription requests failed (and we need to either observe // backoff before retrying, or won't retry at all), emit SUBSCRIPTION_FAILURE. if (type == PerUserTopicSubscriptionRequest::SUBSCRIBE) { // TODO(crbug.com/1020117): case !code.ShouldRetry() now leads to // inconsistent behavior depending on requests completion order: if any // request was successful after it, we may have no |pending_subscriptions_| // and emit ENABLED; otherwise, if failed request is the last one, state // would be SUBSCRIPTION_FAILURE. NotifySubscriptionChannelStateChange( SubscriptionChannelState::SUBSCRIPTION_FAILURE); } if (!code.ShouldRetry()) { // Note: This is a pretty bad (and "silent") failure case. The subscription // will generally not be retried until the next Chrome restart (or user // sign-out + re-sign-in). DVLOG(1) << "Got a persistent error while trying to subscribe to topic " << topic << ", giving up."; pending_subscriptions_.erase(it); return; } ScheduleRequestForRepetition(topic); } TopicSet PerUserTopicSubscriptionManager::GetSubscribedTopicsForTest() const { TopicSet topics; for (const auto& t : topic_to_private_topic_) topics.insert(t.first); return topics; } void PerUserTopicSubscriptionManager::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void PerUserTopicSubscriptionManager::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void PerUserTopicSubscriptionManager::RequestAccessToken() { // Only one active request at a time. if (access_token_fetcher_ != nullptr) { return; } if (request_access_token_retry_timer_.IsRunning()) { // Previous access token request failed and new request shouldn't be issued // until backoff timer passed. return; } access_token_.clear(); access_token_fetcher_ = identity_provider_->FetchAccessToken( "fcm_invalidation", {GaiaConstants::kFCMOAuthScope}, base::BindOnce( &PerUserTopicSubscriptionManager::OnAccessTokenRequestCompleted, base::Unretained(this))); } void PerUserTopicSubscriptionManager::OnAccessTokenRequestCompleted( GoogleServiceAuthError error, std::string access_token) { access_token_fetcher_.reset(); if (error.state() == GoogleServiceAuthError::NONE) OnAccessTokenRequestSucceeded(access_token); else OnAccessTokenRequestFailed(error); } void PerUserTopicSubscriptionManager::OnAccessTokenRequestSucceeded( const std::string& access_token) { // Reset backoff time after successful response. request_access_token_backoff_.InformOfRequest(/*succeeded=*/true); access_token_ = access_token; StartPendingSubscriptions(); } void PerUserTopicSubscriptionManager::OnAccessTokenRequestFailed( GoogleServiceAuthError error) { DCHECK_NE(error.state(), GoogleServiceAuthError::NONE); NotifySubscriptionChannelStateChange( SubscriptionChannelState::ACCESS_TOKEN_FAILURE); request_access_token_backoff_.InformOfRequest(false); request_access_token_retry_timer_.Start( FROM_HERE, request_access_token_backoff_.GetTimeUntilRelease(), base::BindOnce(&PerUserTopicSubscriptionManager::RequestAccessToken, base::Unretained(this))); } void PerUserTopicSubscriptionManager::DropAllSavedSubscriptionsOnTokenChange() { TokenStateOnSubscriptionRequest outcome = DropAllSavedSubscriptionsOnTokenChangeImpl(); base::UmaHistogramEnumeration( "FCMInvalidations.TokenStateOnRegistrationRequest2", outcome); } PerUserTopicSubscriptionManager::TokenStateOnSubscriptionRequest PerUserTopicSubscriptionManager::DropAllSavedSubscriptionsOnTokenChangeImpl() { { DictionaryPrefUpdate token_update(pref_service_, kActiveRegistrationTokens); std::string previous_token; token_update->GetString(project_id_, &previous_token); if (previous_token == instance_id_token_) { // Note: This includes the case where the token was and still is empty. return TokenStateOnSubscriptionRequest::kTokenUnchanged; } token_update->SetString(project_id_, instance_id_token_); if (previous_token.empty()) { // If we didn't have a registration token before, we shouldn't have had // any subscriptions either, so no need to drop them. return TokenStateOnSubscriptionRequest::kTokenWasEmpty; } } // The token has been cleared or changed. In either case, clear all existing // subscriptions since they won't be valid anymore. (No need to send // unsubscribe requests - if the token was revoked, the server will drop the // subscriptions anyway.) PerProjectDictionaryPrefUpdate update(pref_service_, project_id_); *update = base::Value(base::Value::Type::DICTIONARY); topic_to_private_topic_.clear(); private_topic_to_topic_.clear(); pending_subscriptions_.clear(); return instance_id_token_.empty() ? TokenStateOnSubscriptionRequest::kTokenCleared : TokenStateOnSubscriptionRequest::kTokenChanged; } void PerUserTopicSubscriptionManager::NotifySubscriptionChannelStateChange( SubscriptionChannelState state) { // NOT_STARTED is the default state of the subscription // channel and shouldn't explicitly issued. DCHECK(state != SubscriptionChannelState::NOT_STARTED); if (last_issued_state_ == state) { // Notify only on state change. return; } last_issued_state_ = state; for (auto& observer : observers_) { observer.OnSubscriptionChannelStateChanged(state); } } base::DictionaryValue PerUserTopicSubscriptionManager::CollectDebugData() const { base::DictionaryValue status; for (const auto& topic_to_private_topic : topic_to_private_topic_) { status.SetString(topic_to_private_topic.first, topic_to_private_topic.second); } status.SetString("Instance id token", instance_id_token_); return status; } absl::optional<Topic> PerUserTopicSubscriptionManager::LookupSubscribedPublicTopicByPrivateTopic( const std::string& private_topic) const { auto it = private_topic_to_topic_.find(private_topic); if (it == private_topic_to_topic_.end()) { return absl::nullopt; } return it->second; } } // namespace invalidation
37.546166
80
0.735579
DamieFC
9c2484d3538e728431aad1d2f8712e14ce7f3d27
1,412
hh
C++
src/pks/PK_BDF.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/pks/PK_BDF.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/pks/PK_BDF.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* Process Kernels Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Authors: Konstantin Lipnikov, Ethan Coon This is a purely virtual base class for process kernels which use (implicit) time integrators. */ #ifndef AMANZI_PK_BDF_HH_ #define AMANZI_PK_BDF_HH_ #include "Teuchos_RCP.hpp" #include "BDFFnBase.hh" #include "Key.hh" #include "Operator.hh" #include "OperatorDefs.hh" #include "PDE_HelperDiscretization.hh" #include "primary_variable_field_evaluator.hh" #include "PK.hh" namespace Amanzi { class PK_BDF : virtual public PK, public BDFFnBase<TreeVector> { public: PK_BDF() : PK(), BDFFnBase<TreeVector>() {}; PK_BDF(Teuchos::ParameterList& pk_tree, const Teuchos::RCP<Teuchos::ParameterList>& glist, const Teuchos::RCP<State>& S, const Teuchos::RCP<TreeVector>& soln) : PK(pk_tree, glist, S, soln), BDFFnBase<TreeVector>() {}; // access to operators and PDEs in sub-PKs virtual Teuchos::RCP<Operators::Operator> my_operator(const Operators::OperatorType& type) { return Teuchos::null; } virtual Teuchos::RCP<Operators::PDE_HelperDiscretization> my_pde(const Operators::PDEType& type) { return Teuchos::null; } }; } // namespace Amanzi #endif
24.77193
80
0.723796
fmyuan
9c2567621352e41d8deca17ffe7abb907f09999f
1,674
cpp
C++
app/cpp/mysimplegimp/src/core/transformations/bin_niblack.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
app/cpp/mysimplegimp/src/core/transformations/bin_niblack.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
app/cpp/mysimplegimp/src/core/transformations/bin_niblack.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
#include "bin_niblack.h" #include "transformation.h" BinarizationNiblack::BinarizationNiblack(PNM* img) : Transformation(img) { } BinarizationNiblack::BinarizationNiblack(PNM* img, ImageViewer* iv) : Transformation(img, iv) { } PNM* BinarizationNiblack::transform() { int width = image->width(); int height = image->height(); int r = getParameter("r").toInt(); double a = getParameter("a").toDouble(); double arithmetic_mean = 0; double variance = 0; double standard_deviation = 0; math::matrix<float> window; int T; PNM* newImage = new PNM(width, height, QImage::Format_Mono); for (int x=0; x < width; x++) { for (int y=0; y < height; y++) { // Get current pixel QRgb pixel = image->pixel(x, y); //Get current window window = getWindow(x, y, r, LChannel, RepeatEdge); // Calculate arithmetic mean arithmetic_mean = window.sum() / pow(r, 2); // Calculate standard_deviation for (int i = 0; i < r+1; i++){ for (int j = 0; i < r+1; i++){ variance += pow(window[i][j] - arithmetic_mean, 2); } } variance /= pow(r, 2); standard_deviation = sqrt(variance); // Calculate threshold T T = arithmetic_mean + a * standard_deviation; if(qGray(pixel) > T) { newImage->setPixel(x, y, Qt::color1); } else { newImage->setPixel(x, y, Qt::color0); } } } return newImage; }
23.914286
71
0.517324
jaroslaw-wieczorek
9c2567c22c33c731fc0e23733c13d9a9191fdef5
14,586
cpp
C++
Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/directTidalDissipationAccelerationPartial.h" #include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/directTidalTimeLag.h" #include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h" namespace tudat { namespace acceleration_partials { //! Function to compute partial derivative of direct tidal acceleration due to tide on planet w.r.t. position of satellite Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnPlanetWrtPosition( const Eigen::Vector6d relativeStateOfBodyExertingTide, const Eigen::Vector3d planetAngularVelocityVector, const double currentTidalAccelerationMultiplier, const double timeLag, const bool includeDirectRadialComponent ) { Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 ); Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( ); Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 ); double positionVelocityInnerProduct = relativePosition.dot( relativeVelocity ); double distance = relativePosition.norm( ); double distanceSquared = distance * distance; double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0; return currentTidalAccelerationMultiplier * ( radialComponentMultiplier * ( Eigen::Matrix3d::Identity( ) - 8.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) ) + timeLag * ( -20.0 * positionVelocityInnerProduct * relativePositionUnitVector * relativePositionUnitVector.transpose( ) / distanceSquared + 2.0 / distanceSquared * ( Eigen::Matrix3d::Identity( ) * positionVelocityInnerProduct + relativePosition * relativeVelocity.transpose( ) ) - 8.0 / distance * ( relativePosition.cross( planetAngularVelocityVector) + relativeVelocity ) * relativePositionUnitVector.transpose( ) - linear_algebra::getCrossProductMatrix( planetAngularVelocityVector ) ) ); } //! Function to compute partial derivative of direct tidal acceleration due to tide on planet w.r.t. velocity of satellite/ Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnPlanetWrtVelocity( const Eigen::Vector6d relativeStateOfBodyExertingTide, const double currentTidalAccelerationMultiplier, const double timeLag ) { Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 ); Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( ); return currentTidalAccelerationMultiplier * timeLag * ( 2.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) + Eigen::Matrix3d::Identity( ) ); } //! Function to compute partial derivative of direct tidal acceleration due to tide on satellite w.r.t. position of satellite Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnSatelliteWrtPosition( const Eigen::Vector6d relativeStateOfBodyExertingTide, const double currentTidalAccelerationMultiplier, const double timeLag, const bool includeDirectRadialComponent ) { Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 ); Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( ); Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 ); double positionVelocityInnerProduct = relativePosition.dot( relativeVelocity ); double distance = relativePosition.norm( ); double distanceSquared = distance * distance; double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0; return currentTidalAccelerationMultiplier * ( 2.0 * radialComponentMultiplier * ( Eigen::Matrix3d::Identity( ) - 8.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) ) + timeLag * 3.5 * ( -20.0 * positionVelocityInnerProduct * relativePositionUnitVector * relativePositionUnitVector.transpose( ) / distanceSquared + 2.0 / distanceSquared * ( Eigen::Matrix3d::Identity( ) * positionVelocityInnerProduct + relativePosition * relativeVelocity.transpose( ) ) ) ); } //! Function to compute partial derivative of direct tidal acceleration due to tide on satellite w.r.t. velocity of satellite Eigen::Matrix3d computeDirectTidalAccelerationDueToTideOnSatelliteWrtVelocity( const Eigen::Vector6d relativeStateOfBodyExertingTide, const double currentTidalAccelerationMultiplier, const double timeLag ) { Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 ); Eigen::Vector3d relativePositionUnitVector = relativePosition.normalized( ); return currentTidalAccelerationMultiplier * timeLag * 3.5 * ( 2.0 * relativePositionUnitVector * relativePositionUnitVector.transpose( ) ); } //! Function for setting up and retrieving a function returning a partial w.r.t. a double parameter. std::pair< std::function< void( Eigen::MatrixXd& ) >, int > DirectTidalDissipationAccelerationPartial::getParameterPartialFunction( std::shared_ptr< estimatable_parameters::EstimatableParameter< double > > parameter ) { std::pair< std::function< void( Eigen::MatrixXd& ) >, int > partialFunctionPair; // Check dependencies. if( parameter->getParameterName( ).first == estimatable_parameters::gravitational_parameter ) { // If parameter is gravitational parameter, check and create dependency function . partialFunctionPair = this->getGravitationalParameterPartialFunction( parameter->getParameterName( ) ); } else if( parameter->getParameterName( ).first == estimatable_parameters::direct_dissipation_tidal_time_lag ) { if( ( parameter->getParameterName( ).second.first == acceleratingBody_ ) && tidalAcceleration_->getModelTideOnPlanet( ) ) { std::shared_ptr< estimatable_parameters::DirectTidalTimeLag > timeLagParameter = std::dynamic_pointer_cast< estimatable_parameters::DirectTidalTimeLag >( parameter ); if( timeLagParameter == nullptr ) { throw std::runtime_error( "Error when getting partial of DirectTidalDissipationAcceleration w.r.t. DirectTidalTimeLag, models are inconsistent" ); } else { std::vector< std::string > bodiesCausingDeformation = timeLagParameter->getBodiesCausingDeformation( ); if( bodiesCausingDeformation.size( ) == 0 || ( std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ), acceleratedBody_ ) != bodiesCausingDeformation.end( ) ) ) { partialFunctionPair = std::make_pair( std::bind( &DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag, this, std::placeholders::_1 ), 1 ); } } } else if( ( parameter->getParameterName( ).second.first == acceleratedBody_ ) && !tidalAcceleration_->getModelTideOnPlanet( ) ) { std::shared_ptr< estimatable_parameters::DirectTidalTimeLag > timeLagParameter = std::dynamic_pointer_cast< estimatable_parameters::DirectTidalTimeLag >( parameter ); if( timeLagParameter == nullptr ) { throw std::runtime_error( "Error when getting partial of DirectTidalDissipationAcceleration w.r.t. DirectTidalTimeLag, models are inconsistent" ); } else { std::vector< std::string > bodiesCausingDeformation = timeLagParameter->getBodiesCausingDeformation( ); if( bodiesCausingDeformation.size( ) == 0 || ( std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ), acceleratingBody_ ) != bodiesCausingDeformation.end( ) ) ) { partialFunctionPair = std::make_pair( std::bind( &DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag, this, std::placeholders::_1 ), 1 ); } } } } else { partialFunctionPair = std::make_pair( std::function< void( Eigen::MatrixXd& ) >( ), 0 ); } return partialFunctionPair; } void DirectTidalDissipationAccelerationPartial::update( const double currentTime ) { tidalAcceleration_->updateMembers( currentTime ); if( !( currentTime_ == currentTime ) ) { currentRelativeBodyState_ = tidalAcceleration_->getCurrentRelativeState( ); if( tidalAcceleration_->getModelTideOnPlanet( ) ) { currentPartialWrtPosition_ = computeDirectTidalAccelerationDueToTideOnPlanetWrtPosition( currentRelativeBodyState_, tidalAcceleration_->getCurrentAngularVelocityVectorOfBodyUndergoingTide( ), tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), tidalAcceleration_->getTimeLag( ), tidalAcceleration_->getIncludeDirectRadialComponent( ) ); currentPartialWrtVelocity_ = computeDirectTidalAccelerationDueToTideOnPlanetWrtVelocity( currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), tidalAcceleration_->getTimeLag( ) ); } else { currentPartialWrtPosition_ = computeDirectTidalAccelerationDueToTideOnSatelliteWrtPosition( currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), tidalAcceleration_->getTimeLag( ), tidalAcceleration_->getIncludeDirectRadialComponent( ) ); currentPartialWrtVelocity_ = computeDirectTidalAccelerationDueToTideOnSatelliteWrtVelocity( currentRelativeBodyState_, tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), tidalAcceleration_->getTimeLag( ) ); } currentTime_ = currentTime; } } //! Function to create a function returning the current partial w.r.t. a gravitational parameter. std::pair< std::function< void( Eigen::MatrixXd& ) >, int > DirectTidalDissipationAccelerationPartial::getGravitationalParameterPartialFunction( const estimatable_parameters::EstimatebleParameterIdentifier& parameterId ) { std::function< void( Eigen::MatrixXd& ) > partialFunction; int numberOfColumns = 0; // Check if parameter is gravitational parameter. if( parameterId.first == estimatable_parameters::gravitational_parameter ) { // Check if parameter body is central body. if( parameterId.second.first == acceleratingBody_ ) { if( !tidalAcceleration_->getModelTideOnPlanet( ) ) { partialFunction = std::bind( &DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfPlanet, this, std::placeholders::_1 ); numberOfColumns = 1; } } // Check if parameter body is accelerated body, and if the mutual acceleration is used. if( parameterId.second.first == acceleratedBody_ ) { partialFunction = std::bind( &DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfSatellite, this, std::placeholders::_1 ); numberOfColumns = 1; } } return std::make_pair( partialFunction, numberOfColumns ); } //! Function to calculate central gravity partial w.r.t. central body gravitational parameter void DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfPlanet( Eigen::MatrixXd& gravitationalParameterPartial ) { gravitationalParameterPartial.block( 0, 0, 3, 1 ) = tidalAcceleration_->getAcceleration( ) * 2.0 / tidalAcceleration_->getGravitationalParameterFunctionOfBodyExertingTide( )( ); } //! Function to compute derivative w.r.t. gravitational parameter of satellite void DirectTidalDissipationAccelerationPartial::wrtGravitationalParameterOfSatellite( Eigen::MatrixXd& gravitationalParameterPartial ) { gravitationalParameterPartial.block( 0, 0, 3, 1 ) = -tidalAcceleration_->getAcceleration( ) / tidalAcceleration_->getGravitationalParameterFunctionOfBodyUndergoingTide( )( ); if( tidalAcceleration_->getModelTideOnPlanet( ) ) { gravitationalParameterPartial *= -1.0; } } //! Function to compute derivative w.r.t. tidal time lag parameter. void DirectTidalDissipationAccelerationPartial::wrtTidalTimeLag( Eigen::MatrixXd& timeLagPartial ) { if( !tidalAcceleration_->getModelTideOnPlanet( ) ) { timeLagPartial = gravitation::computeDirectTidalAccelerationDueToTideOnSatellite( tidalAcceleration_->getCurrentRelativeState( ), tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), 1.0, false ); } else { timeLagPartial = gravitation::computeDirectTidalAccelerationDueToTideOnPlanet( tidalAcceleration_->getCurrentRelativeState( ), tidalAcceleration_->getCurrentAngularVelocityVectorOfBodyUndergoingTide( ), tidalAcceleration_->getCurrentTidalAccelerationMultiplier( ), 1.0, false ); } } } }
53.04
163
0.67222
sebranchett
9c2633e8271987c1198734d2c376e5426524abb9
1,648
cpp
C++
code/texturanalysis.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
8
2020-02-21T22:21:01.000Z
2022-02-16T05:30:54.000Z
code/texturanalysis.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
null
null
null
code/texturanalysis.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
3
2020-08-05T05:42:35.000Z
2021-08-30T05:39:51.000Z
#define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> #include <vector> #include <string> #include <algorithm> #include <unordered_set> #include <ctype.h> #include <queue> #include <map> #include <set> #include <stack> #include <unordered_map> #define EPSILON 0.00001 typedef long long ll; typedef unsigned long long ull; typedef long double ld; using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll i, j, k; ll whiteSpace; ll stepper; ll caseNum = 1; string texture; bool even; while(cin >> texture && texture != "END") { even = true; if(texture.size() == 1) { cout << caseNum << " EVEN\n"; caseNum++; continue; } else { stepper = 1; while(texture[stepper] != '*') { stepper++; } whiteSpace = stepper; } for(i = 0; i < texture.size(); i++) { if(whiteSpace != 0 && i % whiteSpace != 0) { if (texture[i] != '.') { even = false; } } else { if (texture[i] != '*') { even = false; } } } cout << caseNum << " "; if(even) { cout << "EVEN\n"; } else { cout << "NOT EVEN\n"; } caseNum++; } return 0; }
18.942529
54
0.418689
matthewReff
9c26a39d5606a2d8fc0213a969ff68daa4b1dacf
2,121
hpp
C++
cppcache/src/TimeoutTimer.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
cppcache/src/TimeoutTimer.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
cppcache/src/TimeoutTimer.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef GEODE_TIMEOUTTIMER_H_ #define GEODE_TIMEOUTTIMER_H_ /* * 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 <geode/internal/geode_globals.hpp> #include <ace/Condition_Recursive_Thread_Mutex.h> #include <ace/Condition_T.h> #include <ace/Guard_T.h> #include <ace/Time_Value.h> #include <ace/OS_NS_sys_time.h> namespace apache { namespace geode { namespace client { class APACHE_GEODE_EXPORT TimeoutTimer { private: ACE_Recursive_Thread_Mutex m_mutex; ACE_Condition<ACE_Recursive_Thread_Mutex> m_cond; volatile bool m_reset; public: TimeoutTimer() : m_mutex(), m_cond(m_mutex), m_reset(false) {} /** * Return only after seconds have passed without receiving a reset. */ void untilTimeout(int seconds) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); ACE_OS::last_error(0); while ((ACE_OS::last_error() != ETIME) || m_reset) { m_reset = false; ACE_Time_Value stopTime = ACE_OS::gettimeofday(); stopTime += seconds; ACE_OS::last_error(0); m_cond.wait(&stopTime); } } /** * Reset the timeout interval so that it restarts now. */ void reset() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); // m_cond.signal(); m_reset = true; } }; } // namespace client } // namespace geode } // namespace apache #endif // GEODE_TIMEOUTTIMER_H_
28.662162
75
0.726073
vaijira
9c276dc867139cf2fa6a052bfcf72980c1b04219
6,537
cpp
C++
test/testallkernels/testscankernel.cpp
pc2/fbench
0e21704f9e4dd3440b03ee913e058ee3916086f2
[ "MIT" ]
null
null
null
test/testallkernels/testscankernel.cpp
pc2/fbench
0e21704f9e4dd3440b03ee913e058ee3916086f2
[ "MIT" ]
null
null
null
test/testallkernels/testscankernel.cpp
pc2/fbench
0e21704f9e4dd3440b03ee913e058ee3916086f2
[ "MIT" ]
2
2020-10-20T14:51:31.000Z
2020-10-20T15:25:41.000Z
/* Author: Akhtar, Junaid E-mail: junaida@mail.uni-paderborn.de Date: 2020/05/30 */ #include <gtest/gtest.h> #include <time.h> #include "../../src/common/benchmarkoptionsparser.h" #include "../../src/common/utility.h" #include "../common/basetest.h" using namespace std; using ::testing::Values; using ::testing::WithParamInterface; extern BenchmarkOptions t_options; extern cl_int t_clErr; extern cl_command_queue t_queue; extern cl_context t_ctx; extern cl_device_id t_dev; // scan specific Implementation from BaseFixtureTest class ScanKernelsTestFixture : public BaseTestFixture { }; struct ScanTestItem { int size; }; // Parameterized Tests implementation of Unit Testing Scan with Test Fixtures class ScanKernelsTestFixtureWithParam : public ScanKernelsTestFixture, public WithParamInterface<ScanTestItem> { }; // Value Parameterized Test with Test Fixture for executing Scan Unit Test TEST_P(ScanKernelsTestFixtureWithParam, TestScan) { auto param = GetParam(); // Check if Device Initilization was Successful or not ASSERT_EQ(CL_SUCCESS, t_clErr); int errNum = 0; auto iter = t_options.appsToRun.find(scan); bool status = iter == t_options.appsToRun.end(); if (status) { iter = t_options.appsToRun.find(all); ASSERT_TRUE(status == 1) << "Missing Benchmark Options"; } ApplicationOptions appOptions = iter->second; cl_program fbenchProgram = createProgramFromBitstream(t_ctx, appOptions.bitstreamFile, t_dev); { cl_kernel scankernel = clCreateKernel(fbenchProgram, "scan", &errNum); ASSERT_FALSE(scankernel == 0); ASSERT_EQ(CL_SUCCESS, errNum); // To-do code start int size = param.size; // Convert to MB size = (size * 1024 * 1024) / sizeof(float); // Create input data on CPU unsigned int bytes = size * sizeof(float); float *reference = new float[size]; // Allocate pinned host memory for input data (h_idata) cl_mem h_i = clCreateBuffer(t_ctx, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, bytes, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); float *h_idata = (float *)clEnqueueMapBuffer(t_queue, h_i, true, CL_MAP_READ | CL_MAP_WRITE, 0, bytes, 0, NULL, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); // Allocate pinned host memory for output data (h_odata) cl_mem h_o = clCreateBuffer(t_ctx, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, bytes, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); float *h_odata = (float *)clEnqueueMapBuffer(t_queue, h_o, true, CL_MAP_READ | CL_MAP_WRITE, 0, bytes, 0, NULL, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); // Initialize host memory for (int i = 0; i < size; i++) { h_idata[i] = i % 3; //Fill with some pattern h_odata[i] = -1; } // Allocate device memory for input array cl_mem d_idata = clCreateBuffer(t_ctx, CL_MEM_READ_WRITE, bytes, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); // Allocate device memory for output array cl_mem d_odata = clCreateBuffer(t_ctx, CL_MEM_READ_WRITE, bytes, NULL, &errNum); ASSERT_EQ(CL_SUCCESS, errNum); // SINGLE WORK ITEM KERNELS // Number of local work items per group const size_t local_wsize = 1; // Number of global work items const size_t global_wsize = 1; // Set the kernel arguments errNum = clSetKernelArg(scankernel, 0, sizeof(cl_mem), (void *)&d_idata); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clSetKernelArg(scankernel, 1, sizeof(cl_mem), (void *)&d_odata); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clSetKernelArg(scankernel, 2, sizeof(cl_int), (void *)&size); ASSERT_EQ(CL_SUCCESS, errNum); cl_event evTransfer = NULL; errNum = clEnqueueWriteBuffer(t_queue, d_idata, true, 0, bytes, h_idata, 0, NULL, &evTransfer); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clFinish(t_queue); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clEnqueueNDRangeKernel(t_queue, scankernel, 1, NULL, &global_wsize, &local_wsize, 0, NULL, NULL); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clFinish(t_queue); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clEnqueueReadBuffer(t_queue, d_odata, true, 0, bytes, h_odata, 0, NULL, &evTransfer); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clFinish(t_queue); ASSERT_EQ(CL_SUCCESS, errNum); float last = 0.0f; for (unsigned int i = 0; i < size; ++i) { reference[i] = h_idata[i] + last; last = reference[i]; } for (unsigned int i = 0; i < size; ++i) { ASSERT_FLOAT_EQ(reference[i], h_odata[i]); } // Clean up device memory errNum = clReleaseMemObject(d_idata); ASSERT_EQ(CL_SUCCESS, errNum); errNum = clReleaseMemObject(d_odata); ASSERT_EQ(CL_SUCCESS, errNum); // Clean up other host memory delete[] reference; // To-do code end errNum = clReleaseKernel(scankernel); ASSERT_EQ(CL_SUCCESS, errNum); } errNum = clReleaseProgram(fbenchProgram); ASSERT_EQ(CL_SUCCESS, errNum); }; // ScanKernelsWithParameters // In order to run value-parameterized tests, we need to instantiate them, // or bind them to a list of values which will be used as test parameters. // We can instantiate them in a different translation module, or even // instantiate them several times. // Here to pass test names after fetching from arguments // Here, we instantiate our tests with a list of two PrimeTable object factory functions INSTANTIATE_TEST_CASE_P(TestBaseInstantiation, ScanKernelsTestFixtureWithParam, Values( ScanTestItem{1}, ScanTestItem{2}, ScanTestItem{4}, ScanTestItem{8}, ScanTestItem{16}, ScanTestItem{32}, ScanTestItem{64}));
34.046875
115
0.609454
pc2
9c2b25a05445cbd4fb817c64503b949df9959a2e
17,176
cpp
C++
protoc_plugin/main.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
26
2019-06-09T02:00:00.000Z
2022-02-16T08:08:58.000Z
protoc_plugin/main.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
13
2019-05-28T02:05:23.000Z
2019-07-10T20:21:12.000Z
protoc_plugin/main.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
4
2019-06-08T11:30:38.000Z
2020-05-17T04:45:37.000Z
#include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> #include <filesystem> #include <functional> using google::protobuf::Descriptor; using google::protobuf::FileDescriptor; using google::protobuf::MethodDescriptor; using google::protobuf::ServiceDescriptor; using google::protobuf::compiler::CodeGenerator; using google::protobuf::compiler::GeneratorContext; using google::protobuf::io::CodedOutputStream; using google::protobuf::io::ZeroCopyOutputStream; using std::filesystem::path; const char* header_extension = ".egrpc.pb.h"; const char* source_extension = ".egrpc.pb.cc"; const char* pb_header_extension = ".pb.h"; enum class Method_mode { UNARY, CLIENT_STREAM, SERVER_STREAM, BIDIR_STREAM }; Method_mode get_mode(const MethodDescriptor* method) { bool c_stream = method->client_streaming(); bool s_stream = method->server_streaming(); if(c_stream && s_stream) { return Method_mode::BIDIR_STREAM; } if(c_stream) { return Method_mode::CLIENT_STREAM; } if(s_stream) { return Method_mode::SERVER_STREAM; } return Method_mode::UNARY; } // Obtain the fully-qualified type name for a given descriptor. std::string class_name(const Descriptor* desc) { auto outer = desc; while (outer->containing_type()) { outer = outer->containing_type(); } auto outer_name = outer->full_name(); auto inner_name = desc->full_name().substr(outer_name.size()); std::ostringstream result; result << "::"; for (auto& c : outer_name) { if (c == '.') { result << "::"; } else { result << c; } } for (auto& c : inner_name) { if (c == '.') { result << "_"; } else { result << c; } } return result.str(); } std::string header_guard(std::string_view file_name) { std::ostringstream result; for (auto c : file_name) { if (std::isalnum(c)) { result << c; } else { result << std::hex << int(c); } } return result.str(); } std::vector<std::string> tokenize(const std::string& str, char c) { std::vector<std::string> result; if (!str.empty()) { auto current = 0; auto next = str.find(c); while (next != std::string::npos) { result.push_back(str.substr(current, next-current)); current = next + 1; next = str.find(c, current); } if (current != next) { result.push_back(str.substr(current, next)); } } return result; } std::vector<std::string> package_parts(const FileDescriptor* file) { return tokenize(file->package(), '.'); } void generate_service_header(const ServiceDescriptor* service, std::ostream& dst) { auto name = service->name(); auto full_name = service->full_name(); auto method_name_cste = [&](auto method) { return std::string("k") + name + "_" + method->name() + "_name"; }; dst << "class " << service->name() << " {\n" << "public:\n" << " using service_type = " << name << ";\n\n" << " virtual ~" << name << "() {}\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); dst << " static const char * " << method_name_cste(method) << ";\n"; } dst << "\n"; // Print out the compile-time helper functions for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); auto input = method->input_type(); auto output = method->output_type(); switch(get_mode(method)) { case Method_mode::UNARY: dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ") = 0;\n"; break; case Method_mode::CLIENT_STREAM: dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> " << method->name() << "(::easy_grpc::Stream_future<" << class_name(input) << ">) = 0;\n"; break; case Method_mode::SERVER_STREAM: dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ") = 0;\n"; break; case Method_mode::BIDIR_STREAM: dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(::easy_grpc::Stream_future<" << class_name(input) << ">) = 0;\n"; break; } } dst << "\n"; dst << " class Stub_interface {\n" << " public:\n" << " virtual ~Stub_interface() {}\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); auto input = method->input_type(); auto output = method->output_type(); switch(get_mode(method)) { case Method_mode::UNARY: dst << " virtual ::easy_grpc::Future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ", ::easy_grpc::client::Call_options={}) = 0;\n"; break; case Method_mode::CLIENT_STREAM: dst << " virtual std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> " << method->name() << "(::easy_grpc::client::Call_options={}) = 0;\n"; break; case Method_mode::SERVER_STREAM: dst << " virtual ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ", ::easy_grpc::client::Call_options={}) = 0;\n"; break; case Method_mode::BIDIR_STREAM: dst << " virtual std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> " << method->name() << "(::easy_grpc::client::Call_options={}) = 0;\n"; break; } } dst << " };\n\n"; dst << " class Stub final : public Stub_interface {\n" << " public:\n" << " Stub(::easy_grpc::client::Channel*, " "::easy_grpc::Completion_queue* = nullptr);\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); auto input = method->input_type(); auto output = method->output_type(); switch(get_mode(method)) { case Method_mode::UNARY: dst << " ::easy_grpc::Future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ", ::easy_grpc::client::Call_options={}) override;\n"; break; case Method_mode::CLIENT_STREAM: dst << " std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> " << method->name() << "(::easy_grpc::client::Call_options={}) override;\n"; break; case Method_mode::SERVER_STREAM: dst << " ::easy_grpc::Stream_future<" << class_name(output) << "> " << method->name() << "(" << class_name(input) << ", ::easy_grpc::client::Call_options={}) override;\n"; break; case Method_mode::BIDIR_STREAM: dst << " std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> " << method->name() << "(::easy_grpc::client::Call_options={}) override;\n"; break; } } dst << "\n" << " private:\n" << " ::easy_grpc::client::Channel* channel_;\n" << " ::easy_grpc::Completion_queue* default_queue_;\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); dst << " void* " << method->name() << "_tag_;\n"; } dst << " };\n\n"; dst << " template<typename ImplT>\n" << " static ::easy_grpc::server::Service_config get_config(ImplT& impl) {\n" << " ::easy_grpc::server::Service_config result(\""<< full_name <<"\");\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); auto input = method->input_type(); auto output = method->output_type(); switch(get_mode(method)) { case Method_mode::UNARY: dst << " result.add_method(" << method_name_cste(method) << ", [&impl](" << class_name(input) << " req){return impl." << method->name() << "(std::move(req));});\n"; break; case Method_mode::CLIENT_STREAM: dst << " result.add_method(" << method_name_cste(method) << ", [&impl](::easy_grpc::Stream_future<" << class_name(input) << "> req){return impl." << method->name() << "(std::move(req));});\n"; break; case Method_mode::SERVER_STREAM: dst << " result.add_method(" << method_name_cste(method) << ", [&impl](" << class_name(input) << " req){return impl." << method->name() << "(std::move(req));});\n"; break; case Method_mode::BIDIR_STREAM: dst << " result.add_method(" << method_name_cste(method) << ", [&impl](::easy_grpc::Stream_future<" << class_name(input) << "> req){return impl." << method->name() << "(std::move(req));});\n"; break; } } dst << "\n return result;\n"; dst << " }\n"; dst << "};\n\n"; } void generate_service_source(const ServiceDescriptor* service, std::ostream& dst) { auto name = service->name(); dst << "// ********** " << name << " ********** //\n\n"; auto method_name_cste = [&](auto method) { return std::string("k") + name + "_" + method->name() + "_name"; }; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); dst << "const char* " << name << "::" << method_name_cste(method) << " = \"/" << service->file()->package() << "." << name << "/" << method->name() << "\";\n"; } dst << "\n"; dst << name << "::Stub::Stub(::easy_grpc::client::Channel* c, " "::easy_grpc::Completion_queue* default_queue)\n" << " : channel_(c), default_queue_(default_queue ? default_queue : " "c->default_queue())"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); dst << "\n , " << method->name() << "_tag_(c->register_method(" << method_name_cste(method) << "))"; } dst << " {}\n\n"; for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); auto input = method->input_type(); auto output = method->output_type(); dst << "// " << method->name() << "\n"; switch(get_mode(method)) { case Method_mode::UNARY: dst << "::easy_grpc::Future<" << class_name(output) << "> " << name << "::Stub::" << method->name() << "(" << class_name(input) << " req, ::easy_grpc::client::Call_options options) {\n" << " if(!options.completion_queue) { options.completion_queue = " "default_queue_; }\n" << " return ::easy_grpc::client::start_unary_call<" << class_name(output) << ">(channel_, " << method->name() << "_tag_, std::move(req), std::move(options));\n" << "}\n\n"; break; case Method_mode::CLIENT_STREAM: dst << "std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Future<" << class_name(output) << ">> " << name << "::Stub::" << method->name() << "(::easy_grpc::client::Call_options options) {\n"; dst << " if(!options.completion_queue) { options.completion_queue = " "default_queue_; }\n" << " return ::easy_grpc::client::start_client_streaming_call<" << class_name(output) << ", " << class_name(input) << ">(channel_, " << method->name() << "_tag_, std::move(options));\n" << "}\n\n"; break; case Method_mode::SERVER_STREAM: dst << "::easy_grpc::Stream_future<" << class_name(output) << "> " << name << "::Stub::" << method->name() << "(" << class_name(input) << " req, ::easy_grpc::client::Call_options options) {\n" << " if(!options.completion_queue) { options.completion_queue = " "default_queue_; }\n" << " return ::easy_grpc::client::start_server_streaming_call<" << class_name(output) << ">(channel_, " << method->name() << "_tag_, std::move(req), std::move(options));\n" << "}\n\n"; break; case Method_mode::BIDIR_STREAM: dst << "std::tuple<::easy_grpc::Stream_promise<"<< class_name(input)<<">, ::easy_grpc::Stream_future<" << class_name(output) << ">> " << name << "::Stub::" << method->name() << "(::easy_grpc::client::Call_options options) {\n" << " if(!options.completion_queue) { options.completion_queue = " "default_queue_; }\n" << " return ::easy_grpc::client::start_bidir_streaming_call<" << class_name(output) << ", " << class_name(input) << ">(channel_, " << method->name() << "_tag_, std::move(options));\n" << "}\n\n"; break; } } } std::string generate_header(const FileDescriptor* file) { std::ostringstream result; auto file_name = path(file->name()).stem().string(); // Prologue result << "// This code was generated by the easy_grpc protoc plugin.\n" << "#ifndef EASY_GRPC_" << header_guard(file_name) << "_INCLUDED_H\n" << "#define EASY_GRPC_" << header_guard(file_name) << "_INCLUDED_H\n" << "\n"; // Headers result << "#include \"" << file_name << pb_header_extension << "\"" << "\n\n"; result << "#include \"easy_grpc/ext_protobuf/gen_support.h\"" << "\n\n"; result << "#include <memory>\n\n"; // namespace auto package = package_parts(file); if (!package.empty()) { for (const auto& p : package) { result << "namespace " << p << " {\n"; } result << "\n"; } // Services for (int i = 0; i < file->service_count(); ++i) { generate_service_header(file->service(i), result); } // Epilogue if (!package.empty()) { for (const auto& p : package) { result << "} // namespace" << p << "\n"; } result << "\n"; } result << "#endif\n"; return result.str(); } std::string generate_source(const FileDescriptor* file) { std::ostringstream result; auto file_name = path(file->name()).stem().string(); // Prologue result << "// This code was generated by the easy_grpc protoc plugin.\n\n"; // Headers result << "#include \"" << file_name << header_extension << "\"" << "\n\n"; // namespace auto package = package_parts(file); if (!package.empty()) { for (const auto& p : package) { result << "namespace " << p << " {\n"; } result << "\n"; } // Services for (int i = 0; i < file->service_count(); ++i) { generate_service_source(file->service(i), result); } // Epilogue if (!package.empty()) { for (const auto& p : package) { result << "} // namespace" << p << "\n"; } result << "\n"; } return result.str(); } class Generator : public CodeGenerator { public: // Generates code for the given proto file, generating one or more files in // the given output directory. // // A parameter to be passed to the generator can be specified on the command // line. This is intended to be used to pass generator specific parameters. // It is empty if no parameter was given. ParseGeneratorParameter (below), // can be used to accept multiple parameters within the single parameter // command line flag. // // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. bool Generate(const FileDescriptor* file, const std::string& parameter, GeneratorContext* context, std::string* error) const override { try { auto file_name = path(file->name()).stem().string(); { auto header_data = generate_header(file); std::unique_ptr<ZeroCopyOutputStream> header_dst{ context->Open(file_name + header_extension)}; CodedOutputStream header_out(header_dst.get()); header_out.WriteRaw(header_data.data(), header_data.size()); } { auto src_data = generate_source(file); std::unique_ptr<ZeroCopyOutputStream> src_dst{ context->Open(file_name + source_extension)}; CodedOutputStream src_out(src_dst.get()); src_out.WriteRaw(src_data.data(), src_data.size()); } } catch (std::exception& e) { *error = e.what(); return false; } return true; } }; int main(int argc, char* argv[]) { Generator generator; ::google::protobuf::compiler::PluginMain(argc, argv, &generator); }
34.629032
174
0.55694
FrancoisChabot
9c2ba419c96951cf61cbd815930d9c9460333a1c
6,838
cpp
C++
src/common/meta/GflagsManager.cpp
wenhaocs/nebula
326b856cdf44fcaf67d3883073dc9412a9e3eebd
[ "Apache-2.0" ]
null
null
null
src/common/meta/GflagsManager.cpp
wenhaocs/nebula
326b856cdf44fcaf67d3883073dc9412a9e3eebd
[ "Apache-2.0" ]
null
null
null
src/common/meta/GflagsManager.cpp
wenhaocs/nebula
326b856cdf44fcaf67d3883073dc9412a9e3eebd
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "common/meta/GflagsManager.h" #include "common/conf/Configuration.h" #include "common/fs/FileUtils.h" DEFINE_string(gflags_mode_json, "share/resources/gflags.json", "gflags mode json for service"); namespace nebula { namespace meta { Value GflagsManager::gflagsValueToValue(const std::string& type, const std::string& flagValue) { // all int32/uint32/uint64 gflags are converted to int64 for now folly::StringPiece view(type); if (view.startsWith("int") || view.startsWith("uint")) { return Value(folly::to<int64_t>(flagValue)); } else if (type == "double") { return Value(folly::to<double>(flagValue)); } else if (type == "bool") { return Value(folly::to<bool>(flagValue)); } else if (type == "string") { return Value(folly::to<std::string>(flagValue)); } else if (type == "map") { auto value = Value(folly::to<std::string>(flagValue)); VLOG(1) << "Nested value: " << value; // transform to map value conf::Configuration conf; auto status = conf.parseFromString(value.getStr()); if (!status.ok()) { LOG(ERROR) << "Parse value: " << value << " failed: " << status; return Value::kNullValue; } Map map; conf.forEachItem([&map](const std::string& key, const folly::dynamic& val) { map.kvs.emplace(key, val.asString()); }); value.setMap(std::move(map)); return value; } LOG(WARNING) << "Unknown type: " << type; return Value::kEmpty; } std::unordered_map<std::string, std::pair<cpp2::ConfigMode, bool>> GflagsManager::parseConfigJson( const std::string& path) { // The default conf for gflags flags mode std::unordered_map<std::string, std::pair<cpp2::ConfigMode, bool>> configModeMap{ {"max_edge_returned_per_vertex", {cpp2::ConfigMode::MUTABLE, false}}, {"minloglevel", {cpp2::ConfigMode::MUTABLE, false}}, {"v", {cpp2::ConfigMode::MUTABLE, false}}, {"heartbeat_interval_secs", {cpp2::ConfigMode::MUTABLE, false}}, {"agent_heartbeat_interval_secs", {cpp2::ConfigMode::MUTABLE, false}}, {"meta_client_retry_times", {cpp2::ConfigMode::MUTABLE, false}}, {"wal_ttl", {cpp2::ConfigMode::MUTABLE, false}}, {"clean_wal_interval_secs", {cpp2::ConfigMode::MUTABLE, false}}, {"custom_filter_interval_secs", {cpp2::ConfigMode::MUTABLE, false}}, {"accept_partial_success", {cpp2::ConfigMode::MUTABLE, false}}, {"rocksdb_db_options", {cpp2::ConfigMode::MUTABLE, true}}, {"rocksdb_column_family_options", {cpp2::ConfigMode::MUTABLE, true}}, {"rocksdb_block_based_table_options", {cpp2::ConfigMode::MUTABLE, true}}, }; conf::Configuration conf; if (!conf.parseFromFile(path).ok()) { LOG(ERROR) << "Load gflags json failed"; return configModeMap; } static std::vector<std::string> keys = {"MUTABLE"}; static std::vector<cpp2::ConfigMode> modes = {cpp2::ConfigMode::MUTABLE}; for (size_t i = 0; i < keys.size(); i++) { std::vector<std::string> values; if (!conf.fetchAsStringArray(keys[i].c_str(), values).ok()) { continue; } cpp2::ConfigMode mode = modes[i]; for (const auto& name : values) { configModeMap[name] = {mode, false}; } } static std::string nested = "NESTED"; std::vector<std::string> values; if (conf.fetchAsStringArray(nested.c_str(), values).ok()) { for (const auto& name : values) { // all nested gflags regard as mutable ones configModeMap[name] = {cpp2::ConfigMode::MUTABLE, true}; } } return configModeMap; } std::vector<cpp2::ConfigItem> GflagsManager::declareGflags(const cpp2::ConfigModule& module) { std::vector<cpp2::ConfigItem> configItems; if (module == cpp2::ConfigModule::UNKNOWN) { return configItems; } auto mutableConfig = parseConfigJson(FLAGS_gflags_mode_json); // Get all flags by listing all defined gflags std::vector<gflags::CommandLineFlagInfo> flags; gflags::GetAllFlags(&flags); for (auto& flag : flags) { auto& name = flag.name; auto type = flag.type; // We only register mutable configs to meta cpp2::ConfigMode mode = cpp2::ConfigMode::MUTABLE; auto iter = mutableConfig.find(name); if (iter != mutableConfig.end()) { // isNested if (iter->second.second) { type = "map"; } } else { continue; } Value value = gflagsValueToValue(type, flag.current_value); if (value.empty()) { LOG(INFO) << "Not able to declare " << name << " of " << flag.type; continue; } if (value.isNull()) { LOG(ERROR) << "Parse gflags: " << name << ", value: " << flag.current_value << " failed."; continue; } cpp2::ConfigItem item; item.name_ref() = name; item.module_ref() = module; item.mode_ref() = mode; item.value_ref() = std::move(value); configItems.emplace_back(std::move(item)); } LOG(INFO) << "Prepare to register " << configItems.size() << " gflags to meta"; return configItems; } void GflagsManager::getGflagsModule(cpp2::ConfigModule& gflagsModule) { // get current process according to gflags pid_file gflags::CommandLineFlagInfo pid; if (gflags::GetCommandLineFlagInfo("pid_file", &pid)) { auto defaultPid = pid.default_value; if (defaultPid.find("nebula-graphd") != std::string::npos) { gflagsModule = cpp2::ConfigModule::GRAPH; } else if (defaultPid.find("nebula-storaged") != std::string::npos) { gflagsModule = cpp2::ConfigModule::STORAGE; } else if (defaultPid.find("nebula-metad") != std::string::npos) { gflagsModule = cpp2::ConfigModule::META; } else { LOG(ERROR) << "Should not reach here"; } } else { LOG(INFO) << "Unknown config module"; } } std::string GflagsManager::ValueToGflagString(const Value& val) { switch (val.type()) { case Value::Type::BOOL: { return val.getBool() ? "true" : "false"; } case Value::Type::INT: { return folly::to<std::string>(val.getInt()); } case Value::Type::FLOAT: { return folly::to<std::string>(val.getFloat()); } case Value::Type::STRING: { return val.getStr(); } case Value::Type::MAP: { auto& kvs = val.getMap().kvs; std::vector<std::string> values(kvs.size()); std::transform(kvs.begin(), kvs.end(), values.begin(), [](const auto& iter) -> std::string { std::stringstream out; out << "\"" << iter.first << "\"" << ":" << "\"" << iter.second << "\""; return out.str(); }); std::stringstream os; os << "{" << folly::join(",", values) << "}"; return os.str(); } default: { LOG(FATAL) << "Unsupported type for gflags"; } } } } // namespace meta } // namespace nebula
34.887755
98
0.630301
wenhaocs
9c2c0ff0cc5390f799834059af174f87aa59e277
3,288
cpp
C++
src/qt/veil/veilstatusbar.cpp
Oilplik/veil-1
852b05b255b464201de53fe7afdf7c696ed50724
[ "MIT" ]
null
null
null
src/qt/veil/veilstatusbar.cpp
Oilplik/veil-1
852b05b255b464201de53fe7afdf7c696ed50724
[ "MIT" ]
null
null
null
src/qt/veil/veilstatusbar.cpp
Oilplik/veil-1
852b05b255b464201de53fe7afdf7c696ed50724
[ "MIT" ]
null
null
null
#include <qt/veil/veilstatusbar.h> #include <qt/veil/forms/ui_veilstatusbar.h> #include <qt/bitcoingui.h> #include <qt/walletmodel.h> #include <qt/veil/qtutils.h> #include <iostream> VeilStatusBar::VeilStatusBar(QWidget *parent, BitcoinGUI* gui) : QWidget(parent), mainWindow(gui), ui(new Ui::VeilStatusBar) { ui->setupUi(this); ui->checkStacking->setProperty("cssClass" , "switch"); connect(ui->btnLock, SIGNAL(clicked()), this, SLOT(onBtnLockClicked())); connect(ui->btnSync, SIGNAL(clicked()), this, SLOT(onBtnSyncClicked())); connect(ui->checkStacking, SIGNAL(toggled(bool)), this, SLOT(onCheckStakingClicked(bool))); } bool VeilStatusBar::getSyncStatusVisible() { return ui->btnSync->isVisible(); } void VeilStatusBar::updateSyncStatus(QString status){ ui->btnSync->setText(status); } void VeilStatusBar::setSyncStatusVisible(bool fVisible) { ui->btnSync->setVisible(fVisible); } void VeilStatusBar::onBtnSyncClicked(){ mainWindow->showModalOverlay(); } bool fBlockNextStakeCheckSignal = false; void VeilStatusBar::onCheckStakingClicked(bool res) { // When our own dialog internally changes the checkstate, block signal from executing if (fBlockNextStakeCheckSignal) { fBlockNextStakeCheckSignal = false; return; } // Miner thread starts in init.cpp, but staking enabled flag is checked each iteration of the miner, so can be enabled or disabled here WalletModel::EncryptionStatus lockState = walletModel->getEncryptionStatus(); if (res){ if (gArgs.GetBoolArg("-exchangesandservicesmode", false) || lockState == WalletModel::Locked) { QString dialogMsg = gArgs.GetBoolArg("-exchangesandservicesmode", false) ? "Staking is disabled in exchange mode" : "Must unlock wallet before staking can be enabled"; openToastDialog(dialogMsg, mainWindow); fBlockNextStakeCheckSignal = true; ui->checkStacking->setCheckState(Qt::CheckState::Unchecked); } } else { openToastDialog("Miner stopped", mainWindow); } if (!gArgs.GetBoolArg("-exchangesandservicesmode", false) && lockState != WalletModel::Locked) this->walletModel->setStakingEnabled(res); } bool fBlockNextBtnLockSignal = false; void VeilStatusBar::onBtnLockClicked() { // When our own dialog internally changes the checkstate, block signal from executing if (fBlockNextBtnLockSignal) { fBlockNextBtnLockSignal = false; return; } mainWindow->encryptWallet(walletModel->getEncryptionStatus() != WalletModel::Locked); fBlockNextBtnLockSignal = true; updateStakingCheckbox(); } void VeilStatusBar::setWalletModel(WalletModel *model) { this->preparingFlag = false; this->walletModel = model; updateStakingCheckbox(); this->preparingFlag = true; } void VeilStatusBar::updateStakingCheckbox() { WalletModel::EncryptionStatus lockState = walletModel->getEncryptionStatus(); ui->btnLock->setChecked(lockState == WalletModel::Locked || lockState == WalletModel::UnlockedForStakingOnly); if(this->preparingFlag) { ui->checkStacking->setChecked(walletModel->isStakingEnabled() && lockState != WalletModel::Locked); } } VeilStatusBar::~VeilStatusBar() { delete ui; }
32.88
179
0.716241
Oilplik
9c2e210c0eef0fa2784d7abf75641799a36d804f
4,156
cpp
C++
DT3Core/Resources/Importers/ImporterFontTTF.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/Resources/Importers/ImporterFontTTF.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/Resources/Importers/ImporterFontTTF.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: ImporterFontTTF.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Resources/Importers/ImporterFontTTF.hpp" #include "DT3Core/Resources/ResourceTypes/FontResource.hpp" #include "DT3Core/Types/FileBuffer/BinaryFileStream.hpp" #include "DT3Core/Types/Utility/ConsoleStream.hpp" #include "DT3Core/System/Factory.hpp" #include "DT3Core/System/FileManager.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Register with object factory //============================================================================== IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,ttf) IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,ttc) IMPLEMENT_FACTORY_IMPORTER(ImporterFontTTF,otf) //============================================================================== /// Standard class constructors/destructors //============================================================================== ImporterFontTTF::ImporterFontTTF (void) { } ImporterFontTTF::~ImporterFontTTF (void) { } //============================================================================== //============================================================================== unsigned long ImporterFontTTF::ft_io_func ( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count) { BinaryFileStream *read_ptr = reinterpret_cast<BinaryFileStream*>(stream->descriptor.pointer); read_ptr->seek_g(offset, Stream::FROM_BEGINNING); if (count == 0) return 0; return (unsigned long) read_ptr->read_raw(buffer,count); } void ImporterFontTTF::ft_close_func( FT_Stream stream) { BinaryFileStream *read_ptr = reinterpret_cast<BinaryFileStream*>(stream->descriptor.pointer); delete read_ptr; } //============================================================================== //============================================================================== DTerr ImporterFontTTF::import(FontResource *target, std::string args) { // Open up the stream for the font file BinaryFileStream *file = new BinaryFileStream(); // This pointer has to go through a C-API so no shared_ptr DTerr err = FileManager::open(*file, target->path(), true); if (err != DT3_ERR_NONE) { LOG_MESSAGE << "Unable to open font " << target->path().full_path(); delete file; return DT3_ERR_FILE_OPEN_FAILED; } // Send the stream to freetype FT_Open_Args ftargs; ::memset((void *)&ftargs,0,sizeof(ftargs)); ftargs.flags = FT_OPEN_STREAM; ftargs.stream=(FT_Stream)malloc(sizeof *(ftargs.stream)); ftargs.stream->base = NULL; ftargs.stream->size = static_cast<DTuint>(file->length()); ftargs.stream->pos = 0; ftargs.stream->descriptor.pointer = (void*) (file); ftargs.stream->pathname.pointer = NULL; ftargs.stream->read = &ImporterFontTTF::ft_io_func; ftargs.stream->close = &ImporterFontTTF::ft_close_func; FT_Error error = ::FT_Open_Face(FontResource::library(), &ftargs, 0, &(target->typeface())); ::FT_Select_Charmap(target->typeface(),FT_ENCODING_UNICODE); return error == 0 ? DT3_ERR_NONE : DT3_ERR_FILE_OPEN_FAILED; } //============================================================================== //============================================================================== } // DT3
36.778761
111
0.478104
9heart
9c2e5f56b26e34245f54665bec514f35e3fed30d
5,272
cpp
C++
tests/Util/Time.cpp
DiantArts/xrnEcs
821ad9504dc022972f499721a8f494ab78d4d2d8
[ "MIT" ]
null
null
null
tests/Util/Time.cpp
DiantArts/xrnEcs
821ad9504dc022972f499721a8f494ab78d4d2d8
[ "MIT" ]
13
2022-03-18T00:36:09.000Z
2022-03-28T14:14:26.000Z
tests/Util/Time.cpp
DiantArts/xrnEcs
821ad9504dc022972f499721a8f494ab78d4d2d8
[ "MIT" ]
null
null
null
#include <pch.hpp> #include <xrn/Util/Time.hpp> template class ::xrn::util::BasicTime<double>; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include <boost/test/unit_test.hpp> #pragma GCC diagnostic pop BOOST_AUTO_TEST_SUITE(test) BOOST_AUTO_TEST_SUITE(xrn) BOOST_AUTO_TEST_SUITE(util) BOOST_AUTO_TEST_SUITE(Time) BOOST_AUTO_TEST_CASE(Basic) { using ::xrn::util::literal::operator""_ns; auto t1{ ::xrn::Time::createAsSeconds(0.1) }; auto t2{ t1.getAsMilliseconds() }; // 100ms ::xrn::Time t3{ 30 }; auto t4{ t3.getAsMicroseconds() }; // 30000ms auto t5{ ::xrn::Time::createAsNanoseconds(-800000) }; // -0.8 auto t6{ t5.getAsSeconds() }; // -0.0008ms auto t7{ t1 + ::xrn::Time::createAsSeconds(t6) }; // 99.2ms auto t8{ t1 + -800000_ns }; // 99.2ms auto t9{ t1 + t5 }; // 99.2ms auto t10{ t1 + 55 }; // 155ms auto t11{ 55 + t1 }; // 155ms BOOST_TEST((t1 == 100)); BOOST_TEST((t2 == 100)); BOOST_TEST((t3 == 30)); BOOST_TEST((t4 == 30000)); BOOST_TEST((t5 == -0.8)); BOOST_TEST((t6 == -0.0008)); BOOST_TEST((t7 == 99.2)); BOOST_TEST((t8 == 99.2)); BOOST_TEST((t9 == 99.2)); BOOST_TEST((t10 == 155)); BOOST_TEST((t11 == 155)); } BOOST_AUTO_TEST_CASE(Creates) { auto t1{ ::xrn::Time::createAsSeconds(30) }; auto t2{ ::xrn::Time::createAsMilliseconds(30) }; auto t3{ ::xrn::Time::createAsMicroseconds(30) }; auto t4{ ::xrn::Time::createAsNanoseconds(30) }; BOOST_TEST((t1 == 30000)); BOOST_TEST((t2 == 30)); BOOST_TEST((t3 == 0.03)); BOOST_TEST((t4 == 0.00003)); } BOOST_AUTO_TEST_CASE(Compares) { auto t1{ ::xrn::Time::createAsSeconds(30) }; auto t2{ ::xrn::Time::createAsMilliseconds(30000) }; auto t3{ ::xrn::Time::createAsMicroseconds(30000000) }; auto t4{ ::xrn::Time::createAsNanoseconds(30000000000) }; auto t5{ ::xrn::Time::createAsNanoseconds(20000000000) }; auto t6{ 30000 }; BOOST_TEST((t1 == t2)); BOOST_TEST((t1 == t3)); BOOST_TEST((t1 == t4)); BOOST_TEST((t4 == t1)); BOOST_TEST((t1 >= t5)); BOOST_TEST((t1 > t5)); BOOST_TEST((t5 <= t1)); BOOST_TEST((t5 < t1)); BOOST_TEST((t5 != t1)); BOOST_TEST((t1 != t5)); BOOST_TEST((t1 == t6)); BOOST_TEST((t6 == t1)); BOOST_TEST((t6 >= t5)); BOOST_TEST((t6 > t5)); BOOST_TEST((t5 <= t6)); BOOST_TEST((t5 < t6)); BOOST_TEST((t5 != t6)); BOOST_TEST((t6 != t5)); } BOOST_AUTO_TEST_CASE(GettersSetters) { auto t1{ ::xrn::Time::createAsSeconds(30) }; BOOST_TEST((t1 == 30000)); BOOST_TEST((t1.get() == 30000)); BOOST_TEST((static_cast<double>(t1) == 30000)); BOOST_TEST((t1.getAsSeconds() == 30)); BOOST_TEST((t1.getAsMilliseconds() == 30000)); BOOST_TEST((t1.getAsMicroseconds() == 30000000)); BOOST_TEST((t1.getAsNanoseconds() == 30000000000)); t1 = ::xrn::Time::createAsSeconds(40); BOOST_TEST((t1.get() == 40000)); BOOST_TEST((static_cast<double>(t1) == 40000)); BOOST_TEST((t1.getAsSeconds() == 40)); BOOST_TEST((t1.getAsMilliseconds() == 40000)); BOOST_TEST((t1.getAsMicroseconds() == 40000000)); BOOST_TEST((t1.getAsNanoseconds() == 40000000000)); t1.set(::xrn::Time::createAsSeconds(50)); BOOST_TEST((t1.get() == 50000)); BOOST_TEST((static_cast<double>(t1) == 50000)); BOOST_TEST((t1.getAsSeconds() == 50)); BOOST_TEST((t1.getAsMilliseconds() == 50000)); BOOST_TEST((t1.getAsMicroseconds() == 50000000)); BOOST_TEST((t1.getAsNanoseconds() == 50000000000)); t1.set(60000); BOOST_TEST((t1.get() == 60000)); BOOST_TEST((static_cast<double>(t1) == 60000)); BOOST_TEST((t1.getAsSeconds() == 60)); BOOST_TEST((t1.getAsMilliseconds() == 60000)); BOOST_TEST((t1.getAsMicroseconds() == 60000000)); BOOST_TEST((t1.getAsNanoseconds() == 60000000000)); } BOOST_AUTO_TEST_CASE(Add) { auto t1{ ::xrn::Time::createAsSeconds(3) }; auto t2{ ::xrn::Time::createAsSeconds(3) }; t1 += t2; BOOST_TEST((t1 == 6000)); t1 = t1 + t2; BOOST_TEST((t1 == 9000)); t1 += 3000; BOOST_TEST((t1 == 12000)); t1 = t2 + 3000; BOOST_TEST((t1 == 6000)); t1.add(t2); BOOST_TEST((t1 == 9000)); t1.add(3000); BOOST_TEST((t1 == 12000)); } BOOST_AUTO_TEST_CASE(Sub) { auto t1{ ::xrn::Time::createAsSeconds(3) }; auto t2{ ::xrn::Time::createAsSeconds(3) }; t1 -= t2; BOOST_TEST((t1 == 0)); t1 = t1 - t2; BOOST_TEST((t1 == -3000)); t1 -= 3000; BOOST_TEST((t1 == -6000)); t1 = t2 - 3000; BOOST_TEST((t1 == 0)); t1.sub(t2); BOOST_TEST((t1 == -3000)); t1.sub(3000); BOOST_TEST((t1 == -6000)); } BOOST_AUTO_TEST_CASE(MulDiv) { auto t1{ ::xrn::Time::createAsSeconds(3) }; t1 *= 3; BOOST_TEST((t1 == 9000)); t1 /= 3; BOOST_TEST((t1 == 3000)); t1 = t1 * 3; BOOST_TEST((t1 == 9000)); t1 = t1 / 3; BOOST_TEST((t1 == 3000)); } BOOST_AUTO_TEST_CASE(Mod) { auto t1{ ::xrn::Time::createAsSeconds(3) }; t1 %= 3; BOOST_TEST((t1 == 0)); t1 = ::xrn::Time::createAsSeconds(3); t1 = t1 % 3; BOOST_TEST((t1 == 0)); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
27.89418
65
0.600341
DiantArts
9c2ebb2b4126a7a0e3470acf34861584d1d0ec3a
654
hpp
C++
include/Nazara/Utility/Utility.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Utility/Utility.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Utility/Utility.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_UTILITY_HPP #define NAZARA_UTILITY_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Core.hpp> #include <Nazara/Utility/Config.hpp> namespace Nz { class NAZARA_UTILITY_API Utility : public ModuleBase<Utility> { friend ModuleBase; public: using Dependencies = TypeList<Core>; struct Config {}; Utility(Config /*config*/); ~Utility(); private: static Utility* s_instance; }; } #endif // NAZARA_UTILITY_HPP
19.235294
77
0.733945
waruqi
9c2f73da43d1aa0b1dcb025e970eebebc5984250
6,815
cc
C++
components/no_state_prefetch/common/prerender_url_loader_throttle.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/no_state_prefetch/common/prerender_url_loader_throttle.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/no_state_prefetch/common/prerender_url_loader_throttle.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/no_state_prefetch/common/prerender_url_loader_throttle.h" #include "base/bind.h" #include "build/build_config.h" #include "components/no_state_prefetch/common/prerender_util.h" #include "content/public/common/content_constants.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/load_flags.h" #include "net/url_request/redirect_info.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/loader/resource_type_util.h" namespace prerender { namespace { const char kPurposeHeaderName[] = "Purpose"; const char kPurposeHeaderValue[] = "prefetch"; void CallCancelPrerenderForUnsupportedScheme( mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler) { mojo::Remote<prerender::mojom::PrerenderCanceler>(std::move(canceler)) ->CancelPrerenderForUnsupportedScheme(); } // Returns true if the response has a "no-store" cache control header. bool IsNoStoreResponse(const network::mojom::URLResponseHead& response_head) { return response_head.headers && response_head.headers->HasHeaderValue("cache-control", "no-store"); } } // namespace PrerenderURLLoaderThrottle::PrerenderURLLoaderThrottle( const std::string& histogram_prefix, mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler) : histogram_prefix_(histogram_prefix), canceler_(std::move(canceler)) { DCHECK(canceler_); } PrerenderURLLoaderThrottle::~PrerenderURLLoaderThrottle() { if (destruction_closure_) std::move(destruction_closure_).Run(); } void PrerenderURLLoaderThrottle::PrerenderUsed() { if (original_request_priority_) delegate_->SetPriority(original_request_priority_.value()); if (deferred_) delegate_->Resume(); } void PrerenderURLLoaderThrottle::DetachFromCurrentSequence() { // This method is only called for synchronous XHR from the main thread which // should not occur during a NoStatePrerender. NOTREACHED(); } void PrerenderURLLoaderThrottle::WillStartRequest( network::ResourceRequest* request, bool* defer) { request->load_flags |= net::LOAD_PREFETCH; request->cors_exempt_headers.SetHeader(kPurposeHeaderName, kPurposeHeaderValue); request_destination_ = request->destination; // Abort any prerenders that spawn requests that use unsupported HTTP // methods or schemes. if (!IsValidHttpMethod(request->method)) { // If this is a full prerender, cancel the prerender in response to // invalid requests. For prefetches, cancel invalid requests but keep the // prefetch going. delegate_->CancelWithError(net::ERR_ABORTED); } if (request->destination != network::mojom::RequestDestination::kDocument && !DoesSubresourceURLHaveValidScheme(request->url)) { // Destroying the prerender for unsupported scheme only for non-main // resource to allow chrome://crash to actually crash in the // *RendererCrash tests instead of being intercepted here. The // unsupported scheme for the main resource is checked in // WillRedirectRequest() and NoStatePrefetchContents::CheckURL(). See // http://crbug.com/673771. delegate_->CancelWithError(net::ERR_ABORTED); CallCancelPrerenderForUnsupportedScheme(std::move(canceler_)); return; } #if defined(OS_ANDROID) if (request->is_favicon) { // Delay icon fetching until the contents are getting swapped in // to conserve network usage in mobile devices. *defer = true; return; } #else // Priorities for prerendering requests are lowered, to avoid competing with // other page loads, except on Android where this is less likely to be a // problem. In some cases, this may negatively impact the performance of // prerendering, see https://crbug.com/652746 for details. // Requests with the IGNORE_LIMITS flag set (i.e., sync XHRs) // should remain at MAXIMUM_PRIORITY. if (request->load_flags & net::LOAD_IGNORE_LIMITS) { DCHECK_EQ(request->priority, net::MAXIMUM_PRIORITY); } else if (request->priority != net::IDLE) { original_request_priority_ = request->priority; request->priority = net::IDLE; } #endif // OS_ANDROID detached_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds( content::kDefaultDetachableCancelDelayMs), this, &PrerenderURLLoaderThrottle::OnTimedOut); } const char* PrerenderURLLoaderThrottle::NameForLoggingWillStartRequest() { return "PrerenderThrottle"; } void PrerenderURLLoaderThrottle::WillRedirectRequest( net::RedirectInfo* redirect_info, const network::mojom::URLResponseHead& response_head, bool* defer, std::vector<std::string>* /* to_be_removed_headers */, net::HttpRequestHeaders* /* modified_headers */, net::HttpRequestHeaders* /* modified_cors_exempt_headers */) { redirect_count_++; RecordPrefetchResponseReceived( histogram_prefix_, blink::IsRequestDestinationFrame(request_destination_), true /* is_redirect */, IsNoStoreResponse(response_head)); std::string follow_only_when_prerender_shown_header; if (response_head.headers) { response_head.headers->GetNormalizedHeader( kFollowOnlyWhenPrerenderShown, &follow_only_when_prerender_shown_header); } // Abort any prerenders with requests which redirect to invalid schemes. if (!DoesURLHaveValidScheme(redirect_info->new_url)) { delegate_->CancelWithError(net::ERR_ABORTED); CallCancelPrerenderForUnsupportedScheme(std::move(canceler_)); } else if (follow_only_when_prerender_shown_header == "1" && request_destination_ != network::mojom::RequestDestination::kDocument) { // Only defer redirects with the Follow-Only-When-Prerender-Shown // header. Do not defer redirects on main frame loads. *defer = true; deferred_ = true; } } void PrerenderURLLoaderThrottle::WillProcessResponse( const GURL& response_url, network::mojom::URLResponseHead* response_head, bool* defer) { bool is_main_resource = blink::IsRequestDestinationFrame(request_destination_); RecordPrefetchResponseReceived(histogram_prefix_, is_main_resource, true /* is_redirect */, IsNoStoreResponse(*response_head)); RecordPrefetchRedirectCount(histogram_prefix_, is_main_resource, redirect_count_); } void PrerenderURLLoaderThrottle::OnTimedOut() { delegate_->CancelWithError(net::ERR_ABORTED); } } // namespace prerender
38.721591
80
0.73485
iridium-browser
9c3062e925d921e9a97c72c056b1e17c1b853826
14,587
cpp
C++
whip/VFSBackend.cpp
IlyaFinkelshteyn/whip-server-1
d6055f523950f5f05cb164cc7ad79a5a9424809f
[ "Apache-2.0" ]
2
2018-08-16T02:00:55.000Z
2018-08-19T06:27:00.000Z
whip/VFSBackend.cpp
IlyaFinkelshteyn/whip-server-1
d6055f523950f5f05cb164cc7ad79a5a9424809f
[ "Apache-2.0" ]
2
2018-08-19T17:49:15.000Z
2019-04-24T16:58:32.000Z
whip/VFSBackend.cpp
IlyaFinkelshteyn/whip-server-1
d6055f523950f5f05cb164cc7ad79a5a9424809f
[ "Apache-2.0" ]
5
2016-12-18T08:16:04.000Z
2017-06-04T22:59:41.000Z
#include "StdAfx.h" #include "VFSBackend.h" #include "AppLog.h" #include "AssetStorageError.h" #include "Settings.h" #include "DatabaseSet.h" #include "IndexFile.h" #include "SQLiteIndexFileManager.h" #include "IIndexFileManager.h" #include "kashmir/uuid.h" #include "SQLiteError.h" #include <boost/filesystem/fstream.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/shared_array.hpp> #include <boost/thread/mutex.hpp> #include <boost/foreach.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <stdexcept> #include <sstream> #include <vector> #include <boost/cstdlib.hpp> namespace fs = boost::filesystem; using namespace boost::posix_time; namespace iwvfs { VFSBackend::VFSBackend(const std::string& storageRoot, bool enablePurge, boost::asio::io_service& ioService, PushReplicationService::ptr pushRepl) : _storageRoot(storageRoot), _enablePurge(enablePurge), _stop(false), _ioService(ioService), _purgeLocalsTimer(ioService), _isPurgingLocals(false), _currentLocalsPurgeIndex(0), _diskLatencyAvg(DISK_LATENCY_SAMPLE_SIZE), _diskOpAvg(DISK_LATENCY_SAMPLE_SIZE), _pushRepl(pushRepl) { SAFELOG(AppLog::instance().out() << "[IWVFS] Starting storage backend" << std::endl); //make sure the storage root exists if (! fs::exists(_storageRoot)) { throw std::runtime_error("Unable to start storage backend, the storage root '" + storageRoot + "' was not found"); } SAFELOG(AppLog::instance().out() << "[IWVFS] Root: " << storageRoot << ", Purge: " << (_enablePurge ? "enabled" : "disabled") << std::endl); _debugging = whip::Settings::instance().get("debug").as<bool>(); SAFELOG(AppLog::instance().out() << "[IWVFS] SQLite Index Backend: SQLite v" << sqlite3_libversion() << std::endl); //TODO: Should be deleted on shutdown IIndexFileManager::ptr indexFileManager(new SQLiteIndexFileManager()); IndexFile::SetIndexFileManager(indexFileManager); SAFELOG(AppLog::instance().out() << "[IWVFS] Generating asset existence index" << std::endl); _existenceIndex.reset(new ExistenceIndex(storageRoot)); SAFELOG(AppLog::instance().out() << "[IWVFS] Starting disk I/O worker thread" << std::endl); _workerThread.reset(new boost::thread(boost::bind(&VFSBackend::workLoop, this))); } VFSBackend::~VFSBackend() { } void VFSBackend::workLoop() { while( !_stop ) { try { AssetRequest::ptr req; { boost::mutex::scoped_lock lock(_workMutex); while(_workQueue.empty() && !_stop) { _workArrived.wait(lock); } if (_stop) break; req = _workQueue.front(); _workQueue.pop_front(); } _diskLatencyAvg.addSample(req->queueDuration()); ptime opStart = microsec_clock::universal_time(); req->processRequest(*this); time_duration diff = microsec_clock::universal_time() - opStart; _diskOpAvg.addSample((int) diff.total_milliseconds()); } catch (const std::exception& e) { _ioService.post(boost::bind(&VFSBackend::ioLoopFailed, this, std::string(e.what()))); } catch (...) { _ioService.post(boost::bind(&VFSBackend::ioLoopFailed, this, "Unknown error")); } } } void VFSBackend::performDiskWrite(Asset::ptr asset, AsyncStoreAssetCallback callback) { try { this->storeAsset(asset); _ioService.post(boost::bind(callback, true, AssetStorageError::ptr())); _pushRepl->queueAssetForPush(asset); } catch (const AssetStorageError& storageError) { AssetStorageError::ptr error(new AssetStorageError(storageError)); _ioService.post(boost::bind(callback, false, error)); } catch (const std::exception& storageError) { AssetStorageError::ptr error(new AssetStorageError(storageError.what())); _ioService.post(boost::bind(&VFSBackend::assetWriteFailed, this, asset->getUUID(), storageError.what())); _ioService.post(boost::bind(callback, false, error)); } } void VFSBackend::assetWriteFailed(std::string assetId, std::string reason) { SAFELOG(AppLog::instance().error() << "[IWVFS] Asset write failed for " << assetId << ": " << reason << std::endl); _existenceIndex->removeId(kashmir::uuid::uuid_t(assetId.c_str())); } void VFSBackend::ioLoopFailed(std::string reason) { SAFELOG(AppLog::instance().error() << "[IWVFS] Critical warning: ioWorker caught exception: " << reason << std::endl); } void VFSBackend::performDiskRead(const std::string& assetId, AsyncGetAssetCallback callback) { try { Asset::ptr asset = this->getAsset(assetId); if (asset) { _ioService.post(boost::bind(callback, asset, true, AssetStorageError::ptr())); } else { AssetStorageError::ptr error(new AssetStorageError("Asset " + assetId + " not found")); _ioService.post(boost::bind(callback, Asset::ptr(), false, error)); } } catch (const AssetStorageError& storageError) { AssetStorageError::ptr error(new AssetStorageError(storageError)); _ioService.post(boost::bind(callback, Asset::ptr(), false, error)); } catch (const std::exception& storageError) { AssetStorageError::ptr error(new AssetStorageError(storageError.what())); _ioService.post(boost::bind(callback, Asset::ptr(), false, error)); } } void VFSBackend::performDiskPurge(const std::string& assetId, AsyncAssetPurgeCallback callback) { } void VFSBackend::performDiskPurgeLocals(const std::string& uuidHead) { //purging locals has three steps which starts here // 1) The first step is to look up the asset ids that are contained in the specified index/locals file // 2) Those local ids are passed to the existence index for deletion // 3) When that process completes a full deletion is scheduled for the locals data file and index fs::path indexPath(fs::path(_storageRoot) / uuidHead / "locals.idx"); UuidListPtr containedIds; if (fs::exists(indexPath)) { //open the index file and get a list of asset ids contained within IndexFile::ptr indexFile(new IndexFile(indexPath)); containedIds = indexFile->getContainedAssetIds(); } //schedule a deletion of the returned uuids to happen on the ASIO thread _ioService.post(boost::bind(&VFSBackend::unindexLocals, this, containedIds, uuidHead)); } void VFSBackend::unindexLocals(UuidListPtr uuidList, std::string uuidHead) { if (uuidList) { UuidList::iterator end = uuidList->end(); for (UuidList::iterator i = uuidList->begin(); i != end; ++i) { _existenceIndex->removeId(*i); } } //schedule physical deletion of the index and data files AssetRequest::ptr req(new DeleteLocalStorageRequest(uuidHead)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::performLocalsPhysicalDeletion(const std::string& uuidHead) { fs::path indexPath(fs::path(_storageRoot) / uuidHead / "locals.idx"); IndexFile::GetIndexFileManager()->forceCloseIndexFile(indexPath); //the index file is guaranteed to not be in use, delete the index file and the data file fs::path dataPath(fs::path(_storageRoot) / uuidHead / "locals.data"); fs::remove(indexPath); fs::remove(dataPath); } bool VFSBackend::isLittleEndian() { union { boost::uint32_t i; char c[4]; } bint = {0x01020304}; return bint.c[0] != 1; } fs::path VFSBackend::getFullPathForUUID(const std::string& uuid) { fs::path subdir(fs::path(_storageRoot) / fs::path(uuid.substr(0, whip::Settings::UUID_PATH_CHARS))); return subdir; } void VFSBackend::verifyDatabaseDirectory(const std::string& uuid) { fs::path subdir(this->getFullPathForUUID(uuid)); if (! fs::exists(subdir)) { if (! fs::create_directory(subdir)) { throw AssetStorageError("Could not create directory for database storage " + subdir.string(), true); } } } DatabaseSet::ptr VFSBackend::verifyAndopenSetForUUID(const std::string& uuid) { try { this->verifyDatabaseDirectory(uuid); DatabaseSet::ptr dbset(new DatabaseSet(this->getFullPathForUUID(uuid))); return dbset; } catch (const SQLiteError& e) { throw AssetStorageError(std::string("Index file error: ") + e.what(), true); } } Asset::ptr VFSBackend::getAsset(const std::string& uuid) { DatabaseSet::ptr dbset(this->verifyAndopenSetForUUID(uuid)); Asset::ptr localAsset(dbset->getAsset(uuid)); return localAsset; } void VFSBackend::storeAsset(Asset::ptr asset) { DatabaseSet::ptr dbset(this->verifyAndopenSetForUUID(asset->getUUID())); dbset->storeAsset(asset); } bool VFSBackend::assetExists(const std::string& uuid) { return _existenceIndex->assetExists(uuid); } void VFSBackend::purgeAsset(const std::string& uuid) { //TODO: Not implemented } void VFSBackend::getAsset(const std::string& uuid, unsigned int flags, AsyncGetAssetCallback callBack) { //flags are not used here yet this->getAsset(uuid, callBack); } void VFSBackend::getAsset(const std::string& uuid, AsyncGetAssetCallback callBack) { //use the cache to shortcut the situation where the asset doesnt exist if (! _existenceIndex->assetExists(uuid)) { AssetStorageError::ptr error(new AssetStorageError("Could not retrieve asset " + uuid + ", asset not found")); _ioService.post(boost::bind(callBack, Asset::ptr(), false, error)); return; } AssetRequest::ptr req(new AssetGetRequest(uuid, callBack)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::storeAsset(Asset::ptr asset, AsyncStoreAssetCallback callBack) { //use the cache to shortcut the situation where the asset already exists if (_existenceIndex->assetExists(asset->getUUID())) { AssetStorageError::ptr error(new AssetStorageError("Unable to store asset " + asset->getUUID() + ", asset already exists")); _ioService.post(boost::bind(callBack, false, error)); return; } //we put the asset into the existance index now to be sure there are no race conditions //between storage and subsequent retrieval // remember the queue will process all // requests in order so getting a successful response for a read here is ok since // the write will always happen first _existenceIndex->addNewId(asset->getUUID()); AssetRequest::ptr req(new AssetPutRequest(asset, callBack)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::purgeAsset(const std::string& uuid, AsyncAssetPurgeCallback callBack) { AssetRequest::ptr req(new AssetPurgeRequest(uuid, false, callBack)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::beginPurgeLocals() { if (! _isPurgingLocals) { SAFELOG(AppLog::instance().out() << "[IWVFS] PurgeLocals command received, beginning purge" << std::endl); _isPurgingLocals = true; _currentLocalsPurgeIndex = 0; _purgeLocalsTimer.expires_from_now(boost::posix_time::seconds(1)); _purgeLocalsTimer.async_wait(boost::bind(&VFSBackend::onPurgeTimer, this, boost::asio::placeholders::error)); } } void VFSBackend::onPurgeTimer(const boost::system::error_code& error) { if (!error) { std::stringstream hexNum; hexNum << std::setfill('0') << std::setw(whip::Settings::UUID_PATH_CHARS) << std::hex << _currentLocalsPurgeIndex++; std::string assetId(hexNum.str()); AssetRequest::ptr req(new AssetPurgeRequest(assetId, true)); SAFELOG(AppLog::instance().out() << "[IWVFS] Queueing purge of: " << assetId << std::endl); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); if (_currentLocalsPurgeIndex <= 0xFFF) { _purgeLocalsTimer.expires_from_now(boost::posix_time::seconds(1)); _purgeLocalsTimer.async_wait(boost::bind(&VFSBackend::onPurgeTimer, this, boost::asio::placeholders::error)); } else { _isPurgingLocals = false; } } else { SAFELOG(AppLog::instance().out() << "[IWVFS] PurgeLocals timer execution error: " << error.message() << std::endl); } } void VFSBackend::getStatus(boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback) { AssetRequest::ptr req(new CollectStatusRequest(journal, completedCallback)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::performGetStatus(boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback) { (*journal) << "-VFS Backend" << std::endl; { boost::mutex::scoped_lock lock(_workMutex); (*journal) << " Disk queue size: " << _workQueue.size() << std::endl; (*journal) << " Avg Disk Queue Wait: " << _diskLatencyAvg.getAverage() << " ms" << std::endl; (*journal) << " Avg Disk Op Latency: " << _diskOpAvg.getAverage() << " ms" << std::endl; (*journal) << "-VFS Queue Items" << std::endl; BOOST_FOREACH(AssetRequest::ptr req, _workQueue) { (*journal) << " " << req->getDescription() << std::endl; } } _ioService.post(completedCallback); } void VFSBackend::getStoredAssetIDsWithPrefix(std::string prefix, boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback) { AssetRequest::ptr req(new GetStoredAssetIdsRequest(prefix, journal, completedCallback)); boost::mutex::scoped_lock lock(_workMutex); _workQueue.push_back(req); _workArrived.notify_one(); } void VFSBackend::performGetStoredAssetIds(std::string prefix, boost::shared_ptr<std::ostream> journal, boost::function<void()> completedCallback) { fs::path indexPath(fs::path(_storageRoot) / prefix / "globals.idx"); if (fs::exists(indexPath)) { //open the index file and get a list of asset ids contained within IndexFile::ptr indexFile(new IndexFile(indexPath)); StringUuidListPtr containedIds = indexFile->getContainedAssetIdStrings(); StringUuidList& containedIdsRef = *containedIds; BOOST_FOREACH(const std::string& assetId, containedIdsRef) { (*journal) << assetId << ","; } } _ioService.post(completedCallback); } void VFSBackend::shutdown() { SAFELOG(AppLog::instance().out() << "[IWVFS] Performing clean shutdown" << std::endl); _stop = true; { boost::mutex::scoped_lock lock(_workMutex); _workArrived.notify_one(); } if (_workerThread->joinable()) { _workerThread->join(); } SAFELOG(AppLog::instance().out() << "[IWVFS] Closing indexes" << std::endl); IndexFile::GetIndexFileManager()->shutdown(); SAFELOG(AppLog::instance().out() << "[IWVFS] Shutdown complete" << std::endl); } ExistenceIndex::ptr VFSBackend::getIndex() { return _existenceIndex; } }
31.989035
149
0.710838
IlyaFinkelshteyn
9c30b76ccf7ff6426b05eb259bf7db7ef015b39b
4,019
hpp
C++
Source/AMRInterpolator/AMRInterpolator.hpp
GeraintPratten/GRChombo
ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6
[ "BSD-3-Clause" ]
null
null
null
Source/AMRInterpolator/AMRInterpolator.hpp
GeraintPratten/GRChombo
ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6
[ "BSD-3-Clause" ]
null
null
null
Source/AMRInterpolator/AMRInterpolator.hpp
GeraintPratten/GRChombo
ab6c9d5bd2267215a8f199f3df1ea9dcf4b5abe6
[ "BSD-3-Clause" ]
null
null
null
/* GRChombo * Copyright 2012 The GRChombo collaboration. * Please refer to LICENSE in GRChombo's root directory. */ #ifndef AMRINTERPOLATOR_HPP_ #define AMRINTERPOLATOR_HPP_ // Chombo includes #include "AMR.H" #include "AMRLevel.H" #include "UsingNamespace.H" // Our includes #include "BoundaryConditions.hpp" #include "InterpSource.hpp" #include "InterpolationAlgorithm.hpp" #include "InterpolationLayout.hpp" #include "InterpolationQuery.hpp" #include "MPIContext.hpp" #include "UserVariables.hpp" // End include template <typename InterpAlgo> class AMRInterpolator { public: // constructor for backward compatibility // (adds an artificial BC with only periodic BC) AMRInterpolator(const AMR &amr, const std::array<double, CH_SPACEDIM> &coarsest_origin, const std::array<double, CH_SPACEDIM> &coarsest_dx, int verbosity = 0); AMRInterpolator(const AMR &amr, const std::array<double, CH_SPACEDIM> &coarsest_origin, const std::array<double, CH_SPACEDIM> &coarsest_dx, const BoundaryConditions::params_t &a_bc_params, int verbosity = 0); void refresh(); void limit_num_levels(unsigned int num_levels); void interp(InterpolationQuery &query); const AMR &getAMR() const; const std::array<double, CH_SPACEDIM> &get_coarsest_dx(); const std::array<double, CH_SPACEDIM> &get_coarsest_origin(); private: void computeLevelLayouts(); InterpolationLayout findBoxes(InterpolationQuery &query); void prepareMPI(InterpolationQuery &query, const InterpolationLayout layout); void exchangeMPIQuery(); void calculateAnswers(InterpolationQuery &query); void exchangeMPIAnswer(); /// set values of member 'm_lo_boundary_reflective' and /// 'm_hi_boundary_reflective' void set_reflective_BC(); int get_var_parity(int comp, const VariableType type, int point_idx, const InterpolationQuery &query, const Derivative &deriv) const; /// reflect coordinates if BC set to reflective in that direction double apply_reflective_BC_on_coord(const InterpolationQuery &query, double dir, int point_idx) const; const AMR &m_amr; // Coordinates of the point represented by IntVect::Zero in coarsest grid const std::array<double, CH_SPACEDIM> m_coarsest_origin; // Grid spacing in each direction const std::array<double, CH_SPACEDIM> m_coarsest_dx; int m_num_levels; const int m_verbosity; std::vector<std::array<double, CH_SPACEDIM>> m_origin; std::vector<std::array<double, CH_SPACEDIM>> m_dx; MPIContext m_mpi; std::vector<int> m_mpi_mapping; // Memoisation of boxes previously found std::vector<int> m_mem_level; std::vector<int> m_mem_box; std::vector<int> m_query_level; std::vector<int> m_query_box; std::vector<double> m_query_coords[CH_SPACEDIM]; std::vector<std::vector<double>> m_query_data; std::vector<int> m_answer_level; std::vector<int> m_answer_box; std::vector<double> m_answer_coords[CH_SPACEDIM]; std::vector<std::vector<double>> m_answer_data; // A bit of Android-ism here, but it's really useful! // Identifies the printout as originating from this class. const static string TAG; // Variables for reflective BC // m_bc_params can't be a 'const' reference as we need a // constructor with backward compatibility that builds an artificial // 'BoundaryConditions::params_t' BoundaryConditions::params_t m_bc_params; /// simplified bools saying whether or not boundary has /// a reflective condition in a given direction std::array<bool, CH_SPACEDIM> m_lo_boundary_reflective, m_hi_boundary_reflective; std::array<double, CH_SPACEDIM> m_upper_corner; }; #include "AMRInterpolator.impl.hpp" #endif /* AMRINTERPOLATOR_HPP_ */
33.491667
77
0.696193
GeraintPratten
9c314dcd38ff3f5e0bc532827b1b1eb040b8fd5b
6,135
hpp
C++
src/libraries/core/meshes/lduMesh/lduPrimitiveMesh.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshes/lduMesh/lduPrimitiveMesh.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshes/lduMesh/lduPrimitiveMesh.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::lduPrimitiveMesh Description Simplest contrete lduMesh which stores the addressing needed by lduMatrix. \*---------------------------------------------------------------------------*/ #ifndef lduPrimitiveMesh_H #define lduPrimitiveMesh_H #include "lduMesh.hpp" #include "labelList.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class lduPrimitiveMesh Declaration \*---------------------------------------------------------------------------*/ class lduPrimitiveMesh : public lduMesh, public lduAddressing { // Private data //- Lower addressing labelList lowerAddr_; //- Upper addressing labelList upperAddr_; //- Patch to internal addressing labelListList patchAddr_; //- List of pointers for each patch // with only those pointing to interfaces being set lduInterfacePtrsList interfaces_; //- Patch field evaluation schedule. lduSchedule patchSchedule_; // Private Member Functions //- Disallow default bitwise copy construct lduPrimitiveMesh(const lduPrimitiveMesh&); //- Disallow default bitwise assignment void operator=(const lduPrimitiveMesh&); public: // Constructors //- Construct from components but without interfaces. Add interfaces // separately using addInterfaces lduPrimitiveMesh ( const label nCells, labelList& l, labelList& u, bool reUse ) : lduAddressing(nCells), lowerAddr_(l, reUse), upperAddr_(u, reUse) {} //- Add interfaces to a mesh constructed without void addInterfaces ( const lduInterfacePtrsList& interfaces, const labelListList& pa, const lduSchedule& ps ) { interfaces_ = interfaces; patchAddr_ = pa; patchSchedule_ = ps; } //- Clear interfaces void clearInterfaces() { forAll (interfaces_, i) { if (interfaces_.set(i)) { delete interfaces_(i); } } } //- Construct from components as copies lduPrimitiveMesh ( const label nCells, const labelUList& l, const labelUList& u, const labelListList& pa, lduInterfacePtrsList interfaces, const lduSchedule& ps ) : lduAddressing(nCells), lowerAddr_(l), upperAddr_(u), patchAddr_(pa), interfaces_(interfaces), patchSchedule_(ps) {} //- Construct from components and re-use storage as specified. lduPrimitiveMesh ( const label nCells, labelList& l, labelList& u, labelListList& pa, lduInterfacePtrsList interfaces, const lduSchedule& ps, bool reUse ) : lduAddressing(nCells), lowerAddr_(l, reUse), upperAddr_(u, reUse), patchAddr_(pa, reUse), interfaces_(interfaces, reUse), patchSchedule_(ps) {} //- Destructor virtual ~lduPrimitiveMesh() {} // Member Functions //- Return number of interfaces virtual label nPatches() const { return interfaces_.size(); } // Access //- Return ldu addressing virtual const lduAddressing& lduAddr() const { return *this; } //- Return a list of pointers for each patch // with only those pointing to interfaces being set virtual lduInterfacePtrsList interfaces() const { return interfaces_; } //- Return Lower addressing virtual const labelUList& lowerAddr() const { return lowerAddr_; } //- Return Upper addressing virtual const labelUList& upperAddr() const { return upperAddr_; } //- Return patch addressing virtual const labelUList& patchAddr(const label i) const { return patchAddr_[i]; } virtual const labelUList& getPatchAddr(const label i) const { return patchAddr_[i]; } //- Return patch evaluation schedule virtual const lduSchedule& patchSchedule() const { return patchSchedule_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
26.790393
79
0.48802
MrAwesomeRocks
9c3199d0fe9f3ea30e284f29e8059b00b560cb84
1,088
cpp
C++
AK/MappedFile.cpp
shubhdev/serenity
9321d9d83d366ad4cf686c856063ff9ac97c18a4
[ "BSD-2-Clause" ]
4
2021-02-23T05:35:25.000Z
2021-06-08T06:11:06.000Z
AK/MappedFile.cpp
shubhdev/serenity
9321d9d83d366ad4cf686c856063ff9ac97c18a4
[ "BSD-2-Clause" ]
4
2021-04-27T20:44:44.000Z
2021-06-30T18:07:10.000Z
AK/MappedFile.cpp
shubhdev/serenity
9321d9d83d366ad4cf686c856063ff9ac97c18a4
[ "BSD-2-Clause" ]
1
2022-01-10T08:02:34.000Z
2022-01-10T08:02:34.000Z
/* * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/MappedFile.h> #include <AK/ScopeGuard.h> #include <AK/String.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> namespace AK { Result<NonnullRefPtr<MappedFile>, OSError> MappedFile::map(const String& path) { int fd = open(path.characters(), O_RDONLY | O_CLOEXEC, 0); if (fd < 0) return OSError(errno); ScopeGuard fd_close_guard = [fd] { close(fd); }; struct stat st; if (fstat(fd, &st) < 0) { auto saved_errno = errno; return OSError(saved_errno); } auto size = st.st_size; auto* ptr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); if (ptr == MAP_FAILED) return OSError(errno); return adopt_ref(*new MappedFile(ptr, size)); } MappedFile::MappedFile(void* ptr, size_t size) : m_data(ptr) , m_size(size) { } MappedFile::~MappedFile() { auto rc = munmap(m_data, m_size); VERIFY(rc == 0); } }
19.428571
78
0.627757
shubhdev
9c349d12895913e37f7dabba7864ee7f7724e541
21,610
cpp
C++
shared/ebm_native/CalculateInteractionScore.cpp
jruales/interpret
edb7418cd12865e55e352ace6c61ff5cef8e1061
[ "MIT" ]
null
null
null
shared/ebm_native/CalculateInteractionScore.cpp
jruales/interpret
edb7418cd12865e55e352ace6c61ff5cef8e1061
[ "MIT" ]
null
null
null
shared/ebm_native/CalculateInteractionScore.cpp
jruales/interpret
edb7418cd12865e55e352ace6c61ff5cef8e1061
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #include "PrecompiledHeader.h" #include <stddef.h> // size_t, ptrdiff_t #include <limits> // numeric_limits #include "ebm_native.h" #include "EbmInternal.h" #include "Logging.h" // EBM_ASSERT & LOG // feature includes #include "FeatureAtomic.h" #include "FeatureGroup.h" // dataset depends on features #include "DataSetInteraction.h" #include "CachedThreadResourcesInteraction.h" #include "InteractionDetector.h" #include "TensorTotalsSum.h" extern void BinInteraction( InteractionDetector * const pInteractionDetector, const FeatureGroup * const pFeatureGroup, HistogramBucketBase * const aHistogramBuckets #ifndef NDEBUG , const unsigned char * const aHistogramBucketsEndDebug #endif // NDEBUG ); extern FloatEbmType FindBestInteractionGainPairs( InteractionDetector * const pInteractionDetector, const FeatureGroup * const pFeatureGroup, const size_t cSamplesRequiredForChildSplitMin, HistogramBucketBase * pAuxiliaryBucketZone, HistogramBucketBase * const aHistogramBuckets #ifndef NDEBUG , const HistogramBucketBase * const aHistogramBucketsDebugCopy , const unsigned char * const aHistogramBucketsEndDebug #endif // NDEBUG ); static bool CalculateInteractionScoreInternal( CachedInteractionThreadResources * const pCachedThreadResources, InteractionDetector * const pInteractionDetector, const FeatureGroup * const pFeatureGroup, const size_t cSamplesRequiredForChildSplitMin, FloatEbmType * const pInteractionScoreReturn ) { // TODO : we NEVER use the denominator term in HistogramBucketVectorEntry when calculating interaction scores, but we're spending time calculating // it, and it's taking up precious memory. We should eliminate the denominator term HERE in our datastructures OR we should think whether we can // use the denominator as part of the gain function!!! const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses(); const bool bClassification = IsClassification(runtimeLearningTypeOrCountTargetClasses); LOG_0(TraceLevelVerbose, "Entered CalculateInteractionScoreInternal"); const size_t cDimensions = pFeatureGroup->GetCountFeatures(); EBM_ASSERT(1 <= cDimensions); // situations with 0 dimensions should have been filtered out before this function was called (but still inside the C++) size_t cAuxillaryBucketsForBuildFastTotals = 0; size_t cTotalBucketsMainSpace = 1; for(size_t iDimension = 0; iDimension < cDimensions; ++iDimension) { const size_t cBins = pFeatureGroup->GetFeatureGroupEntries()[iDimension].m_pFeature->GetCountBins(); EBM_ASSERT(2 <= cBins); // situations with 1 bin should have been filtered out before this function was called (but still inside the C++) // if cBins could be 1, then we'd need to check at runtime for overflow of cAuxillaryBucketsForBuildFastTotals // if this wasn't true then we'd have to check IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace) at runtime EBM_ASSERT(cAuxillaryBucketsForBuildFastTotals < cTotalBucketsMainSpace); // since cBins must be 2 or more, cAuxillaryBucketsForBuildFastTotals must grow slower than cTotalBucketsMainSpace, and we checked at allocation // that cTotalBucketsMainSpace would not overflow EBM_ASSERT(!IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace)); // this can overflow, but if it does then we're guaranteed to catch the overflow via the multiplication check below cAuxillaryBucketsForBuildFastTotals += cTotalBucketsMainSpace; if(IsMultiplyError(cTotalBucketsMainSpace, cBins)) { // unlike in the boosting code where we check at allocation time if the tensor created overflows on multiplication // we don't know what group of features our caller will give us for calculating the interaction scores, // so we need to check if our caller gave us a tensor that overflows multiplication LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsMultiplyError(cTotalBucketsMainSpace, cBins)"); return true; } cTotalBucketsMainSpace *= cBins; // if this wasn't true then we'd have to check IsAddError(cAuxillaryBucketsForBuildFastTotals, cTotalBucketsMainSpace) at runtime EBM_ASSERT(cAuxillaryBucketsForBuildFastTotals < cTotalBucketsMainSpace); } const size_t cAuxillaryBucketsForSplitting = 4; const size_t cAuxillaryBuckets = cAuxillaryBucketsForBuildFastTotals < cAuxillaryBucketsForSplitting ? cAuxillaryBucketsForSplitting : cAuxillaryBucketsForBuildFastTotals; if(IsAddError(cTotalBucketsMainSpace, cAuxillaryBuckets)) { LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsAddError(cTotalBucketsMainSpace, cAuxillaryBuckets)"); return true; } const size_t cTotalBuckets = cTotalBucketsMainSpace + cAuxillaryBuckets; const size_t cVectorLength = GetVectorLength(runtimeLearningTypeOrCountTargetClasses); if(GetHistogramBucketSizeOverflow(bClassification, cVectorLength)) { LOG_0( TraceLevelWarning, "WARNING CalculateInteractionScoreInternal GetHistogramBucketSizeOverflow<bClassification>(cVectorLength)" ); return true; } const size_t cBytesPerHistogramBucket = GetHistogramBucketSize(bClassification, cVectorLength); if(IsMultiplyError(cTotalBuckets, cBytesPerHistogramBucket)) { LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal IsMultiplyError(cTotalBuckets, cBytesPerHistogramBucket)"); return true; } const size_t cBytesBuffer = cTotalBuckets * cBytesPerHistogramBucket; // this doesn't need to be freed since it's tracked and re-used by the class CachedInteractionThreadResources HistogramBucketBase * const aHistogramBuckets = pCachedThreadResources->GetThreadByteBuffer1(cBytesBuffer); if(UNLIKELY(nullptr == aHistogramBuckets)) { LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal nullptr == aHistogramBuckets"); return true; } if(bClassification) { HistogramBucket<true> * const aHistogramBucketsLocal = aHistogramBuckets->GetHistogramBucket<true>(); for(size_t i = 0; i < cTotalBuckets; ++i) { HistogramBucket<true> * const pHistogramBucket = GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBucketsLocal, i); pHistogramBucket->Zero(cVectorLength); } } else { HistogramBucket<false> * const aHistogramBucketsLocal = aHistogramBuckets->GetHistogramBucket<false>(); for(size_t i = 0; i < cTotalBuckets; ++i) { HistogramBucket<false> * const pHistogramBucket = GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBucketsLocal, i); pHistogramBucket->Zero(cVectorLength); } } HistogramBucketBase * pAuxiliaryBucketZone = GetHistogramBucketByIndex(cBytesPerHistogramBucket, aHistogramBuckets, cTotalBucketsMainSpace); #ifndef NDEBUG const unsigned char * const aHistogramBucketsEndDebug = reinterpret_cast<unsigned char *>(aHistogramBuckets) + cBytesBuffer; #endif // NDEBUG BinInteraction( pInteractionDetector, pFeatureGroup, aHistogramBuckets #ifndef NDEBUG , aHistogramBucketsEndDebug #endif // NDEBUG ); #ifndef NDEBUG // make a copy of the original binned buckets for debugging purposes size_t cTotalBucketsDebug = 1; for(size_t iDimensionDebug = 0; iDimensionDebug < cDimensions; ++iDimensionDebug) { const size_t cBins = pFeatureGroup->GetFeatureGroupEntries()[iDimensionDebug].m_pFeature->GetCountBins(); EBM_ASSERT(!IsMultiplyError(cTotalBucketsDebug, cBins)); // we checked this above cTotalBucketsDebug *= cBins; } // we wouldn't have been able to allocate our main buffer above if this wasn't ok EBM_ASSERT(!IsMultiplyError(cTotalBucketsDebug, cBytesPerHistogramBucket)); HistogramBucketBase * const aHistogramBucketsDebugCopy = EbmMalloc<HistogramBucketBase>(cTotalBucketsDebug, cBytesPerHistogramBucket); if(nullptr != aHistogramBucketsDebugCopy) { // if we can't allocate, don't fail.. just stop checking const size_t cBytesBufferDebug = cTotalBucketsDebug * cBytesPerHistogramBucket; memcpy(aHistogramBucketsDebugCopy, aHistogramBuckets, cBytesBufferDebug); } #endif // NDEBUG TensorTotalsBuild( runtimeLearningTypeOrCountTargetClasses, pFeatureGroup, pAuxiliaryBucketZone, aHistogramBuckets #ifndef NDEBUG , aHistogramBucketsDebugCopy , aHistogramBucketsEndDebug #endif // NDEBUG ); if(2 == cDimensions) { LOG_0(TraceLevelVerbose, "CalculateInteractionScoreInternal Starting bin sweep loop"); FloatEbmType bestSplittingScore = FindBestInteractionGainPairs( pInteractionDetector, pFeatureGroup, cSamplesRequiredForChildSplitMin, pAuxiliaryBucketZone, aHistogramBuckets #ifndef NDEBUG , aHistogramBucketsDebugCopy , aHistogramBucketsEndDebug #endif // NDEBUG ); LOG_0(TraceLevelVerbose, "CalculateInteractionScoreInternal Done bin sweep loop"); if(nullptr != pInteractionScoreReturn) { // we started our score at zero, and didn't replace with anything lower, so it can't be below zero // if we collected a NaN value, then we kept it EBM_ASSERT(std::isnan(bestSplittingScore) || FloatEbmType { 0 } <= bestSplittingScore); EBM_ASSERT((!bClassification) || !std::isinf(bestSplittingScore)); // if bestSplittingScore was NaN we make it zero so that it's not included. If infinity, also don't include it since we overloaded something // even though bestSplittingScore shouldn't be +-infinity for classification, we check it for +-infinity // here since it's most efficient to check that the exponential is all ones, which is the case only for +-infinity and NaN, but not others // comparing to max is a good way to check for +infinity without using infinity, which can be problematic on // some compilers with some compiler settings. Using <= helps avoid optimization away because the compiler // might assume that nothing is larger than max if it thinks there's no +infinity if(UNLIKELY(UNLIKELY(std::isnan(bestSplittingScore)) || UNLIKELY(std::numeric_limits<FloatEbmType>::max() <= bestSplittingScore))) { bestSplittingScore = FloatEbmType { 0 }; } *pInteractionScoreReturn = bestSplittingScore; } } else { EBM_ASSERT(false); // we only support pairs currently LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScoreInternal 2 != cDimensions"); // TODO: handle this better if(nullptr != pInteractionScoreReturn) { // for now, just return any interactions that have other than 2 dimensions as zero, which means they won't be considered *pInteractionScoreReturn = FloatEbmType { 0 }; } } #ifndef NDEBUG free(aHistogramBucketsDebugCopy); #endif // NDEBUG LOG_0(TraceLevelVerbose, "Exited CalculateInteractionScoreInternal"); return false; } // we made this a global because if we had put this variable inside the InteractionDetector object, then we would need to dereference that before getting // the count. By making this global we can send a log message incase a bad InteractionDetector object is sent into us we only decrease the count if the // count is non-zero, so at worst if there is a race condition then we'll output this log message more times than desired, but we can live with that static int g_cLogCalculateInteractionScoreParametersMessages = 10; EBM_NATIVE_IMPORT_EXPORT_BODY IntEbmType EBM_NATIVE_CALLING_CONVENTION CalculateInteractionScore( InteractionDetectorHandle interactionDetectorHandle, IntEbmType countFeaturesInGroup, const IntEbmType * featureIndexes, IntEbmType countSamplesRequiredForChildSplitMin, FloatEbmType * interactionScoreOut ) { LOG_COUNTED_N( &g_cLogCalculateInteractionScoreParametersMessages, TraceLevelInfo, TraceLevelVerbose, "CalculateInteractionScore parameters: interactionDetectorHandle=%p, countFeaturesInGroup=%" IntEbmTypePrintf ", featureIndexes=%p, countSamplesRequiredForChildSplitMin=%" IntEbmTypePrintf ", interactionScoreOut=%p", static_cast<void *>(interactionDetectorHandle), countFeaturesInGroup, static_cast<const void *>(featureIndexes), countSamplesRequiredForChildSplitMin, static_cast<void *>(interactionScoreOut) ); InteractionDetector * pInteractionDetector = reinterpret_cast<InteractionDetector *>(interactionDetectorHandle); if(nullptr == pInteractionDetector) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore ebmInteraction cannot be nullptr"); return 1; } LOG_COUNTED_0(pInteractionDetector->GetPointerCountLogEnterMessages(), TraceLevelInfo, TraceLevelVerbose, "Entered CalculateInteractionScore"); if(countFeaturesInGroup < 0) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore countFeaturesInGroup must be positive"); return 1; } if(0 != countFeaturesInGroup && nullptr == featureIndexes) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes cannot be nullptr if 0 < countFeaturesInGroup"); return 1; } if(!IsNumberConvertable<size_t>(countFeaturesInGroup)) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore countFeaturesInGroup too large to index"); return 1; } size_t cFeaturesInGroup = static_cast<size_t>(countFeaturesInGroup); if(0 == cFeaturesInGroup) { LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore empty feature group"); if(nullptr != interactionScoreOut) { // we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer our // caler be smarter about this condition *interactionScoreOut = FloatEbmType { 0 }; } return 0; } if(0 == pInteractionDetector->GetDataSetByFeature()->GetCountSamples()) { // if there are zero samples, there isn't much basis to say whether there are interactions, so just return zero LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore zero samples"); if(nullptr != interactionScoreOut) { // we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer our // caler be smarter about this condition *interactionScoreOut = 0; } return 0; } size_t cSamplesRequiredForChildSplitMin = size_t { 1 }; // this is the min value if(IntEbmType { 1 } <= countSamplesRequiredForChildSplitMin) { cSamplesRequiredForChildSplitMin = static_cast<size_t>(countSamplesRequiredForChildSplitMin); if(!IsNumberConvertable<size_t>(countSamplesRequiredForChildSplitMin)) { // we can never exceed a size_t number of samples, so let's just set it to the maximum if we were going to overflow because it will generate // the same results as if we used the true number cSamplesRequiredForChildSplitMin = std::numeric_limits<size_t>::max(); } } else { LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScore countSamplesRequiredForChildSplitMin can't be less than 1. Adjusting to 1."); } const Feature * const aFeatures = pInteractionDetector->GetFeatures(); const IntEbmType * pFeatureIndexes = featureIndexes; const IntEbmType * const pFeatureIndexesEnd = featureIndexes + cFeaturesInGroup; do { const IntEbmType indexFeatureInterop = *pFeatureIndexes; if(indexFeatureInterop < 0) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value cannot be negative"); return 1; } if(!IsNumberConvertable<size_t>(indexFeatureInterop)) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value too big to reference memory"); return 1; } const size_t iFeatureInGroup = static_cast<size_t>(indexFeatureInterop); if(pInteractionDetector->GetCountFeatures() <= iFeatureInGroup) { if(LIKELY(nullptr != interactionScoreOut)) { *interactionScoreOut = FloatEbmType { 0 }; } LOG_0(TraceLevelError, "ERROR CalculateInteractionScore featureIndexes value must be less than the number of features"); return 1; } const Feature * const pFeature = &aFeatures[iFeatureInGroup]; if(pFeature->GetCountBins() <= 1) { if(nullptr != interactionScoreOut) { // we return the lowest value possible for the interaction score, but we don't return an error since we handle it even though we'd prefer // our caler be smarter about this condition *interactionScoreOut = 0; } LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore feature with 0/1 value"); return 0; } ++pFeatureIndexes; } while(pFeatureIndexesEnd != pFeatureIndexes); if(k_cDimensionsMax < cFeaturesInGroup) { // if we try to run with more than k_cDimensionsMax we'll exceed our memory capacity, so let's exit here instead LOG_0(TraceLevelWarning, "WARNING CalculateInteractionScore k_cDimensionsMax < cFeaturesInGroup"); return 1; } // put the pFeatureGroup object on the stack. We want to put it into a FeatureGroup object since we want to share code with boosting, // which calls things like building the tensor totals (which is templated to be compiled many times) char FeatureGroupBuffer[FeatureGroup::GetFeatureGroupCountBytes(k_cDimensionsMax)]; FeatureGroup * const pFeatureGroup = reinterpret_cast<FeatureGroup *>(&FeatureGroupBuffer); pFeatureGroup->Initialize(cFeaturesInGroup, 0); pFeatureIndexes = featureIndexes; // restart from the start FeatureGroupEntry * pFeatureGroupEntry = pFeatureGroup->GetFeatureGroupEntries(); do { const IntEbmType indexFeatureInterop = *pFeatureIndexes; EBM_ASSERT(0 <= indexFeatureInterop); EBM_ASSERT(IsNumberConvertable<size_t>(indexFeatureInterop)); // we already checked indexFeatureInterop was good above size_t iFeatureInGroup = static_cast<size_t>(indexFeatureInterop); EBM_ASSERT(iFeatureInGroup < pInteractionDetector->GetCountFeatures()); const Feature * const pFeature = &aFeatures[iFeatureInGroup]; EBM_ASSERT(2 <= pFeature->GetCountBins()); // we should have filtered out anything with 1 bin above pFeatureGroupEntry->m_pFeature = pFeature; ++pFeatureGroupEntry; ++pFeatureIndexes; } while(pFeatureIndexesEnd != pFeatureIndexes); if(ptrdiff_t { 0 } == pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses() || ptrdiff_t { 1 } == pInteractionDetector->GetRuntimeLearningTypeOrCountTargetClasses()) { LOG_0(TraceLevelInfo, "INFO CalculateInteractionScore target with 0/1 classes"); if(nullptr != interactionScoreOut) { // if there is only 1 classification target, then we can predict the outcome with 100% accuracy and there is no need for logits or // interactions or anything else. We return 0 since interactions have no benefit *interactionScoreOut = FloatEbmType { 0 }; } return 0; } // TODO : be smarter about our CachedInteractionThreadResources, otherwise why have it? CachedInteractionThreadResources * const pCachedThreadResources = CachedInteractionThreadResources::Allocate(); if(nullptr == pCachedThreadResources) { return 1; } IntEbmType ret = CalculateInteractionScoreInternal( pCachedThreadResources, pInteractionDetector, pFeatureGroup, cSamplesRequiredForChildSplitMin, interactionScoreOut ); CachedInteractionThreadResources::Free(pCachedThreadResources); if(0 != ret) { LOG_N(TraceLevelWarning, "WARNING CalculateInteractionScore returned %" IntEbmTypePrintf, ret); } if(nullptr != interactionScoreOut) { // if *interactionScoreOut was negative for floating point instability reasons, we zero it so that we don't return a negative number to our caller EBM_ASSERT(FloatEbmType { 0 } <= *interactionScoreOut); LOG_COUNTED_N( pInteractionDetector->GetPointerCountLogExitMessages(), TraceLevelInfo, TraceLevelVerbose, "Exited CalculateInteractionScore %" FloatEbmTypePrintf, *interactionScoreOut ); } else { LOG_COUNTED_0(pInteractionDetector->GetPointerCountLogExitMessages(), TraceLevelInfo, TraceLevelVerbose, "Exited CalculateInteractionScore"); } return ret; }
49.002268
222
0.741323
jruales
9c35b8ac2db3bbc1bdeff2051048e22eec55d45b
4,159
cpp
C++
BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp
mscarpiniti/ArtBook
ca74c773c7312d22329cc453f4a5a799fe2dd587
[ "MIT" ]
null
null
null
BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp
mscarpiniti/ArtBook
ca74c773c7312d22329cc453f4a5a799fe2dd587
[ "MIT" ]
null
null
null
BookSamples/Capitolo7/Filtro_Shelving_II_ordine/Filtro_Shelving_II_ordine/main.cpp
mscarpiniti/ArtBook
ca74c773c7312d22329cc453f4a5a799fe2dd587
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include "audioIO.h" #define F0 (3000) #define FB (1000) using namespace std; typedef struct { float f0; float fb; float G; float wL[2]; float wR[2]; } filtro; /* Parametri del filtro Shelving del II ordine ----------------------- */ float shelving_II_ordine(float x, float f0, float fb, float G, float *xw) { float k, d, V0, H0, a, xh; float y1, y; V0 = pow(10, G/20.0); // G è in dB H0 = V0 - 1; k = tan(M_PI * fb / (float)SAMPLE_RATE); d = -cos(2 * M_PI * f0 / (float)SAMPLE_RATE); if (G >= 0) a = (k - 1) / (k + 1); // Peak else a = (k - V0) / (k + V0); // Notch xh = x - d * (1 - a) * xw[0] + a * xw[1]; y1 = -a * xh + d * (1 - a) * xw[0] + xw[1]; xw[1] = xw[0]; xw[0] = xh; y = 0.5 * H0 * (x - y1) + x; // Peak/Notch return y; } /* Stream Callback ------------------------------------------------------ */ static int stream_Callback(const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { float *in = (float*)inputBuffer; float *out = (float*)outputBuffer; filtro *data = (filtro*)userData; float f0 = data->f0, fb = data->fb, G = data->G; float *wL = data->wL, *wR = data->wR; unsigned long i; (void)timeInfo; (void)statusFlags; for (i = 0; i<framesPerBuffer; i++) { *out++ = shelving_II_ordine(*in++, f0, fb, G, wL); *out++ = shelving_II_ordine(*in++, f0, fb, G, wR); } return paContinue; } /* Print Error ------------------------------------------------------ */ int printError(PaError p_err) { Pa_Terminate(); cout << "Si è verificato un errore" << endl << "Codice di errore: " << p_err << endl << "Messaggio di errore: " << Pa_GetErrorText(p_err) << endl; return -1; } /* Funzione MAIN ------------------------------------------------------ */ int main(int argc, char *argv[]) { PaStreamParameters outputParameters; PaStreamParameters inputParameters; PaStream *stream; PaError err; filtro *h; (void)argv; (void)argc; /* Inizializzazione di PortAudio*/ err = Pa_Initialize(); if (err != paNoError) return(printError(err)); outputParameters.device = Pa_GetDefaultOutputDevice(); /* device di default in input */ outputParameters.channelCount = NUM_CANALI; /* stereo */ outputParameters.sampleFormat = PA_SAMPLE_TYPE; /* 32 bit floating point */ outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; inputParameters.device = Pa_GetDefaultInputDevice(); /* device di default in output */ inputParameters.channelCount = NUM_CANALI; /* stereo */ inputParameters.sampleFormat = PA_SAMPLE_TYPE; /* 32 bit floating point */ inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; h = (filtro*)malloc(sizeof(filtro)); h->f0 = F0; h->fb = FB; h->G = 20; h->wL[0] = 0.0; h->wL[1] = 0.0; h->wR[0] = 0.0; h->wR[1] = 0.0; err = Pa_OpenStream(&stream, &inputParameters, &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, stream_Callback, h ); if (err != paNoError) return(printError(err)); err = Pa_StartStream(stream); if (err != paNoError) return(printError(err)); cout << "Premi ENTER per terminare il programma." << endl; getchar(); err = Pa_StopStream(stream); if (err != paNoError) return(printError(err)); err = Pa_CloseStream(stream); if (err != paNoError) return(printError(err)); Pa_Terminate(); free(h); return 0; }
27.183007
108
0.550373
mscarpiniti
9c37123e8bff55bd674904b2d77533de42dd1f15
966
cpp
C++
UVa 10738 - Riemann vs Mertens/sample/10738 - Riemann vs Mertens.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10738 - Riemann vs Mertens/sample/10738 - Riemann vs Mertens.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10738 - Riemann vs Mertens/sample/10738 - Riemann vs Mertens.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> int mu[1000005], M[1000005] = {}; int p[1005], pt = 0; void sieve() { int i, j, mark[1005] = {}; for(i = 2; i <= 1000; i++) { if(mark[i] == 0) { p[pt++] = i; for(j = i+i; j <= 1000; j += i) mark[j] = 1; } } } int main() { sieve(); mu[1] = 1, M[1] = 1; int n, i, j; for(i = 2; i <= 1000000; i++) { n = i; int cnt = 0; for(j = 0; j < pt && p[j]*p[j] <= n; j++) { if(n%p[j] == 0) { cnt++; if(n/p[j]%p[j] == 0) { cnt = -100; break; } n /= p[j]; } } if(n != 1) cnt++; if(cnt < 0) mu[i] = 0; else if(cnt&1) mu[i] = -1; else mu[i] = 1; M[i] = M[i-1] + mu[i]; } while(scanf("%d", &n) == 1 && n) printf("%8d%8d%8d\n", n, mu[n], M[n]); return 0; }
23.560976
51
0.298137
tadvi
9c37448899a230552b320e4eb37e7bf79139fa63
1,558
cpp
C++
life/lifeclient/explodingmachine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
9
2019-09-03T18:33:31.000Z
2022-02-04T04:00:02.000Z
life/lifeclient/explodingmachine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
life/lifeclient/explodingmachine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
// Author: Jonas Byström // Copyright (c) Pixel Doctrine #include "pch.h" #include "explodingmachine.h" #include "../../cure/include/contextmanager.h" #include "../../cure/include/gamemanager.h" #include "../../cure/include/health.h" #include "../projectileutil.h" namespace life { ExplodingMachine::ExplodingMachine(cure::ResourceManager* resource_manager, const str& class_id, UiCure::GameUiManager* ui_manager, Launcher* launcher): Parent(resource_manager, class_id, ui_manager), launcher_(launcher), trigger_death_frame_(-1), death_frame_delay_(1), disappear_after_death_delay_(-1), is_detonated_(false), explosive_strength_(2) { } ExplodingMachine::~ExplodingMachine() { } void ExplodingMachine::SetExplosiveStrength(float explosive_strength) { explosive_strength_ = explosive_strength; } void ExplodingMachine::SetDeathFrameDelay(int death_frame_delay) { death_frame_delay_ = death_frame_delay; } void ExplodingMachine::SetDisappearAfterDeathDelay(float disappear_delay) { disappear_after_death_delay_ = disappear_delay; } void ExplodingMachine::OnTick() { Parent::OnTick(); if (cure::Health::Get(this, 1) <= 0 && trigger_death_frame_ < 0) { trigger_death_frame_ = 0; } if (trigger_death_frame_ >= 0) { if (++trigger_death_frame_ > death_frame_delay_) { OnDie(); } } } void ExplodingMachine::OnDie() { ProjectileUtil::Detonate(this, &is_detonated_, launcher_, GetPosition(), GetVelocity(), vec3(), explosive_strength_, disappear_after_death_delay_); } loginstance(kGameContextCpp, ExplodingMachine); }
21.943662
152
0.759307
highfestiva
9c383eab4379b324dceb5df57df14d90c2349016
4,562
cpp
C++
hard/training_army/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
hard/training_army/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
hard/training_army/main.cpp
exbibyte/hr
100514dfc2a1c9b5366c12ec0a75e889132a620e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // edge struct E { int from; int to; int cap; int rev; }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, t; cin >> n >> t; int source = n + t; int sink = n + t + 1; int nodes_total = n + t + 2; vector<int> skills(n, 0); for (auto &i : skills) { cin >> i; } vector<vector<int>> adj(nodes_total); // node -> edge id in es int e_id = 0; vector<E> es; // edges // connect source and sink to skill nodes for (int i = 0; i < skills.size(); ++i) { adj[source].push_back(e_id); adj[i].push_back(e_id + 1); es.push_back( E{.from = source, .to = i, .cap = skills[i], .rev = e_id + 1}); es.push_back(E{.from = i, .to = source, .cap = 0, .rev = e_id}); e_id += 2; adj[i].push_back(e_id); adj[sink].push_back(e_id + 1); es.push_back(E{.from = i, .to = sink, .cap = 1, .rev = e_id + 1}); es.push_back(E{.from = sink, .to = i, .cap = 0, .rev = e_id}); e_id += 2; } // process trainer nodes for (int i = 0; i < t; ++i) { int l; cin >> l; vector<int> from(l, 0); for (auto &j : from) { cin >> j; j--; } cin >> l; vector<int> to(l, 0); for (auto &j : to) { cin >> j; j--; } // connect trainer nodes to other skill nodes for (auto j : from) { adj[j].push_back(e_id); adj[n + i].push_back(e_id + 1); es.push_back(E{.from = j, .to = n + i, .cap = 1, .rev = e_id + 1}); es.push_back(E{.from = n + i, .to = j, .cap = 0, .rev = e_id}); e_id += 2; } for (auto j : to) { adj[n + i].push_back(e_id); adj[j].push_back(e_id + 1); es.push_back(E{.from = n + i, .to = j, .cap = 1, .rev = e_id + 1}); es.push_back(E{.from = j, .to = n + i, .cap = 0, .rev = e_id}); e_id += 2; } } assert(e_id == es.size()); vector<int> node_levels(nodes_total); int ans = 0; while (true) { // construct level graph from residual graph fill(node_levels.begin(), node_levels.end(), -1); node_levels[source] = 0; deque<int> q{source}; while (q.size() > 0) { auto idx = q.front(); q.pop_front(); for (auto edge_id : adj[idx]) { auto edge = es[edge_id]; assert(edge.from == idx); int neighbour = edge.to; int residual = edge.cap; if ((residual > 0) && (node_levels[neighbour] == -1)) { node_levels[neighbour] = node_levels[idx] + 1; q.push_back(neighbour); } } } if (node_levels[sink] == -1) { break; } // avoid searching repeatedly for adjacent edges to a node vector<int> idx_edge_start(nodes_total, 0); // find an augmenting path auto dfs_search = [&](int cur, int par, int fwd_flow, auto f) -> int { if (cur == sink || fwd_flow == 0) { return fwd_flow; } for (int &index = idx_edge_start[cur]; index < adj[cur].size(); ++index) { int edge_id = adj[cur][index]; auto &edge = es[edge_id]; int neighbour = edge.to; assert(edge.from == cur); int residual = edge.cap; if (node_levels[cur] + 1 == node_levels[neighbour] && residual > 0) { int fwd_flow_constrained = min(fwd_flow, residual); int fwd_augment = f(neighbour, cur, fwd_flow_constrained, f); if (fwd_augment > 0) { edge.cap -= fwd_augment; es[edge.rev].cap += fwd_augment; assert(edge.cap >= 0); assert(es[edge.rev].cap >= 0); return fwd_augment; } } } return 0; }; int flow; do { flow = dfs_search(source, -1, numeric_limits<int>::max(), dfs_search); ans += flow; } while (flow > 0); } cout << ans << endl; fflush(stdout); return 0; }
26.523256
79
0.437089
exbibyte
9c38d5ddd89144f56e4bee9c565d5ec92b464176
779
cc
C++
blimp/engine/app/ui/blimp_window_tree_host.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
blimp/engine/app/ui/blimp_window_tree_host.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
blimp/engine/app/ui/blimp_window_tree_host.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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 "blimp/engine/app/ui/blimp_window_tree_host.h" #include "base/memory/ptr_util.h" #include "ui/platform_window/stub/stub_window.h" namespace blimp { namespace engine { BlimpWindowTreeHost::BlimpWindowTreeHost() : aura::WindowTreeHostPlatform() { SetPlatformWindow(base::WrapUnique(new ui::StubWindow(this))); } BlimpWindowTreeHost::~BlimpWindowTreeHost() {} void BlimpWindowTreeHost::OnAcceleratedWidgetAvailable( gfx::AcceleratedWidget widget, float device_pixel_ratio) { // Do nothing to avoid creating an output surface and gpu process. } } // namespace engine } // namespace blimp
28.851852
77
0.768935
Wzzzx
9c3b081fbe4be5f759063ecd100484698ed4247f
778
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/thread/experimental/config/inline_namespace.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
17,104
2016-12-28T07:45:54.000Z
2022-03-31T07:02:52.000Z
ios/Pods/boost-for-react-native/boost/thread/experimental/config/inline_namespace.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ios/Pods/boost-for-react-native/boost/thread/experimental/config/inline_namespace.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
3,568
2016-12-28T07:47:46.000Z
2022-03-31T02:13:19.000Z
#ifndef BOOST_THREAD_EXPERIMENTAL_CONFIG_INLINE_NAMESPACE_HPP #define BOOST_THREAD_EXPERIMENTAL_CONFIG_INLINE_NAMESPACE_HPP ////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Vicente J. Botet Escriba 2014. 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/thread for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/config.hpp> #if !defined(BOOST_NO_CXX11_INLINE_NAMESPACES) # define BOOST_THREAD_INLINE_NAMESPACE(name) inline namespace name #else # define BOOST_THREAD_INLINE_NAMESPACE(name) namespace name #endif #endif
32.416667
78
0.642674
Harshitha91
9c3e77adb7f7a6ee5e438ff5884de2ba60e39b5a
4,259
cpp
C++
src/goto-programs/show_goto_functions_json.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
null
null
null
src/goto-programs/show_goto_functions_json.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
8
2017-05-04T10:31:06.000Z
2019-02-15T10:34:48.000Z
src/goto-programs/show_goto_functions_json.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
4
2017-04-25T11:47:41.000Z
2017-05-16T08:22:25.000Z
/*******************************************************************\ Module: Goto Program Author: Thomas Kiley \*******************************************************************/ /// \file /// Goto Program #include "show_goto_functions_json.h" #include <iostream> #include <sstream> #include <util/json_irep.h> #include <util/cprover_prefix.h> #include <util/prefix.h> #include <langapi/language_util.h> #include "goto_functions.h" #include "goto_model.h" /// For outputting the GOTO program in a readable JSON format. /// \param _ns: the namespace to use to resolve names with /// \param _list_only: output only list of functions, but not their bodies show_goto_functions_jsont::show_goto_functions_jsont( const namespacet &_ns, bool _list_only) : ns(_ns), list_only(_list_only) {} /// Walks through all of the functions in the program and returns a JSON object /// representing all their functions /// \param goto_functions: the goto functions that make up the program json_objectt show_goto_functions_jsont::convert( const goto_functionst &goto_functions) { json_arrayt json_functions; const json_irept no_comments_irep_converter(false); const auto sorted = goto_functions.sorted(); for(const auto &function_entry : sorted) { const irep_idt &function_name = function_entry->first; const goto_functionst::goto_functiont &function = function_entry->second; json_objectt &json_function= json_functions.push_back(jsont()).make_object(); json_function["name"] = json_stringt(function_name); json_function["isBodyAvailable"]= jsont::json_boolean(function.body_available()); bool is_internal= has_prefix(id2string(function_name), CPROVER_PREFIX) || has_prefix(id2string(function_name), "java::array[") || has_prefix(id2string(function_name), "java::org.cprover") || has_prefix(id2string(function_name), "java::java"); json_function["isInternal"]=jsont::json_boolean(is_internal); if(list_only) continue; if(function.body_available()) { json_arrayt json_instruction_array=json_arrayt(); for(const goto_programt::instructiont &instruction : function.body.instructions) { json_objectt instruction_entry{ {"instructionId", json_stringt(instruction.to_string())}}; if(instruction.code.source_location().is_not_nil()) { instruction_entry["sourceLocation"]= json(instruction.code.source_location()); } std::ostringstream instruction_builder; function.body.output_instruction( ns, function_name, instruction_builder, instruction); instruction_entry["instruction"]= json_stringt(instruction_builder.str()); if(!instruction.code.operands().empty()) { json_arrayt operand_array; for(const exprt &operand : instruction.code.operands()) { json_objectt operand_object= no_comments_irep_converter.convert_from_irep( operand); operand_array.push_back(operand_object); } instruction_entry["operands"] = std::move(operand_array); } if(!instruction.guard.is_true()) { json_objectt guard_object= no_comments_irep_converter.convert_from_irep( instruction.guard); instruction_entry["guard"] = std::move(guard_object); } json_instruction_array.push_back(std::move(instruction_entry)); } json_function["instructions"] = std::move(json_instruction_array); } } return json_objectt({{"functions", json_functions}}); } /// Print the json object generated by /// show_goto_functions_jsont::show_goto_functions to the provided stream (e.g. /// std::cout) /// \param goto_functions: the goto functions that make up the program /// \param out: the stream to write the object to /// \param append: should a command and newline be appended to the stream before /// writing the JSON object. Defaults to true void show_goto_functions_jsont::operator()( const goto_functionst &goto_functions, std::ostream &out, bool append) { if(append) { out << ",\n"; } out << convert(goto_functions); }
30.640288
80
0.67058
mauguignard
9c40964eafc57d7d768b1756ef4265a71647a9b8
4,142
cpp
C++
Universal-Physics-mod/src/gui/interface/DropDown.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
1
2022-03-26T20:01:13.000Z
2022-03-26T20:01:13.000Z
Universal-Physics-mod/src/gui/interface/DropDown.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
null
null
null
Universal-Physics-mod/src/gui/interface/DropDown.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
1
2022-03-26T19:59:13.000Z
2022-03-26T19:59:13.000Z
#include "DropDown.h" #include "graphics/Graphics.h" #include "gui/Style.h" #include "Button.h" #include "gui/interface/Window.h" namespace ui { class DropDownWindow : public ui::Window { DropDown * dropDown; Appearance appearance; std::vector<Button> buttons; public: DropDownWindow(DropDown * dropDown): Window(dropDown->GetScreenPos() + ui::Point(-1, -1 - dropDown->optionIndex * 16), ui::Point(dropDown->Size.X+2, 1+dropDown->options.size()*16)), dropDown(dropDown), appearance(dropDown->Appearance) { int currentY = 1; for (size_t i = 0; i < dropDown->options.size(); i++) { Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), dropDown->options[i].first); tempButton->Appearance = appearance; if (i) tempButton->Appearance.Border = ui::Border(0, 1, 1, 1); auto option = dropDown->options[i].first; tempButton->SetActionCallback({ [this, option] { CloseActiveWindow(); setOption(option); SelfDestruct(); } }); AddComponent(tempButton); currentY += 16; } } void OnDraw() override { Graphics * g = GetGraphics(); g->clearrect(Position.X, Position.Y, Size.X, Size.Y); } void setOption(String option) { dropDown->SetOption(option); if (dropDown->actionCallback.change) { dropDown->actionCallback.change(); } } void OnTryExit(ExitMethod method) override { CloseActiveWindow(); SelfDestruct(); } virtual ~DropDownWindow() {} }; DropDown::DropDown(Point position, Point size): Component(position, size), isMouseInside(false), optionIndex(-1) { } void DropDown::OnMouseClick(int x, int y, unsigned int button) { DropDownWindow * newWindow = new DropDownWindow(this); newWindow->MakeActiveWindow(); } void DropDown::Draw(const Point& screenPos) { if(!drawn) { if(optionIndex!=-1) TextPosition(options[optionIndex].first); drawn = true; } Graphics * g = GetGraphics(); Point Position = screenPos; ui::Colour textColour = Appearance.TextInactive; ui::Colour borderColour = Appearance.BorderInactive; ui::Colour backgroundColour = Appearance.BackgroundInactive; if (isMouseInside) { textColour = Appearance.TextHover; borderColour = Appearance.BorderHover; backgroundColour = Appearance.BackgroundHover; } else { textColour = Appearance.TextInactive; borderColour = Appearance.BorderInactive; backgroundColour = Appearance.BackgroundInactive; } g->fillrect(Position.X-1, Position.Y-1, Size.X+2, Size.Y+2, backgroundColour.Red, backgroundColour.Green, backgroundColour.Blue, backgroundColour.Alpha); g->drawrect(Position.X, Position.Y, Size.X, Size.Y, borderColour.Red, borderColour.Green, borderColour.Blue, borderColour.Alpha); if(optionIndex!=-1) g->drawtext(Position.X+textPosition.X, Position.Y+textPosition.Y, options[optionIndex].first, textColour.Red, textColour.Green, textColour.Blue, textColour.Alpha); } void DropDown::OnMouseEnter(int x, int y) { isMouseInside = true; } void DropDown::OnMouseLeave(int x, int y) { isMouseInside = false; } std::pair<String, int> DropDown::GetOption() { if(optionIndex!=-1) { return options[optionIndex]; } return std::pair<String, int>("", -1); } void DropDown::SetOption(String option) { for (size_t i = 0; i < options.size(); i++) { if (options[i].first == option) { optionIndex = i; TextPosition(options[optionIndex].first); return; } } } void DropDown::SetOption(int option) { for (size_t i = 0; i < options.size(); i++) { if (options[i].second == option) { optionIndex = i; TextPosition(options[optionIndex].first); return; } } } void DropDown::AddOption(std::pair<String, int> option) { for (size_t i = 0; i < options.size(); i++) { if (options[i] == option) return; } options.push_back(option); } void DropDown::RemoveOption(String option) { start: for (size_t i = 0; i < options.size(); i++) { if (options[i].first == option) { if ((int)i == optionIndex) optionIndex = -1; options.erase(options.begin()+i); goto start; } } } void DropDown::SetOptions(std::vector<std::pair<String, int> > options) { this->options = options; } } /* namespace ui */
22.63388
165
0.691453
AllSafeCyberSecur1ty
9c415356cd564ee239b480467d6a04805aa4568f
2,036
cpp
C++
04/main.cpp
kmrzyglod/PRiR
eabefb4db017a2c3a8289cb04c19643358c60421
[ "MIT" ]
null
null
null
04/main.cpp
kmrzyglod/PRiR
eabefb4db017a2c3a8289cb04c19643358c60421
[ "MIT" ]
null
null
null
04/main.cpp
kmrzyglod/PRiR
eabefb4db017a2c3a8289cb04c19643358c60421
[ "MIT" ]
null
null
null
#include<iostream> #include<sys/time.h> #include<stdio.h> #include"LennardJonesPotential.h" #include"MonteCarlo.h" #include"Particles.h" using namespace std; double getTime() { struct timeval tf; gettimeofday( &tf, NULL ); return tf.tv_sec + tf.tv_usec * 0.000001; } double showTime( double last ) { double now = getTime(); printf( "--- Time report: %09.6lfsec.\n", now - last ); return now; } void calc( Particles *particles ) { LennardJonesPotential *p = new LennardJonesPotential(); MonteCarlo *mc = new MonteCarlo(); mc->setParticles(particles); mc->setPotential(p); double kBT = 0.9; cout << "START" << endl; double tStart = getTime(); double tStart0 = tStart; double Etot = mc->calcTotalPotentialEnergy(); tStart = showTime( tStart ); cout << "Etot = " << Etot << endl; for (int i = 0; i < TEMPERATURES; i++) { mc->setKBTinv(kBT); // ustalenie parametrów temperatury mc->calcMC ((int)( PARTICLES * PARTICLES_PER_TEMP_MULTI ) ); kBT += 0.1; } tStart = showTime( tStart ); // koniec pomiaru czasu double Eget = mc->getTotalPotentialEnergy(); tStart = getTime(); Etot = mc->calcTotalPotentialEnergy(); tStart = showTime( tStart ); double avrMinDist = mc->calcMinOfMinDistance(); tStart = showTime( tStart ); long *histogram = mc->getHistogram( HISTOGRAM_SIZE ); for ( int i = 0 ; i < HISTOGRAM_SIZE; i++ ) { if ( histogram[ i ]) cout << i << " " << histogram[ i ] << endl; } tStart = showTime( tStart ); cout << "Etot get = " << Eget << endl; cout << "Etot calc = " << Etot << endl; cout << "Najmniejsza odleglosc do najblizszego sasiada: " << avrMinDist << endl; cout << "Total time = " << (tStart - tStart0) << endl; } int main(int argc, char **argv) { srandom( time( NULL ) ); Particles *pa = new Particles(PARTICLES); Particles *paBackup; pa->setBoxSize( BOX_SIZE ); pa->initializePositions(BOX_SIZE, DISTANCE); paBackup = new Particles( pa ); // tu tworzona jest kopia położeń cząstek calc( pa ); }
23.674419
81
0.641945
kmrzyglod
9c41a76c899390ba3d8d99333cbc8c8ab4746494
11,100
cpp
C++
gtsam/geometry/Pose2.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
3
2020-08-13T20:25:43.000Z
2021-03-05T22:24:43.000Z
gtsam/geometry/Pose2.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
1
2020-03-02T17:39:13.000Z
2020-03-02T17:39:13.000Z
gtsam/geometry/Pose2.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
1
2020-04-18T19:27:18.000Z
2020-04-18T19:27:18.000Z
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file Pose2.cpp * @brief 2D Pose */ #include <gtsam/geometry/concepts.h> #include <gtsam/geometry/Pose2.h> #include <gtsam/base/Testable.h> #include <gtsam/base/concepts.h> #include <cmath> #include <iostream> #include <iomanip> using namespace std; namespace gtsam { /** instantiate concept checks */ GTSAM_CONCEPT_POSE_INST(Pose2); static const Rot2 R_PI_2(Rot2::fromCosSin(0., 1.)); /* ************************************************************************* */ Matrix3 Pose2::matrix() const { Matrix2 R = r_.matrix(); Matrix32 R0; R0.block<2,2>(0,0) = R; R0.block<1,2>(2,0).setZero(); Matrix31 T; T << t_.x(), t_.y(), 1.0; Matrix3 RT_; RT_.block<3,2>(0,0) = R0; RT_.block<3,1>(0,2) = T; return RT_; } /* ************************************************************************* */ void Pose2::print(const string& s) const { cout << s << "(" << t_.x() << ", " << t_.y() << ", " << r_.theta() << ")" << endl; } /* ************************************************************************* */ bool Pose2::equals(const Pose2& q, double tol) const { return equal_with_abs_tol(t_, q.t_, tol) && r_.equals(q.r_, tol); } /* ************************************************************************* */ Pose2 Pose2::Expmap(const Vector3& xi, OptionalJacobian<3, 3> H) { assert(xi.size() == 3); if (H) *H = Pose2::ExpmapDerivative(xi); const Point2 v(xi(0),xi(1)); const double w = xi(2); if (std::abs(w) < 1e-10) return Pose2(xi[0], xi[1], xi[2]); else { const Rot2 R(Rot2::fromAngle(w)); const Point2 v_ortho = R_PI_2 * v; // points towards rot center const Point2 t = (v_ortho - R.rotate(v_ortho)) / w; return Pose2(R, t); } } /* ************************************************************************* */ Vector3 Pose2::Logmap(const Pose2& p, OptionalJacobian<3, 3> H) { if (H) *H = Pose2::LogmapDerivative(p); const Rot2& R = p.r(); const Point2& t = p.t(); double w = R.theta(); if (std::abs(w) < 1e-10) return Vector3(t.x(), t.y(), w); else { double c_1 = R.c()-1.0, s = R.s(); double det = c_1*c_1 + s*s; Point2 p = R_PI_2 * (R.unrotate(t) - t); Point2 v = (w/det) * p; return Vector3(v.x(), v.y(), w); } } /* ************************************************************************* */ Pose2 Pose2::ChartAtOrigin::Retract(const Vector3& v, ChartJacobian H) { #ifdef SLOW_BUT_CORRECT_EXPMAP return Expmap(v, H); #else if (H) { *H = I_3x3; H->topLeftCorner<2,2>() = Rot2(-v[2]).matrix(); } return Pose2(v[0], v[1], v[2]); #endif } /* ************************************************************************* */ Vector3 Pose2::ChartAtOrigin::Local(const Pose2& r, ChartJacobian H) { #ifdef SLOW_BUT_CORRECT_EXPMAP return Logmap(r, H); #else if (H) { *H = I_3x3; H->topLeftCorner<2,2>() = r.rotation().matrix(); } return Vector3(r.x(), r.y(), r.theta()); #endif } /* ************************************************************************* */ // Calculate Adjoint map // Ad_pose is 3*3 matrix that when applied to twist xi, returns Ad_pose(xi) Matrix3 Pose2::AdjointMap() const { double c = r_.c(), s = r_.s(), x = t_.x(), y = t_.y(); Matrix3 rvalue; rvalue << c, -s, y, s, c, -x, 0.0, 0.0, 1.0; return rvalue; } /* ************************************************************************* */ Matrix3 Pose2::adjointMap(const Vector3& v) { // See Chirikjian12book2, vol.2, pg. 36 Matrix3 ad = Z_3x3; ad(0,1) = -v[2]; ad(1,0) = v[2]; ad(0,2) = v[1]; ad(1,2) = -v[0]; return ad; } /* ************************************************************************* */ Matrix3 Pose2::ExpmapDerivative(const Vector3& v) { double alpha = v[2]; Matrix3 J; if (std::abs(alpha) > 1e-5) { // Chirikjian11book2, pg. 36 /* !!!Warning!!! Compare Iserles05an, formula 2.42 and Chirikjian11book2 pg.26 * Iserles' right-trivialization dexpR is actually the left Jacobian J_l in Chirikjian's notation * In fact, Iserles 2.42 can be written as: * \dot{g} g^{-1} = dexpR_{q}\dot{q} * where q = A, and g = exp(A) * and the LHS is in the definition of J_l in Chirikjian11book2, pg. 26. * Hence, to compute ExpmapDerivative, we have to use the formula of J_r Chirikjian11book2, pg.36 */ double sZalpha = sin(alpha)/alpha, c_1Zalpha = (cos(alpha)-1)/alpha; double v1Zalpha = v[0]/alpha, v2Zalpha = v[1]/alpha; J << sZalpha, -c_1Zalpha, v1Zalpha + v2Zalpha*c_1Zalpha - v1Zalpha*sZalpha, c_1Zalpha, sZalpha, -v1Zalpha*c_1Zalpha + v2Zalpha - v2Zalpha*sZalpha, 0, 0, 1; } else { // Thanks to Krunal: Apply L'Hospital rule to several times to // compute the limits when alpha -> 0 J << 1,0,-0.5*v[1], 0,1, 0.5*v[0], 0,0, 1; } return J; } /* ************************************************************************* */ Matrix3 Pose2::LogmapDerivative(const Pose2& p) { Vector3 v = Logmap(p); double alpha = v[2]; Matrix3 J; if (std::abs(alpha) > 1e-5) { double alphaInv = 1/alpha; double halfCotHalfAlpha = 0.5*sin(alpha)/(1-cos(alpha)); double v1 = v[0], v2 = v[1]; J << alpha*halfCotHalfAlpha, -0.5*alpha, v1*alphaInv - v1*halfCotHalfAlpha + 0.5*v2, 0.5*alpha, alpha*halfCotHalfAlpha, v2*alphaInv - 0.5*v1 - v2*halfCotHalfAlpha, 0, 0, 1; } else { J << 1,0, 0.5*v[1], 0,1, -0.5*v[0], 0,0, 1; } return J; } /* ************************************************************************* */ Pose2 Pose2::inverse() const { return Pose2(r_.inverse(), r_.unrotate(Point2(-t_.x(), -t_.y()))); } /* ************************************************************************* */ // see doc/math.lyx, SE(2) section Point2 Pose2::transformTo(const Point2& point, OptionalJacobian<2, 3> Hpose, OptionalJacobian<2, 2> Hpoint) const { OptionalJacobian<2, 2> Htranslation = Hpose.cols<2>(0); OptionalJacobian<2, 1> Hrotation = Hpose.cols<1>(2); const Point2 q = r_.unrotate(point - t_, Hrotation, Hpoint); if (Htranslation) *Htranslation << -1.0, 0.0, 0.0, -1.0; return q; } /* ************************************************************************* */ // see doc/math.lyx, SE(2) section Point2 Pose2::transformFrom(const Point2& point, OptionalJacobian<2, 3> Hpose, OptionalJacobian<2, 2> Hpoint) const { OptionalJacobian<2, 2> Htranslation = Hpose.cols<2>(0); OptionalJacobian<2, 1> Hrotation = Hpose.cols<1>(2); const Point2 q = r_.rotate(point, Hrotation, Hpoint); if (Htranslation) *Htranslation = (Hpoint ? *Hpoint : r_.matrix()); return q + t_; } /* ************************************************************************* */ Rot2 Pose2::bearing(const Point2& point, OptionalJacobian<1, 3> Hpose, OptionalJacobian<1, 2> Hpoint) const { // make temporary matrices Matrix23 D_d_pose; Matrix2 D_d_point; Point2 d = transformTo(point, Hpose ? &D_d_pose : 0, Hpoint ? &D_d_point : 0); if (!Hpose && !Hpoint) return Rot2::relativeBearing(d); Matrix12 D_result_d; Rot2 result = Rot2::relativeBearing(d, Hpose || Hpoint ? &D_result_d : 0); if (Hpose) *Hpose = D_result_d * D_d_pose; if (Hpoint) *Hpoint = D_result_d * D_d_point; return result; } /* ************************************************************************* */ Rot2 Pose2::bearing(const Pose2& pose, OptionalJacobian<1, 3> Hpose, OptionalJacobian<1, 3> Hother) const { Matrix12 D2; Rot2 result = bearing(pose.t(), Hpose, Hother ? &D2 : 0); if (Hother) { Matrix12 H2_ = D2 * pose.r().matrix(); *Hother << H2_, Z_1x1; } return result; } /* ************************************************************************* */ double Pose2::range(const Point2& point, OptionalJacobian<1,3> Hpose, OptionalJacobian<1,2> Hpoint) const { Point2 d = point - t_; if (!Hpose && !Hpoint) return d.norm(); Matrix12 D_r_d; double r = norm2(d, D_r_d); if (Hpose) { Matrix23 D_d_pose; D_d_pose << -r_.c(), r_.s(), 0.0, -r_.s(), -r_.c(), 0.0; *Hpose = D_r_d * D_d_pose; } if (Hpoint) *Hpoint = D_r_d; return r; } /* ************************************************************************* */ double Pose2::range(const Pose2& pose, OptionalJacobian<1,3> Hpose, OptionalJacobian<1,3> Hother) const { Point2 d = pose.t() - t_; if (!Hpose && !Hother) return d.norm(); Matrix12 D_r_d; double r = norm2(d, D_r_d); if (Hpose) { Matrix23 D_d_pose; D_d_pose << -r_.c(), r_.s(), 0.0, -r_.s(), -r_.c(), 0.0; *Hpose = D_r_d * D_d_pose; } if (Hother) { Matrix23 D_d_other; D_d_other << pose.r_.c(), -pose.r_.s(), 0.0, pose.r_.s(), pose.r_.c(), 0.0; *Hother = D_r_d * D_d_other; } return r; } /* ************************************************************************* * New explanation, from scan.ml * It finds the angle using a linear method: * q = Pose2::transformFrom(p) = t + R*p * We need to remove the centroids from the data to find the rotation * using dp=[dpx;dpy] and q=[dqx;dqy] we have * |dqx| |c -s| |dpx| |dpx -dpy| |c| * | | = | | * | | = | | * | | = H_i*cs * |dqy| |s c| |dpy| |dpy dpx| |s| * where the Hi are the 2*2 matrices. Then we will minimize the criterion * J = \sum_i norm(q_i - H_i * cs) * Taking the derivative with respect to cs and setting to zero we have * cs = (\sum_i H_i' * q_i)/(\sum H_i'*H_i) * The hessian is diagonal and just divides by a constant, but this * normalization constant is irrelevant, since we take atan2. * i.e., cos ~ sum(dpx*dqx + dpy*dqy) and sin ~ sum(-dpy*dqx + dpx*dqy) * The translation is then found from the centroids * as they also satisfy cq = t + R*cp, hence t = cq - R*cp */ boost::optional<Pose2> align(const vector<Point2Pair>& pairs) { size_t n = pairs.size(); if (n<2) return boost::none; // we need at least two pairs // calculate centroids Point2 cp(0,0), cq(0,0); for(const Point2Pair& pair: pairs) { cp += pair.first; cq += pair.second; } double f = 1.0/n; cp *= f; cq *= f; // calculate cos and sin double c=0,s=0; for(const Point2Pair& pair: pairs) { Point2 dq = pair.first - cp; Point2 dp = pair.second - cq; c += dp.x() * dq.x() + dp.y() * dq.y(); s += dp.y() * dq.x() - dp.x() * dq.y(); // this works but is negative from formula above !! :-( } // calculate angle and translation double theta = atan2(s,c); Rot2 R = Rot2::fromAngle(theta); Point2 t = cq - R*cp; return Pose2(R, t); } /* ************************************************************************* */ } // namespace gtsam
32.647059
101
0.513063
kvmanohar22
9c44353560a839399919bbd570b06ce32c238e7c
2,272
cpp
C++
llarp/net/exit_info.cpp
braveheart12/loki-network
568977e3a9a6825ed67e31f2ecce55946ebd8bbf
[ "Zlib" ]
1
2021-02-10T03:41:22.000Z
2021-02-10T03:41:22.000Z
llarp/net/exit_info.cpp
tzf-key/loki-network
01b3c0363caa746abf0fa52d27ffef1c84141cc3
[ "Zlib" ]
2
2019-12-19T15:37:07.000Z
2020-01-31T19:42:28.000Z
llarp/net/exit_info.cpp
tzf-key/loki-network
01b3c0363caa746abf0fa52d27ffef1c84141cc3
[ "Zlib" ]
1
2019-10-03T10:07:30.000Z
2019-10-03T10:07:30.000Z
#ifndef _WIN32 #include <arpa/inet.h> #endif #include <net/exit_info.hpp> #include <util/bencode.h> #include <util/bits.hpp> #include <util/mem.h> #include <list> #include <string.h> namespace llarp { bool ExitInfo::BEncode(llarp_buffer_t* buf) const { char tmp[128] = {0}; if(!bencode_start_dict(buf)) return false; if(!inet_ntop(AF_INET6, address.s6_addr, tmp, sizeof(tmp))) return false; if(!BEncodeWriteDictString("a", std::string(tmp), buf)) return false; if(!inet_ntop(AF_INET6, netmask.s6_addr, tmp, sizeof(tmp))) return false; if(!BEncodeWriteDictString("b", std::string(tmp), buf)) return false; if(!BEncodeWriteDictEntry("k", pubkey, buf)) return false; if(!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); } static bool bdecode_ip_string(llarp_buffer_t* buf, in6_addr& ip) { char tmp[128] = {0}; llarp_buffer_t strbuf; if(!bencode_read_string(buf, &strbuf)) return false; if(strbuf.sz >= sizeof(tmp)) return false; memcpy(tmp, strbuf.base, strbuf.sz); tmp[strbuf.sz] = 0; return inet_pton(AF_INET6, tmp, &ip.s6_addr[0]) == 1; } bool ExitInfo::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; if(!BEncodeMaybeReadDictEntry("k", pubkey, read, k, buf)) return false; if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; if(k == "a") return bdecode_ip_string(buf, address); if(k == "b") return bdecode_ip_string(buf, netmask); return read; } std::ostream& ExitInfo::print(std::ostream& stream, int level, int spaces) const { Printer printer(stream, level, spaces); std::ostringstream ss; char tmp[128] = {0}; if(inet_ntop(AF_INET6, (void*)&address, tmp, sizeof(tmp))) ss << tmp; else return stream; ss << std::string("/"); #if defined(ANDROID) || defined(RPI) snprintf(tmp, sizeof(tmp), "%zu", llarp::bits::count_array_bits(netmask.s6_addr)); ss << tmp; #else ss << std::to_string(llarp::bits::count_array_bits(netmask.s6_addr)); #endif printer.printValue(ss.str()); return stream; } } // namespace llarp
23.42268
73
0.634683
braveheart12
9c4560a949c748ecf34ed42dfabf21bae9f16af5
17,860
hpp
C++
3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/laea.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/laea.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/laea.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Boost.Geometry - gis-projections (based on PROJ4) // Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017, 2018. // Modifications copyright (c) 2017-2018, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by Gerald Evenden (then of the USGS) // PROJ4 is maintained by Frank Warmerdam // PROJ4 is converted to Boost.Geometry by Barend Gehrels // Last updated version of proj: 5.0.0 // Original copyright notice: // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef BOOST_GEOMETRY_PROJECTIONS_LAEA_HPP #define BOOST_GEOMETRY_PROJECTIONS_LAEA_HPP #include <boost/config.hpp> #include <boost/geometry/util/math.hpp> #include <boost/math/special_functions/hypot.hpp> #include <boost/geometry/srs/projections/impl/base_static.hpp> #include <boost/geometry/srs/projections/impl/base_dynamic.hpp> #include <boost/geometry/srs/projections/impl/projects.hpp> #include <boost/geometry/srs/projections/impl/factory_entry.hpp> #include <boost/geometry/srs/projections/impl/pj_auth.hpp> #include <boost/geometry/srs/projections/impl/pj_qsfn.hpp> namespace boost { namespace geometry { namespace projections { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace laea { static const double epsilon10 = 1.e-10; enum mode_type { n_pole = 0, s_pole = 1, equit = 2, obliq = 3 }; template <typename T> struct par_laea { T sinb1; T cosb1; T xmf; T ymf; T mmf; T qp; T dd; T rq; detail::apa<T> apa; mode_type mode; }; // template class, using CRTP to implement forward/inverse template <typename T, typename Parameters> struct base_laea_ellipsoid : public base_t_fi<base_laea_ellipsoid<T, Parameters>, T, Parameters> { par_laea<T> m_proj_parm; inline base_laea_ellipsoid(const Parameters& par) : base_t_fi<base_laea_ellipsoid<T, Parameters>, T, Parameters>(*this, par) {} // FORWARD(e_forward) ellipsoid // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const { static const T half_pi = detail::half_pi<T>(); T coslam, sinlam, sinphi, q, sinb=0.0, cosb=0.0, b=0.0; coslam = cos(lp_lon); sinlam = sin(lp_lon); sinphi = sin(lp_lat); q = pj_qsfn(sinphi, this->m_par.e, this->m_par.one_es); if (this->m_proj_parm.mode == obliq || this->m_proj_parm.mode == equit) { sinb = q / this->m_proj_parm.qp; cosb = sqrt(1. - sinb * sinb); } switch (this->m_proj_parm.mode) { case obliq: b = 1. + this->m_proj_parm.sinb1 * sinb + this->m_proj_parm.cosb1 * cosb * coslam; break; case equit: b = 1. + cosb * coslam; break; case n_pole: b = half_pi + lp_lat; q = this->m_proj_parm.qp - q; break; case s_pole: b = lp_lat - half_pi; q = this->m_proj_parm.qp + q; break; } if (fabs(b) < epsilon10) { BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); } switch (this->m_proj_parm.mode) { case obliq: b = sqrt(2. / b); xy_y = this->m_proj_parm.ymf * b * (this->m_proj_parm.cosb1 * sinb - this->m_proj_parm.sinb1 * cosb * coslam); goto eqcon; break; case equit: b = sqrt(2. / (1. + cosb * coslam)); xy_y = b * sinb * this->m_proj_parm.ymf; eqcon: xy_x = this->m_proj_parm.xmf * b * cosb * sinlam; break; case n_pole: case s_pole: if (q >= 0.) { b = sqrt(q); xy_x = b * sinlam; xy_y = coslam * (this->m_proj_parm.mode == s_pole ? b : -b); } else xy_x = xy_y = 0.; break; } } // INVERSE(e_inverse) ellipsoid // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const { T cCe, sCe, q, rho, ab=0.0; switch (this->m_proj_parm.mode) { case equit: case obliq: xy_x /= this->m_proj_parm.dd; xy_y *= this->m_proj_parm.dd; rho = boost::math::hypot(xy_x, xy_y); if (rho < epsilon10) { lp_lon = 0.; lp_lat = this->m_par.phi0; return; } sCe = 2. * asin(.5 * rho / this->m_proj_parm.rq); cCe = cos(sCe); sCe = sin(sCe); xy_x *= sCe; if (this->m_proj_parm.mode == obliq) { ab = cCe * this->m_proj_parm.sinb1 + xy_y * sCe * this->m_proj_parm.cosb1 / rho; xy_y = rho * this->m_proj_parm.cosb1 * cCe - xy_y * this->m_proj_parm.sinb1 * sCe; } else { ab = xy_y * sCe / rho; xy_y = rho * cCe; } break; case n_pole: xy_y = -xy_y; BOOST_FALLTHROUGH; case s_pole: q = (xy_x * xy_x + xy_y * xy_y); if (q == 0.0) { lp_lon = 0.; lp_lat = this->m_par.phi0; return; } ab = 1. - q / this->m_proj_parm.qp; if (this->m_proj_parm.mode == s_pole) ab = - ab; break; } lp_lon = atan2(xy_x, xy_y); lp_lat = pj_authlat(asin(ab), this->m_proj_parm.apa); } static inline std::string get_name() { return "laea_ellipsoid"; } }; // template class, using CRTP to implement forward/inverse template <typename T, typename Parameters> struct base_laea_spheroid : public base_t_fi<base_laea_spheroid<T, Parameters>, T, Parameters> { par_laea<T> m_proj_parm; inline base_laea_spheroid(const Parameters& par) : base_t_fi<base_laea_spheroid<T, Parameters>, T, Parameters>(*this, par) {} // FORWARD(s_forward) spheroid // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const { static const T fourth_pi = detail::fourth_pi<T>(); T coslam, cosphi, sinphi; sinphi = sin(lp_lat); cosphi = cos(lp_lat); coslam = cos(lp_lon); switch (this->m_proj_parm.mode) { case equit: xy_y = 1. + cosphi * coslam; goto oblcon; case obliq: xy_y = 1. + this->m_proj_parm.sinb1 * sinphi + this->m_proj_parm.cosb1 * cosphi * coslam; oblcon: if (xy_y <= epsilon10) { BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); } xy_y = sqrt(2. / xy_y); xy_x = xy_y * cosphi * sin(lp_lon); xy_y *= this->m_proj_parm.mode == equit ? sinphi : this->m_proj_parm.cosb1 * sinphi - this->m_proj_parm.sinb1 * cosphi * coslam; break; case n_pole: coslam = -coslam; BOOST_FALLTHROUGH; case s_pole: if (fabs(lp_lat + this->m_par.phi0) < epsilon10) { BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); } xy_y = fourth_pi - lp_lat * .5; xy_y = 2. * (this->m_proj_parm.mode == s_pole ? cos(xy_y) : sin(xy_y)); xy_x = xy_y * sin(lp_lon); xy_y *= coslam; break; } } // INVERSE(s_inverse) spheroid // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const { static const T half_pi = detail::half_pi<T>(); T cosz=0.0, rh, sinz=0.0; rh = boost::math::hypot(xy_x, xy_y); if ((lp_lat = rh * .5 ) > 1.) { BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); } lp_lat = 2. * asin(lp_lat); if (this->m_proj_parm.mode == obliq || this->m_proj_parm.mode == equit) { sinz = sin(lp_lat); cosz = cos(lp_lat); } switch (this->m_proj_parm.mode) { case equit: lp_lat = fabs(rh) <= epsilon10 ? 0. : asin(xy_y * sinz / rh); xy_x *= sinz; xy_y = cosz * rh; break; case obliq: lp_lat = fabs(rh) <= epsilon10 ? this->m_par.phi0 : asin(cosz * this->m_proj_parm.sinb1 + xy_y * sinz * this->m_proj_parm.cosb1 / rh); xy_x *= sinz * this->m_proj_parm.cosb1; xy_y = (cosz - sin(lp_lat) * this->m_proj_parm.sinb1) * rh; break; case n_pole: xy_y = -xy_y; lp_lat = half_pi - lp_lat; break; case s_pole: lp_lat -= half_pi; break; } lp_lon = (xy_y == 0. && (this->m_proj_parm.mode == equit || this->m_proj_parm.mode == obliq)) ? 0. : atan2(xy_x, xy_y); } static inline std::string get_name() { return "laea_spheroid"; } }; // Lambert Azimuthal Equal Area template <typename Parameters, typename T> inline void setup_laea(Parameters& par, par_laea<T>& proj_parm) { static const T half_pi = detail::half_pi<T>(); T t; t = fabs(par.phi0); if (fabs(t - half_pi) < epsilon10) proj_parm.mode = par.phi0 < 0. ? s_pole : n_pole; else if (fabs(t) < epsilon10) proj_parm.mode = equit; else proj_parm.mode = obliq; if (par.es != 0.0) { double sinphi; par.e = sqrt(par.es); proj_parm.qp = pj_qsfn(1., par.e, par.one_es); proj_parm.mmf = .5 / (1. - par.es); proj_parm.apa = pj_authset<T>(par.es); switch (proj_parm.mode) { case n_pole: case s_pole: proj_parm.dd = 1.; break; case equit: proj_parm.dd = 1. / (proj_parm.rq = sqrt(.5 * proj_parm.qp)); proj_parm.xmf = 1.; proj_parm.ymf = .5 * proj_parm.qp; break; case obliq: proj_parm.rq = sqrt(.5 * proj_parm.qp); sinphi = sin(par.phi0); proj_parm.sinb1 = pj_qsfn(sinphi, par.e, par.one_es) / proj_parm.qp; proj_parm.cosb1 = sqrt(1. - proj_parm.sinb1 * proj_parm.sinb1); proj_parm.dd = cos(par.phi0) / (sqrt(1. - par.es * sinphi * sinphi) * proj_parm.rq * proj_parm.cosb1); proj_parm.ymf = (proj_parm.xmf = proj_parm.rq) / proj_parm.dd; proj_parm.xmf *= proj_parm.dd; break; } } else { if (proj_parm.mode == obliq) { proj_parm.sinb1 = sin(par.phi0); proj_parm.cosb1 = cos(par.phi0); } } } }} // namespace laea #endif // doxygen /*! \brief Lambert Azimuthal Equal Area projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Azimuthal - Spheroid - Ellipsoid \par Example \image html ex_laea.gif */ template <typename T, typename Parameters> struct laea_ellipsoid : public detail::laea::base_laea_ellipsoid<T, Parameters> { template <typename Params> inline laea_ellipsoid(Params const& , Parameters const& par) : detail::laea::base_laea_ellipsoid<T, Parameters>(par) { detail::laea::setup_laea(this->m_par, this->m_proj_parm); } }; /*! \brief Lambert Azimuthal Equal Area projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Azimuthal - Spheroid - Ellipsoid \par Example \image html ex_laea.gif */ template <typename T, typename Parameters> struct laea_spheroid : public detail::laea::base_laea_spheroid<T, Parameters> { template <typename Params> inline laea_spheroid(Params const& , Parameters const& par) : detail::laea::base_laea_spheroid<T, Parameters>(par) { detail::laea::setup_laea(this->m_par, this->m_proj_parm); } }; #ifndef DOXYGEN_NO_DETAIL namespace detail { // Static projection BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_laea, laea_spheroid, laea_ellipsoid) // Factory entry(s) BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(laea_entry, laea_spheroid, laea_ellipsoid) BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(laea_init) { BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(laea, laea_entry) } } // namespace detail #endif // doxygen } // namespace projections }} // namespace boost::geometry #endif // BOOST_GEOMETRY_PROJECTIONS_LAEA_HPP
40.590909
134
0.477548
rajeev02101987
9c45ff4fb0814473c7cb76ce0e57a7f044fb3382
2,658
cpp
C++
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/lua_helper.cpp
yatyricky/XYWE
6577f4038346c258b346865808b0e3b2730611b6
[ "Apache-2.0" ]
2
2017-11-27T11:50:20.000Z
2021-04-04T13:26:45.000Z
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/lua_helper.cpp
yatyricky/XYWE
6577f4038346c258b346865808b0e3b2730611b6
[ "Apache-2.0" ]
null
null
null
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/lua_helper.cpp
yatyricky/XYWE
6577f4038346c258b346865808b0e3b2730611b6
[ "Apache-2.0" ]
null
null
null
#include "lua_helper.h" #include "storm.h" #include <cstring> #include <base/util/unicode.h> #include <base/warcraft3/jass.h> #include <base/warcraft3/war3_searcher.h> namespace base { namespace warcraft3 { namespace lua_engine { namespace package { int searcher_storm(lua_State *L); int searcher_file(lua_State *L); } static void* l_alloc(void* /*ud*/, void* ptr, size_t /*osize*/, size_t nsize) { if (nsize == 0) { free(ptr); return NULL; } else { return realloc(ptr, nsize); } } static int panic(lua_State *L) { lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L, -1)); return 0; } uintptr_t get_random_seed() { war3_searcher& s = get_war3_searcher(); uintptr_t ptr = s.search_string("SetRandomSeed"); ptr = *(uintptr_t*)(ptr + 0x05); ptr = next_opcode(ptr, 0x8B, 6); ptr = *(uintptr_t*)(ptr + 2); return *(uintptr_t*)(*(uintptr_t*)(ptr) + 4); } lua_State* luaL_newstate2() { lua_State *L = lua_newstate2(l_alloc, NULL, get_random_seed()); if (L) lua_atpanic(L, &panic); return L; } int __cdecl searcher_preload(lua_State* L) { const char *name = luaL_checkstring(L, 1); lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD"); lua_getfield(L, -1, name); if (lua_isnil(L, -1)) /* not found? */ lua_pushfstring(L, "\n\tno field package.preload['%s']", name); return 1; } bool clear_searchers_table(lua_State* L) { lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, -1, LUA_LOADLIBNAME); if (lua_istable(L, -1)) { lua_createtable(L, 2, 0); lua_pushvalue(L, -2); lua_pushcclosure(L, searcher_preload, 1); lua_rawseti(L, -2, 1); lua_setfield(L, -2, "searchers"); lua_pop(L, 2); return true; } lua_pop(L, 2); return false; } bool insert_searchers_table(lua_State* L) { lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, -1, LUA_LOADLIBNAME); if (!lua_istable(L, -1)) { lua_pop(L, 2); return false; } lua_pushstring(L, "?;?.lua"); lua_setfield(L, -2, "path"); lua_getfield(L, -1, "searchers"); if (!lua_istable(L, -1)) { lua_pop(L, 3); return false; } for (int i = 1;; i++) { lua_rawgeti(L, -1, i); if (lua_isnil(L, -1)) { lua_pushvalue(L, -3); lua_pushcclosure(L, package::searcher_file, 1); lua_rawseti(L, -3, i); lua_pushvalue(L, -3); lua_pushcclosure(L, package::searcher_storm, 1); lua_rawseti(L, -3, i + 1); lua_pop(L, 4); return true; } lua_pop(L, 1); } } }}}
22.913793
99
0.606847
yatyricky
9c47edd0ee7c2fd984564056dbdd7887a290a433
17,345
cc
C++
util/cache.cc
paritytech/rocksdb
362c69481d18f8bf1bc59d93750dfebf4705bd2e
[ "BSD-3-Clause" ]
2
2021-04-22T06:28:43.000Z
2021-11-12T06:34:16.000Z
util/cache.cc
paritytech/rocksdb
362c69481d18f8bf1bc59d93750dfebf4705bd2e
[ "BSD-3-Clause" ]
null
null
null
util/cache.cc
paritytech/rocksdb
362c69481d18f8bf1bc59d93750dfebf4705bd2e
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "rocksdb/cache.h" #include "port/port.h" #include "util/autovector.h" #include "util/hash.h" #include "util/mutexlock.h" namespace rocksdb { Cache::~Cache() { } namespace { // LRU cache implementation // An entry is a variable length heap-allocated structure. // Entries are referenced by cache and/or by any external entity. // The cache keeps all its entries in table. Some elements // are also stored on LRU list. // // LRUHandle can be in these states: // 1. Referenced externally AND in hash table. // In that case the entry is *not* in the LRU. (refs > 1 && in_cache == true) // 2. Not referenced externally and in hash table. In that case the entry is // in the LRU and can be freed. (refs == 1 && in_cache == true) // 3. Referenced externally and not in hash table. In that case the entry is // in not on LRU and not in table. (refs >= 1 && in_cache == false) // // All newly created LRUHandles are in state 1. If you call LRUCache::Release // on entry in state 1, it will go into state 2. To move from state 1 to // state 3, either call LRUCache::Erase or LRUCache::Insert with the same key. // To move from state 2 to state 1, use LRUCache::Lookup. // Before destruction, make sure that no handles are in state 1. This means // that any successful LRUCache::Lookup/LRUCache::Insert have a matching // RUCache::Release (to move into state 2) or LRUCache::Erase (for state 3) struct LRUHandle { void* value; void (*deleter)(const Slice&, void* value); LRUHandle* next_hash; LRUHandle* next; LRUHandle* prev; size_t charge; // TODO(opt): Only allow uint32_t? size_t key_length; uint32_t refs; // a number of refs to this entry // cache itself is counted as 1 bool in_cache; // true, if this entry is referenced by the hash table uint32_t hash; // Hash of key(); used for fast sharding and comparisons char key_data[1]; // Beginning of key Slice key() const { // For cheaper lookups, we allow a temporary Handle object // to store a pointer to a key in "value". if (next == this) { return *(reinterpret_cast<Slice*>(value)); } else { return Slice(key_data, key_length); } } void Free() { assert((refs == 1 && in_cache) || (refs == 0 && !in_cache)); (*deleter)(key(), value); delete[] reinterpret_cast<char*>(this); } }; // We provide our own simple hash table since it removes a whole bunch // of porting hacks and is also faster than some of the built-in hash // table implementations in some of the compiler/runtime combinations // we have tested. E.g., readrandom speeds up by ~5% over the g++ // 4.4.3's builtin hashtable. class HandleTable { public: HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); } template <typename T> void ApplyToAllCacheEntries(T func) { for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != nullptr) { auto n = h->next_hash; assert(h->in_cache); func(h); h = n; } } } ~HandleTable() { ApplyToAllCacheEntries([](LRUHandle* h) { if (h->refs == 1) { h->Free(); } }); delete[] list_; } LRUHandle* Lookup(const Slice& key, uint32_t hash) { return *FindPointer(key, hash); } LRUHandle* Insert(LRUHandle* h) { LRUHandle** ptr = FindPointer(h->key(), h->hash); LRUHandle* old = *ptr; h->next_hash = (old == nullptr ? nullptr : old->next_hash); *ptr = h; if (old == nullptr) { ++elems_; if (elems_ > length_) { // Since each cache entry is fairly large, we aim for a small // average linked list length (<= 1). Resize(); } } return old; } LRUHandle* Remove(const Slice& key, uint32_t hash) { LRUHandle** ptr = FindPointer(key, hash); LRUHandle* result = *ptr; if (result != nullptr) { *ptr = result->next_hash; --elems_; } return result; } private: // The table consists of an array of buckets where each bucket is // a linked list of cache entries that hash into the bucket. uint32_t length_; uint32_t elems_; LRUHandle** list_; // Return a pointer to slot that points to a cache entry that // matches key/hash. If there is no such cache entry, return a // pointer to the trailing slot in the corresponding linked list. LRUHandle** FindPointer(const Slice& key, uint32_t hash) { LRUHandle** ptr = &list_[hash & (length_ - 1)]; while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) { ptr = &(*ptr)->next_hash; } return ptr; } void Resize() { uint32_t new_length = 16; while (new_length < elems_ * 1.5) { new_length *= 2; } LRUHandle** new_list = new LRUHandle*[new_length]; memset(new_list, 0, sizeof(new_list[0]) * new_length); uint32_t count = 0; for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != nullptr) { LRUHandle* next = h->next_hash; uint32_t hash = h->hash; LRUHandle** ptr = &new_list[hash & (new_length - 1)]; h->next_hash = *ptr; *ptr = h; h = next; count++; } } assert(elems_ == count); delete[] list_; list_ = new_list; length_ = new_length; } }; // A single shard of sharded cache. class LRUCache { public: LRUCache(); ~LRUCache(); // Separate from constructor so caller can easily make an array of LRUCache // if current usage is more than new capacity, the function will attempt to // free the needed space void SetCapacity(size_t capacity); // Like Cache methods, but with an extra "hash" parameter. Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)); Cache::Handle* Lookup(const Slice& key, uint32_t hash); void Release(Cache::Handle* handle); void Erase(const Slice& key, uint32_t hash); // Although in some platforms the update of size_t is atomic, to make sure // GetUsage() and GetPinnedUsage() work correctly under any platform, we'll // protect them with mutex_. size_t GetUsage() const { MutexLock l(&mutex_); return usage_; } size_t GetPinnedUsage() const { MutexLock l(&mutex_); assert(usage_ >= lru_usage_); return usage_ - lru_usage_; } void ApplyToAllCacheEntries(void (*callback)(void*, size_t), bool thread_safe); private: void LRU_Remove(LRUHandle* e); void LRU_Append(LRUHandle* e); // Just reduce the reference count by 1. // Return true if last reference bool Unref(LRUHandle* e); // Free some space following strict LRU policy until enough space // to hold (usage_ + charge) is freed or the lru list is empty // This function is not thread safe - it needs to be executed while // holding the mutex_ void EvictFromLRU(size_t charge, autovector<LRUHandle*>* deleted); // Initialized before use. size_t capacity_; // Memory size for entries residing in the cache size_t usage_; // Memory size for entries residing only in the LRU list size_t lru_usage_; // mutex_ protects the following state. // We don't count mutex_ as the cache's internal state so semantically we // don't mind mutex_ invoking the non-const actions. mutable port::Mutex mutex_; // Dummy head of LRU list. // lru.prev is newest entry, lru.next is oldest entry. // LRU contains items which can be evicted, ie reference only by cache LRUHandle lru_; HandleTable table_; }; LRUCache::LRUCache() : usage_(0), lru_usage_(0) { // Make empty circular linked list lru_.next = &lru_; lru_.prev = &lru_; } LRUCache::~LRUCache() {} bool LRUCache::Unref(LRUHandle* e) { assert(e->refs > 0); e->refs--; return e->refs == 0; } // Call deleter and free void LRUCache::ApplyToAllCacheEntries(void (*callback)(void*, size_t), bool thread_safe) { if (thread_safe) { mutex_.Lock(); } table_.ApplyToAllCacheEntries([callback](LRUHandle* h) { callback(h->value, h->charge); }); if (thread_safe) { mutex_.Unlock(); } } void LRUCache::LRU_Remove(LRUHandle* e) { assert(e->next != nullptr); assert(e->prev != nullptr); e->next->prev = e->prev; e->prev->next = e->next; e->prev = e->next = nullptr; lru_usage_ -= e->charge; } void LRUCache::LRU_Append(LRUHandle* e) { // Make "e" newest entry by inserting just before lru_ assert(e->next == nullptr); assert(e->prev == nullptr); e->next = &lru_; e->prev = lru_.prev; e->prev->next = e; e->next->prev = e; lru_usage_ += e->charge; } void LRUCache::EvictFromLRU(size_t charge, autovector<LRUHandle*>* deleted) { while (usage_ + charge > capacity_ && lru_.next != &lru_) { LRUHandle* old = lru_.next; assert(old->in_cache); assert(old->refs == 1); // LRU list contains elements which may be evicted LRU_Remove(old); table_.Remove(old->key(), old->hash); old->in_cache = false; Unref(old); usage_ -= old->charge; deleted->push_back(old); } } void LRUCache::SetCapacity(size_t capacity) { autovector<LRUHandle*> last_reference_list; { MutexLock l(&mutex_); capacity_ = capacity; EvictFromLRU(0, &last_reference_list); } // we free the entries here outside of mutex for // performance reasons for (auto entry : last_reference_list) { entry->Free(); } } Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) { MutexLock l(&mutex_); LRUHandle* e = table_.Lookup(key, hash); if (e != nullptr) { assert(e->in_cache); if (e->refs == 1) { LRU_Remove(e); } e->refs++; } return reinterpret_cast<Cache::Handle*>(e); } void LRUCache::Release(Cache::Handle* handle) { LRUHandle* e = reinterpret_cast<LRUHandle*>(handle); bool last_reference = false; { MutexLock l(&mutex_); last_reference = Unref(e); if (last_reference) { usage_ -= e->charge; } if (e->refs == 1 && e->in_cache) { // The item is still in cache, and nobody else holds a reference to it if (usage_ > capacity_) { // the cache is full // The LRU list must be empty since the cache is full assert(lru_.next == &lru_); // take this opportunity and remove the item table_.Remove(e->key(), e->hash); e->in_cache = false; Unref(e); usage_ -= e->charge; last_reference = true; } else { // put the item on the list to be potentially freed LRU_Append(e); } } } // free outside of mutex if (last_reference) { e->Free(); } } Cache::Handle* LRUCache::Insert( const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) { // Allocate the memory here outside of the mutex // If the cache is full, we'll have to release it // It shouldn't happen very often though. LRUHandle* e = reinterpret_cast<LRUHandle*>( new char[sizeof(LRUHandle) - 1 + key.size()]); autovector<LRUHandle*> last_reference_list; e->value = value; e->deleter = deleter; e->charge = charge; e->key_length = key.size(); e->hash = hash; e->refs = 2; // One from LRUCache, one for the returned handle e->next = e->prev = nullptr; e->in_cache = true; memcpy(e->key_data, key.data(), key.size()); { MutexLock l(&mutex_); // Free the space following strict LRU policy until enough space // is freed or the lru list is empty EvictFromLRU(charge, &last_reference_list); // insert into the cache // note that the cache might get larger than its capacity if not enough // space was freed LRUHandle* old = table_.Insert(e); usage_ += e->charge; if (old != nullptr) { old->in_cache = false; if (Unref(old)) { usage_ -= old->charge; // old is on LRU because it's in cache and its reference count // was just 1 (Unref returned 0) LRU_Remove(old); last_reference_list.push_back(old); } } } // we free the entries here outside of mutex for // performance reasons for (auto entry : last_reference_list) { entry->Free(); } return reinterpret_cast<Cache::Handle*>(e); } void LRUCache::Erase(const Slice& key, uint32_t hash) { LRUHandle* e; bool last_reference = false; { MutexLock l(&mutex_); e = table_.Remove(key, hash); if (e != nullptr) { last_reference = Unref(e); if (last_reference) { usage_ -= e->charge; } if (last_reference && e->in_cache) { LRU_Remove(e); } e->in_cache = false; } } // mutex not held here // last_reference will only be true if e != nullptr if (last_reference) { e->Free(); } } static int kNumShardBits = 4; // default values, can be overridden class ShardedLRUCache : public Cache { private: LRUCache* shards_; port::Mutex id_mutex_; port::Mutex capacity_mutex_; uint64_t last_id_; int num_shard_bits_; size_t capacity_; static inline uint32_t HashSlice(const Slice& s) { return Hash(s.data(), s.size(), 0); } uint32_t Shard(uint32_t hash) { // Note, hash >> 32 yields hash in gcc, not the zero we expect! return (num_shard_bits_ > 0) ? (hash >> (32 - num_shard_bits_)) : 0; } public: ShardedLRUCache(size_t capacity, int num_shard_bits) : last_id_(0), num_shard_bits_(num_shard_bits), capacity_(capacity) { int num_shards = 1 << num_shard_bits_; shards_ = new LRUCache[num_shards]; const size_t per_shard = (capacity + (num_shards - 1)) / num_shards; for (int s = 0; s < num_shards; s++) { shards_[s].SetCapacity(per_shard); } } virtual ~ShardedLRUCache() { delete[] shards_; } virtual void SetCapacity(size_t capacity) override { int num_shards = 1 << num_shard_bits_; const size_t per_shard = (capacity + (num_shards - 1)) / num_shards; MutexLock l(&capacity_mutex_); for (int s = 0; s < num_shards; s++) { shards_[s].SetCapacity(per_shard); } capacity_ = capacity; } virtual Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) override { const uint32_t hash = HashSlice(key); return shards_[Shard(hash)].Insert(key, hash, value, charge, deleter); } virtual Handle* Lookup(const Slice& key) override { const uint32_t hash = HashSlice(key); return shards_[Shard(hash)].Lookup(key, hash); } virtual void Release(Handle* handle) override { LRUHandle* h = reinterpret_cast<LRUHandle*>(handle); shards_[Shard(h->hash)].Release(handle); } virtual void Erase(const Slice& key) override { const uint32_t hash = HashSlice(key); shards_[Shard(hash)].Erase(key, hash); } virtual void* Value(Handle* handle) override { return reinterpret_cast<LRUHandle*>(handle)->value; } virtual uint64_t NewId() override { MutexLock l(&id_mutex_); return ++(last_id_); } virtual size_t GetCapacity() const override { return capacity_; } virtual size_t GetUsage() const override { // We will not lock the cache when getting the usage from shards. int num_shards = 1 << num_shard_bits_; size_t usage = 0; for (int s = 0; s < num_shards; s++) { usage += shards_[s].GetUsage(); } return usage; } virtual size_t GetUsage(Handle* handle) const override { return reinterpret_cast<LRUHandle*>(handle)->charge; } virtual size_t GetPinnedUsage() const override { // We will not lock the cache when getting the usage from shards. int num_shards = 1 << num_shard_bits_; size_t usage = 0; for (int s = 0; s < num_shards; s++) { usage += shards_[s].GetPinnedUsage(); } return usage; } virtual void DisownData() override { shards_ = nullptr; } virtual void ApplyToAllCacheEntries(void (*callback)(void*, size_t), bool thread_safe) override { int num_shards = 1 << num_shard_bits_; for (int s = 0; s < num_shards; s++) { shards_[s].ApplyToAllCacheEntries(callback, thread_safe); } } }; } // end anonymous namespace shared_ptr<Cache> NewLRUCache(size_t capacity) { return NewLRUCache(capacity, kNumShardBits); } shared_ptr<Cache> NewLRUCache(size_t capacity, int num_shard_bits) { if (num_shard_bits >= 20) { return nullptr; // the cache cannot be sharded into too many fine pieces } return std::make_shared<ShardedLRUCache>(capacity, num_shard_bits); } } // namespace rocksdb
29.751286
79
0.638109
paritytech
9c49f33692cc3edf605aac4fa0e330872ad59fd9
16,375
cpp
C++
all/native/components/LicenseManager.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
155
2016-10-20T08:39:13.000Z
2022-02-27T14:08:32.000Z
all/native/components/LicenseManager.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
448
2016-10-20T12:33:06.000Z
2022-03-22T14:42:58.000Z
all/native/components/LicenseManager.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
64
2016-12-05T16:04:31.000Z
2022-02-07T09:36:22.000Z
#include "LicenseManager.h" #include "core/BinaryData.h" #include "components/Exceptions.h" #include "components/LicenseManagerListener.h" #include "network/HTTPClient.h" #include "utils/PlatformUtils.h" #include "utils/NetworkUtils.h" #include "utils/Log.h" #include <chrono> #include <cstdlib> #include <ctime> #include <iomanip> #include <regex> #include <sstream> #include <tuple> #include <unordered_map> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <picojson/picojson.h> #include <botan/botan_all.h> namespace carto { bool LicenseManager::registerLicense(const std::string& licenseKey, const std::shared_ptr<LicenseManagerListener>& listener) { bool result = false; std::unordered_map<std::string, std::string> parameters; try { std::lock_guard<std::mutex> lock(_mutex); parameters = DecodeLicense(licenseKey); result = verifyLicenseParameters(parameters); if (!result) { _parameters["watermark"] = "expired"; } } catch (const std::exception& ex) { std::lock_guard<std::mutex> lock(_mutex); _parameters["watermark"] = "expired"; Log::Errorf("LicenseManager::registerLicense: Invalid license: %s", ex.what()); return false; } auto it = parameters.find("onlineLicense"); if (it != parameters.end()) { if (!it->second.empty() && it->second != "0") { std::lock_guard<std::mutex> updateThreadsLock(_updateThreadsMutex); // Keep the listener reference as DirectorPtr as we need it before then method returns DirectorPtr<LicenseManagerListener> listenerPtr(listener); std::thread updateThread([listenerPtr, parameters, this]() { std::string updatedLicenseKey = updateOnlineLicense(); // Call listener with updated license string if (!updatedLicenseKey.empty()) { if (listenerPtr) { listenerPtr->onLicenseUpdated(updatedLicenseKey); } } }); _updateThreads.push_back(std::move(updateThread)); } } return result; } bool LicenseManager::getParameter(const std::string& name, std::string& value, bool wait) const { if (wait) { // Wait until all update threads have finished std::lock_guard<std::mutex> lock(_updateThreadsMutex); while (!_updateThreads.empty()) { _updateThreads.front().join(); _updateThreads.erase(_updateThreads.begin()); } } // Try to get the parameter std::lock_guard<std::mutex> lock(_mutex); auto it = _parameters.find(name); if (it != _parameters.end()) { value = it->second; return true; } return false; } bool LicenseManager::getPackageEncryptionKey(std::string& key) const { key = PACKAGE_ENCRYPTION_KEY; return true; } LicenseManager& LicenseManager::GetInstance() { static LicenseManager instance; return instance; } LicenseManager::LicenseManager() : _appId(), _parameters(), _mutex(), _updateThreads(), _updateThreadsMutex() { _parameters["watermark"] = "development"; } LicenseManager::~LicenseManager() { for (std::thread& updateThread : _updateThreads) { updateThread.join(); } } bool LicenseManager::GetProductId(std::string& appParam, std::string& sdkProduct) { switch (PlatformUtils::GetPlatformType()) { case PlatformType::PLATFORM_TYPE_ANDROID: appParam = "packageName"; sdkProduct = "sdk-android-"; break; case PlatformType::PLATFORM_TYPE_IOS: appParam = "bundleIdentifier"; sdkProduct = "sdk-ios-"; break; case PlatformType::PLATFORM_TYPE_XAMARIN_ANDROID: appParam = "packageName"; sdkProduct = "sdk-xamarin-android-"; break; case PlatformType::PLATFORM_TYPE_XAMARIN_IOS: appParam = "bundleIdentifier"; sdkProduct = "sdk-xamarin-ios-"; break; case PlatformType::PLATFORM_TYPE_WINDOWS_PHONE: appParam = "productId"; sdkProduct = "sdk-winphone-"; break; default: return false; } sdkProduct += PRODUCT_VERSION; return true; } bool LicenseManager::MatchProduct(const std::string& productTemplate, const std::string& product) { std::vector<std::string> productREs; boost::split(productREs, productTemplate, boost::is_any_of(",")); for (std::string productRE : productREs) { productRE = boost::replace_all_copy(boost::replace_all_copy(productRE, ".", "[.]"), "*", ".*"); if (std::regex_match(product, std::regex(productRE))) { return true; } } return false; } bool LicenseManager::MatchAppId(const std::string& appIdTemplate, const std::string& appId) { std::vector<std::string> appIdREs; boost::split(appIdREs, appIdTemplate, boost::is_any_of(",")); for (std::string appIdRE : appIdREs) { appIdRE = boost::replace_all_copy(boost::replace_all_copy(appIdRE, ".", "[.]"), "*", ".*"); if (std::regex_match(appId, std::regex(appIdRE))) { return true; } } return false; } std::unordered_map<std::string, std::string> LicenseManager::DecodeLicense(const std::string& licenseKey) { // Unsalt and decode the license string if (licenseKey.substr(0, LICENSE_PREFIX.size()) != LICENSE_PREFIX) { throw ParseException("Invalid license prefix"); } Botan::secure_vector<std::uint8_t> decodedLicense = Botan::base64_decode(licenseKey.substr(LICENSE_PREFIX.size())); std::string license(decodedLicense.begin(), decodedLicense.end()); std::string line; std::stringstream ss(license); // Extract the encoded signature std::string encodedSignature; while (std::getline(ss, line)) { if (line.empty()) { break; } encodedSignature += line; } if (!line.empty()) { throw ParseException("Invalid license, expecting empty line"); } // Decode signature. Note: it is in DER-format and needs to be converted to raw 40-byte signature Botan::secure_vector<std::uint8_t> decodedSignature = Botan::base64_decode(encodedSignature); std::vector<std::uint8_t> signature(decodedSignature.begin(), decodedSignature.end()); // Extract license Parameters std::vector<std::uint8_t> message; std::unordered_map<std::string, std::string> parameters; while (std::getline(ss, line)) { if (line.empty()) { break; } std::string::size_type pos = line.find('='); if (pos != std::string::npos) { parameters[line.substr(0, pos)] = line.substr(pos + 1); } message.insert(message.end(), line.begin(), line.end()); } // Decode the DSA public key Botan::secure_vector<std::uint8_t> decodedPublicKey(Botan::base64_decode(PUBLIC_KEY)); Botan::AlgorithmIdentifier algId; std::vector<std::uint8_t> keyBits; Botan::BER_Decoder(decodedPublicKey).start_cons(Botan::SEQUENCE).decode(algId).decode(keyBits, Botan::BIT_STRING).end_cons(); std::unique_ptr<Botan::Public_Key> publicKey(new Botan::DSA_PublicKey(algId, keyBits)); // Check signature Botan::PK_Verifier verifier(*publicKey, "EMSA1(SHA1)", Botan::Signature_Format::DER_SEQUENCE); bool result = verifier.verify_message(message, signature); if (!result) { throw GenericException("Signature validation failed", ss.str()); } // Success return parameters; } bool LicenseManager::verifyLicenseParameters(const std::unordered_map<std::string, std::string>& parameters) { std::string appParam, sdkProduct; if (!GetProductId(appParam, sdkProduct)) { throw GenericException("Unsupported platform"); } // Get the license app identifier auto it = parameters.find(appParam); if (it != parameters.end()) { _appId = it->second; } else { throw GenericException("No app identifier in license"); } // Check the app identifier std::string appId = PlatformUtils::GetAppIdentifier(); if (!MatchAppId(it->second, appId)) { throw GenericException("Invalid (mismatching) app identifier: expected '" + it->second + "', actual '" + appId + "'"); } // Construct the name of this product it = parameters.find("products"); if (it == parameters.end()) { throw GenericException("No products in license"); } // Check the product name if (!MatchProduct(it->second, sdkProduct)) { throw GenericException("Invalid (mismatching) product: : expected '" + it->second + "', actual '" + sdkProduct + "'"); } // Check for additional required licenses #ifdef _CARTO_GDAL_SUPPORT if (!MatchProduct(it->second, "sdk-gisextension")) { Log::Warnf("License does not support GIS extension"); } #endif // Check the watermark type, we also use this as 'license type' it = parameters.find("watermark"); if (it == parameters.end()) { throw GenericException("Watermark not defined in license"); } // Check the license valid until date, if it exists bool valid = true; it = parameters.find("validUntil"); if (it != parameters.end()) { // Extract license date std::vector<int> expirationDate; for (auto it2 = boost::make_split_iterator(it->second, boost::token_finder(boost::is_any_of("-"))); it2 != boost::split_iterator<std::string::const_iterator>(); it2++) { try { expirationDate.push_back(boost::lexical_cast<int>(*it2)); } catch (const boost::bad_lexical_cast&) { throw GenericException("Invalid date in license"); } } // Get current date std::time_t timeT(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); std::tm tm = { 0 }; #ifdef _WIN32 _gmtime64_s(&tm, &timeT); #else gmtime_r(&timeT, &tm); #endif std::vector<int> currentDate; currentDate.push_back(tm.tm_year + 1900); currentDate.push_back(tm.tm_mon + 1); currentDate.push_back(tm.tm_mon); // Compare dates if (expirationDate < currentDate) { Log::Errorf("LicenseManager::verifyLicenseParameters: License is expired, valid until: %s", it->second.c_str()); valid = false; } } // Store license type _parameters = parameters; return valid; } std::string LicenseManager::updateOnlineLicense() { // Request new license from server std::map<std::string, std::string> params; params["device"] = PlatformUtils::GetDeviceId(); params["platform"] = PlatformUtils::GetPlatformId(); std::string url = NetworkUtils::BuildURLFromParameters(LICENSE_SERVICE_URL + NetworkUtils::URLEncode(PlatformUtils::GetAppIdentifier()) + "/getLicense", params); std::shared_ptr<BinaryData> responseData; Log::Debug("LicenseManager::updateOnlineLicense: Requesting updated license"); try { HTTPClient client(false); client.setTimeout(LICENSESERVER_TIMEOUT); std::map<std::string, std::string> requestHeaders; std::map<std::string, std::string> responseHeaders; if (client.get(url, requestHeaders, responseHeaders, responseData) != 0) { std::string result; if (responseData) { result = std::string(reinterpret_cast<const char*>(responseData->data()), responseData->size()); } Log::Warnf("LicenseManager::updateOnlineLicense: Failed to update license: %s", result.c_str()); return std::string(); } } catch (const std::exception& ex) { Log::Warnf("LicenseManager::updateOnlineLicense: Exception while updating license: %s", ex.what()); return std::string(); } Log::Debug("LicenseManager::updateOnlineLicense: Received updated license"); std::string licenseKey; if (responseData) { std::string responseString = std::string(reinterpret_cast<const char*>(responseData->data()), responseData->size()); picojson::value responseDoc; std::string err = picojson::parse(responseDoc, responseString); if (!err.empty()) { Log::Warnf("LicenseManager::updateOnlineLicense: Illegal response: %s", err.c_str()); return std::string(); } if (responseDoc.is<picojson::value::object>()) { const picojson::value& licenseKeyValue = responseDoc.get("license_key"); if (licenseKeyValue.is<std::string>()) { licenseKey = licenseKeyValue.get<std::string>(); } else { std::string message = "(Unknown error)"; const picojson::value& messageValue = responseDoc.get("license_key"); if (messageValue.is<std::string>()) { message = messageValue.get<std::string>(); } Log::Warnf("LicenseManager::updateOnlineLicense: Received error: %s", message.c_str()); return std::string(); } } else { Log::Warnf("LicenseManager::updateOnlineLicense: Illegal response, expecting object"); return std::string(); } } std::lock_guard<std::mutex> lock(_mutex); bool result = false; std::unordered_map<std::string, std::string> parameters; try { parameters = DecodeLicense(licenseKey); result = verifyLicenseParameters(parameters); if (result) { Log::Info("LicenseManager::updateOnlineLicense: License updated successfully"); } else { _parameters["watermark"] = "expired"; } } catch (const std::exception& ex) { _parameters["watermark"] = "expired"; Log::Errorf("LicenseManager::updateOnlineLicense: Invalid license: %s", ex.what()); return std::string(); } return licenseKey; } const int LicenseManager::LICENSESERVER_TIMEOUT = 5000; const std::string LicenseManager::LICENSE_PREFIX = "X"; const std::string LicenseManager::LICENSE_SERVICE_URL = "https://mobile-licenseserver.carto.com/api/"; const std::string LicenseManager::PUBLIC_KEY = "MIIBtjCCASsGByqGSM44BAEwggEeAoGBAIlFs9OqwdM4lcfhXQVCyYDzPc6rO6sbtlKuEYa/uSzeuk1tvYcGybBwB3mYLYvOh0Qd/65TUO6rYI9xTAHK0HtjGj+XLaNDiP4eEvaVfg2fhX26XDdaAGXfKWKCHKiZ0cWLnBtTap2woVvSt6TLxcxrDnwG9mrL3Lt06rflF4oJAhUAyWhMdWcGzgq37TUJcKauhX7OEHcCgYAsXe5Q9JRA3yQsAGijSifQS8Pth1FfF69dU7VUeYD55VZ5x4UVAQP+wg7K5e6RQgJpaL1R4duVkFRgr3RuTwevv1szi/3ENiIQW4vNhPxc/sN+Y2YdlNnguOhV2LEcYmneX+F5cb2UXQZBBDhVgEtU7c9bxyA6tSwKuC70EqfZSQOBhAACgYAzp7pUQ1XxR79N8NbaB1PUPE7n1bZdFLF1QsK9thjL4Q3dbg6fub3qZfSPL286nZjfD+15oya1ORFKwSplindHNx6vSL+AmNhI4GYdyIasPnLAqCV9rIMTgQ+RfmyWDvSLxSDVqWqA83M6m/FFuWMKWKqMOEueJZTwrr/HNNTk+w=="; const std::string LicenseManager::PACKAGE_ENCRYPTION_KEY = "Hkz2jexmz9"; const std::string LicenseManager::PRODUCT_VERSION = "4.0.0"; }
40.532178
646
0.596519
ShaneCoufreur
9c4abf66180196da6beb3be80bdd0f2438c3ca2d
1,527
cpp
C++
gra.cpp
arokasprz100/Warsztat---niby-gra
5b6a76315501a52401469d3c1316df41f785f5b4
[ "MIT" ]
null
null
null
gra.cpp
arokasprz100/Warsztat---niby-gra
5b6a76315501a52401469d3c1316df41f785f5b4
[ "MIT" ]
null
null
null
gra.cpp
arokasprz100/Warsztat---niby-gra
5b6a76315501a52401469d3c1316df41f785f5b4
[ "MIT" ]
null
null
null
#include <cstdlib> #include <ctime> #include "gra.h" #include "kreacjaPostaci.h" #include "walka.h" #include "poSmierci.h" #include "czyJeszczeRaz.h" #include "zwolnijPamiec.h" void glownaPetlaGry() { srand(time(0)); char *imieBohatera=0; int atakFizyczny=0; int obronaFizyczna=0; int atakMagiczny=0; int obronaMagiczna=0; int zycie=0; do{ bool czyPrzezylaNarodziny=kreacjaPostaci (&imieBohatera, atakFizyczny, obronaFizyczna, atakMagiczny, obronaMagiczna, zycie); int * atkfizZabitych=0; int * obrfizZabitych=0; int * atkmagZabitych=0; int * obrmagZabitych=0; int * zycieZabitych=0; int zabojcaGracza[5]={0}; if (czyPrzezylaNarodziny==true) { int licznikZabitychPotworow=walka(imieBohatera, atakFizyczny, obronaFizyczna, atakMagiczny, obronaMagiczna, zycie, &atkfizZabitych, &obrfizZabitych, &atkmagZabitych, &obrmagZabitych, &zycieZabitych, &zabojcaGracza); poSmierci (licznikZabitychPotworow, &atkfizZabitych, &obrfizZabitych, &atkmagZabitych, &obrmagZabitych, &zycieZabitych, imieBohatera, atakFizyczny, obronaFizyczna, atakMagiczny, obronaMagiczna, zycie, zabojcaGracza ); } zwolnijPamiec(&imieBohatera, &atkfizZabitych, &obrfizZabitych, &atkmagZabitych, &obrmagZabitych, &zycieZabitych ); }while (czyJeszczeRaz()==true); }
31.163265
145
0.639162
arokasprz100
9c4b32435f73e16e3c625751edcb717c87c70655
1,402
cpp
C++
CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp
Idhrendur/CK3toEU4
25137130f14d78ade8962dfc87ff9c4fc237973d
[ "MIT" ]
1
2020-09-03T00:08:27.000Z
2020-09-03T00:08:27.000Z
CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp
PheonixScale9094/CK3toEU4
fcf891880ec6cc5cbafbb4d249b5c9f6528f9fd0
[ "MIT" ]
null
null
null
CK3toEU4/Source/Mappers/ReligionGroupScraper/ReligionGroupScraper.cpp
PheonixScale9094/CK3toEU4
fcf891880ec6cc5cbafbb4d249b5c9f6528f9fd0
[ "MIT" ]
null
null
null
#include "ReligionGroupScraper.h" #include "Log.h" #include "OSCompatibilityLayer.h" #include "ParserHelpers.h" #include "ReligionGroupScraping.h" #include "CommonRegexes.h" mappers::ReligionGroupScraper::ReligionGroupScraper() { LOG(LogLevel::Info) << "-> Scraping religion hierarchy."; registerKeys(); for (const auto& fileName: commonItems::GetAllFilesInFolder("blankmod/output/common/religions/")) parseFile("blankmod/output/common/religions/" + fileName); clearRegisteredKeywords(); LOG(LogLevel::Info) << "<> Loaded " << religionGroups.size() << " religion groups."; } mappers::ReligionGroupScraper::ReligionGroupScraper(std::istream& theStream) { registerKeys(); parseStream(theStream); clearRegisteredKeywords(); } void mappers::ReligionGroupScraper::registerKeys() { registerRegex(commonItems::catchallRegex, [this](const std::string& religionGroupName, std::istream& theStream) { const auto religions = ReligionGroupScraping(theStream); const auto& foundReligions = religions.getReligionNames(); religionGroups[religionGroupName].insert(foundReligions.begin(), foundReligions.end()); }); } std::optional<std::string> mappers::ReligionGroupScraper::getReligionGroupForReligion(const std::string& religion) const { for (const auto& religionGroupItr: religionGroups) if (religionGroupItr.second.count(religion)) return religionGroupItr.first; return std::nullopt; }
34.195122
120
0.773894
Idhrendur
9c4b479239405c04bfcbf0d94cc51ed6eeb742e0
1,934
cpp
C++
tests/cxx/isce3/cuda/core/device.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
64
2019-08-06T19:22:22.000Z
2022-03-20T17:11:46.000Z
tests/cxx/isce3/cuda/core/device.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
8
2020-09-01T22:46:53.000Z
2021-11-04T00:05:28.000Z
tests/cxx/isce3/cuda/core/device.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
29
2019-08-05T21:40:55.000Z
2022-03-23T00:17:03.000Z
#include <gtest/gtest.h> #include <isce3/cuda/core/Device.h> #include <isce3/except/Error.h> using isce3::cuda::core::Device; using isce3::cuda::core::getDevice; using isce3::cuda::core::getDeviceCount; using isce3::cuda::core::setDevice; using isce3::except::InvalidArgument; struct DeviceTest : public testing::Test { void SetUp() override { count = getDeviceCount(); EXPECT_GE(count, 1); } int count = 0; }; TEST_F(DeviceTest, Device) { for (int id = 0; id < count; ++id) { const Device device(id); EXPECT_EQ(device.id(), id); std::cout << "Device " << device.id() << std::endl << "--------" << std::endl << "name: " << device.name() << std::endl << "compute: " << device.computeCapability() << std::endl << "total mem (bytes): " << device.totalGlobalMem() << std::endl; EXPECT_NE(device.name(), ""); EXPECT_GT(device.totalGlobalMem(), 0); const auto compute = device.computeCapability(); EXPECT_GE(compute.major, 1); EXPECT_GE(compute.minor, 0); } } TEST_F(DeviceTest, InvalidDevice) { EXPECT_THROW({ const Device device(-1); }, InvalidArgument); EXPECT_THROW({ const Device device(count); }, InvalidArgument); } TEST_F(DeviceTest, GetDevice) { const Device device = getDevice(); EXPECT_GE(device.id(), 0); } TEST_F(DeviceTest, SetDevice) { for (int id = 0; id < count; ++id) { const Device device(id); setDevice(id); EXPECT_EQ(getDevice(), device); } } TEST_F(DeviceTest, Comparison) { const Device device1(0); const Device device2(0); EXPECT_TRUE(device1 == device2); if (count > 1) { const Device device3(1); EXPECT_TRUE(device1 != device3); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
23.585366
83
0.592554
piyushrpt
9c4d1a960f8b1f2e0db4a1a94702bc667461376c
12,798
cc
C++
dali/pipeline/operators/reader/coco_reader_op.cc
klecki/DALI
a101e0065ae568c8b01931ed65babf40728f8360
[ "ECL-2.0", "Apache-2.0" ]
2
2019-03-24T17:18:58.000Z
2021-01-19T09:58:15.000Z
dali/pipeline/operators/reader/coco_reader_op.cc
Omar-Belghaouti/DALI
3aa1b44349cb94f25a35050bbf33c001049851c7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
dali/pipeline/operators/reader/coco_reader_op.cc
Omar-Belghaouti/DALI
3aa1b44349cb94f25a35050bbf33c001049851c7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright (c) 2017-2018, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "dali/pipeline/operators/reader/coco_reader_op.h" #include "dali/util/rapidjson/reader.h" #include "dali/util/rapidjson/document.h" RAPIDJSON_DIAG_PUSH #ifdef __GNUC__ RAPIDJSON_DIAG_OFF(effc++) #endif using rapidjson::SizeType; using rapidjson::Value; using rapidjson::Reader; using rapidjson::InsituStringStream; using rapidjson::kParseDefaultFlags; using rapidjson::kParseInsituFlag; using rapidjson::kArrayType; using rapidjson::kObjectType; namespace { // taken from https://github.com/Tencent/rapidjson/blob/master/example/lookaheadparser/lookaheadparser.cpp class LookaheadParserHandler { public: bool Null() { st_ = kHasNull; v_.SetNull(); return true; } bool Bool(bool b) { st_ = kHasBool; v_.SetBool(b); return true; } bool Int(int i) { st_ = kHasNumber; v_.SetInt(i); return true; } bool Uint(unsigned u) { st_ = kHasNumber; v_.SetUint(u); return true; } bool Int64(int64_t i) { st_ = kHasNumber; v_.SetInt64(i); return true; } bool Uint64(uint64_t u) { st_ = kHasNumber; v_.SetUint64(u); return true; } bool Double(double d) { st_ = kHasNumber; v_.SetDouble(d); return true; } bool RawNumber(const char*, SizeType, bool) { return false; } bool String(const char* str, SizeType length, bool) { st_ = kHasString; v_.SetString(str, length); return true; } bool StartObject() { st_ = kEnteringObject; return true; } bool Key(const char* str, SizeType length, bool) { st_ = kHasKey; v_.SetString(str, length); return true; } bool EndObject(SizeType) { st_ = kExitingObject; return true; } bool StartArray() { st_ = kEnteringArray; return true; } bool EndArray(SizeType) { st_ = kExitingArray; return true; } protected: explicit LookaheadParserHandler(char* str); void ParseNext(); protected: enum LookaheadParsingState { kInit, kError, kHasNull, kHasBool, kHasNumber, kHasString, kHasKey, kEnteringObject, kExitingObject, kEnteringArray, kExitingArray }; Value v_; LookaheadParsingState st_; Reader r_; InsituStringStream ss_; static const int parseFlags = kParseDefaultFlags | kParseInsituFlag; }; LookaheadParserHandler::LookaheadParserHandler(char* str) : v_(), st_(kInit), r_(), ss_(str) { r_.IterativeParseInit(); ParseNext(); } void LookaheadParserHandler::ParseNext() { if (r_.HasParseError()) { st_ = kError; return; } r_.IterativeParseNext<parseFlags>(ss_, *this); } class LookaheadParser : protected LookaheadParserHandler { public: explicit LookaheadParser(char* str) : LookaheadParserHandler(str) {} bool EnterObject(); bool EnterArray(); const char* NextObjectKey(); bool NextArrayValue(); int GetInt(); double GetDouble(); const char* GetString(); bool GetBool(); void GetNull(); void SkipObject(); void SkipArray(); void SkipValue(); Value* PeekValue(); // returns a rapidjson::Type, or -1 for no value (at end of object/array) int PeekType(); bool IsValid() { return st_ != kError; } protected: void SkipOut(int depth); }; bool LookaheadParser::EnterObject() { if (st_ != kEnteringObject) { st_ = kError; return false; } ParseNext(); return true; } bool LookaheadParser::EnterArray() { if (st_ != kEnteringArray) { st_ = kError; return false; } ParseNext(); return true; } const char* LookaheadParser::NextObjectKey() { if (st_ == kHasKey) { const char* result = v_.GetString(); ParseNext(); return result; } if (st_ != kExitingObject) { st_ = kError; return 0; } ParseNext(); return 0; } bool LookaheadParser::NextArrayValue() { if (st_ == kExitingArray) { ParseNext(); return false; } if (st_ == kError || st_ == kExitingObject || st_ == kHasKey) { st_ = kError; return false; } return true; } int LookaheadParser::GetInt() { if (st_ != kHasNumber || !v_.IsInt()) { st_ = kError; return 0; } int result = v_.GetInt(); ParseNext(); return result; } double LookaheadParser::GetDouble() { if (st_ != kHasNumber) { st_ = kError; return 0.; } double result = v_.GetDouble(); ParseNext(); return result; } bool LookaheadParser::GetBool() { if (st_ != kHasBool) { st_ = kError; return false; } bool result = v_.GetBool(); ParseNext(); return result; } void LookaheadParser::GetNull() { if (st_ != kHasNull) { st_ = kError; return; } ParseNext(); } const char* LookaheadParser::GetString() { if (st_ != kHasString) { st_ = kError; return 0; } const char* result = v_.GetString(); ParseNext(); return result; } void LookaheadParser::SkipOut(int depth) { do { if (st_ == kEnteringArray || st_ == kEnteringObject) { ++depth; } else if (st_ == kExitingArray || st_ == kExitingObject) { --depth; } else if (st_ == kError) { return; } ParseNext(); } while (depth > 0); } void LookaheadParser::SkipValue() { SkipOut(0); } void LookaheadParser::SkipArray() { SkipOut(1); } void LookaheadParser::SkipObject() { SkipOut(1); } Value* LookaheadParser::PeekValue() { if (st_ >= kHasNull && st_ <= kHasKey) { return &v_; } return 0; } int LookaheadParser::PeekType() { if (st_ >= kHasNull && st_ <= kHasKey) { return v_.GetType(); } if (st_ == kEnteringArray) { return kArrayType; } if (st_ == kEnteringObject) { return kObjectType; } return -1; } } // namespace namespace dali { DALI_REGISTER_OPERATOR(COCOReader, COCOReader, CPU); DALI_SCHEMA(COCOReader) .NumInput(0) .NumOutput(3) .DocStr(R"code(Read data from a COCO dataset composed of directory with images and an anotation files. For each image, with `m` bboxes, returns its bboxes as (m,4) Tensor (`m` * `[x, y, w, h] or `m` * [left, top, right, bottom]`) and labels as `(m,1)` Tensor (`m` * `category_id`).)code") .AddArg("file_root", R"code(Path to a directory containing data files.)code", DALI_STRING) .AddArg("annotations_file", R"code(List of paths to the JSON annotations files.)code", DALI_STRING_VEC) .AddOptionalArg("file_list", R"code(Path to the file with a list of pairs ``file label`` (leave empty to traverse the `file_root` directory to obtain files and labels))code", std::string()) .AddOptionalArg("ltrb", R"code(If true, bboxes are returned as [left, top, right, bottom], else [x, y, width, height].)code", false) .AddOptionalArg("ratio", R"code(If true, bboxes returned values as expressed as ratio w.r.t. to the image width and height.)code", false) .AddOptionalArg("size_threshold", R"code(If width or height of a bounding box representing an instance of an object is under this value, object will be skipped during reading. It is represented as absolute value.)code", 0.1f, false) .AddOptionalArg("skip_empty", R"code(If true, reader will skip samples with no object instances in them)code", false) .AddOptionalArg("save_img_ids", R"code(If true, image IDs will also be returned.)code", false) .AddOptionalArg("shuffle_after_epoch", R"code(If true, reader shuffles whole dataset after each epoch.)code", false) .AdditionalOutputsFn([](const OpSpec& spec) { return static_cast<int>(spec.GetArgument<bool>("save_img_ids")); }) .AddParent("LoaderBase"); void ParseAnnotationFilesHelper(std::vector<std::string> &annotations_filename, AnnotationMap &annotations_multimap, std::vector<std::pair<std::string, int>> &image_id_pairs, bool ltrb, bool ratio, float size_threshold, bool skip_empty) { for (auto& file_name : annotations_filename) { // Loading raw json into the RAM std::ifstream f(file_name); DALI_ENFORCE(f, "Could not open JSON annotations file"); f.seekg(0, std::ios::end); size_t file_size = f.tellg(); std::unique_ptr<char, std::function<void(char*)>> buff(new char[file_size], [](char* data) {delete [] data;}); f.seekg(0, std::ios::beg); f.read(buff.get(), file_size); LookaheadParser r(buff.get()); // mapping each image_id to its WH dimension std::unordered_map<int, std::pair<int, int> > image_id_to_wh; // Change categories IDs to be in range [1, 80] std::vector<int> deleted_categories{ 12, 26, 29, 30, 45, 66, 68, 69, 71, 83, 91 }; std::map<int, int> new_category_ids; int current_id = 1; int vector_id = 0; for (int i = 1; i <= 90; i++) { if (i == deleted_categories[vector_id]) { vector_id++; } else { new_category_ids.insert(std::make_pair(i, current_id)); current_id++; } } RAPIDJSON_ASSERT(r.PeekType() == kObjectType); r.EnterObject(); while (const char* key = r.NextObjectKey()) { if (0 == strcmp(key, "images")) { RAPIDJSON_ASSERT(r.PeekType() == kArrayType); r.EnterArray(); int id; string image_file_name; int width; int height; while (r.NextArrayValue()) { if (r.PeekType() != kObjectType) { continue; } r.EnterObject(); while (const char* internal_key = r.NextObjectKey()) { if (0 == strcmp(internal_key, "id")) { id = r.GetInt(); } else if (0 == strcmp(internal_key, "width")) { width = r.GetInt(); } else if (0 == strcmp(internal_key, "height")) { height = r.GetInt(); } else if (0 == strcmp(internal_key, "file_name")) { image_file_name = r.GetString(); } else { r.SkipValue(); } } image_id_pairs.push_back(std::make_pair(image_file_name, id)); image_id_to_wh.insert(std::make_pair(id, std::make_pair(width, height))); } } else if (0 == strcmp(key, "annotations")) { RAPIDJSON_ASSERT(r.PeekType() == kArrayType); r.EnterArray(); int image_id; int category_id; std::array<float, 4> bbox = {0, }; while (r.NextArrayValue()) { if (r.PeekType() != kObjectType) { continue; } r.EnterObject(); while (const char* internal_key = r.NextObjectKey()) { if (0 == strcmp(internal_key, "image_id")) { image_id = r.GetInt(); } else if (0 == strcmp(internal_key, "category_id")) { category_id = r.GetInt(); } else if (0 == strcmp(internal_key, "bbox")) { RAPIDJSON_ASSERT(r.PeekType() == kArrayType); r.EnterArray(); int i = 0; while (r.NextArrayValue()) { bbox[i] = r.GetDouble(); ++i; } } else { r.SkipValue(); } } if (bbox[2] < size_threshold || bbox[3] < size_threshold) { continue; } if (ltrb) { bbox[2] += bbox[0]; bbox[3] += bbox[1]; } annotations_multimap.insert( std::make_pair(image_id, Annotation(bbox[0], bbox[1], bbox[2], bbox[3], new_category_ids[category_id]))); } } else { r.SkipValue(); } } if (skip_empty) { std::vector<std::pair<std::string, int>> non_empty_ids; non_empty_ids.reserve(image_id_pairs.size()); for (const auto &id_pair : image_id_pairs) if (annotations_multimap.count(id_pair.second) > 0) non_empty_ids.push_back(id_pair); image_id_pairs = std::move(non_empty_ids); } if (ratio) { for (auto& elm : annotations_multimap) { const auto& wh = image_id_to_wh[elm.first]; elm.second.bbox[0] /= static_cast<float>(wh.first); elm.second.bbox[1] /= static_cast<float>(wh.second); elm.second.bbox[2] /= static_cast<float>(wh.first); elm.second.bbox[3] /= static_cast<float>(wh.second); } } f.close(); } } RAPIDJSON_DIAG_POP } // namespace dali
27.522581
191
0.618612
klecki
9c4da66bcaa4000103323c8634fea629a15c3aa5
5,376
cpp
C++
src/graphs/laplacian.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/graphs/laplacian.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/graphs/laplacian.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
#include "tkdCmdParser.h" #include "graphCommon.h" /** * Calculate (normalized) laplacian and eigenvector/values. */ class Laplacian { public: typedef double PixelType; /** * Run app. */ void Run( const std::string& filename, const std::string& outputFileName, bool normalize, const std::string& outputFileNameEigen, unsigned int numberOfEigenVectors, bool outputEigenFiles, const std::string& outputFileNameKmeans, unsigned int numberOfClusters, bool outputKmeans, bool sparse ) { // get dimensions... unsigned int dims = graph::Graph< PixelType >::GetImageDimensions( filename ); if ( dims == 2 ) { graph::Graph< PixelType >::ImagePointerType image; graph::Graph< PixelType >::ReadMatrix( image, filename ); PixelType* buffer = image->GetPixelContainer()->GetBufferPointer( ); graph::Graph< PixelType >::ImageType::RegionType region = image->GetLargestPossibleRegion( ); graph::Graph< PixelType >::ImageType::SizeType size = region.GetSize(); int rows = size[ 0 ]; int cols = size[ 1 ]; graph::Graph< PixelType >::DataMatrixType G( rows, cols, buffer ); graph::Graph< PixelType >::DiagMatrixType D; graph::Graph< PixelType >::MatrixType L; // [ 1 ] graph::Graph< PixelType >::CalculateLaplacian( L, G, D, normalize ); // [ 2 ] graph::Graph< PixelType >::MatrixType eigenVectors; graph::Graph< PixelType >::VectorType eigenValues; if( sparse ) { // convert dense matrix into sparse matrix... vnl_sparse_matrix< PixelType > S( L.rows(), L.cols() ); for( unsigned int i = 0; i < L.rows(); i++ ) for( unsigned int j = i; j < L.cols(); j++ ) if( L( i, j ) != 0 ) S( i, j ) = L( i, j ); graph::Graph< PixelType >::GeneralizedEigenCalculation( S, eigenVectors, eigenValues, numberOfEigenVectors ); } else graph::Graph< PixelType >::GeneralizedEigenCalculation( L, D, eigenVectors, eigenValues ); // Output eigenfiles... graph::Graph< PixelType >::WriteEigenFiles( outputFileNameEigen, numberOfEigenVectors, eigenVectors, eigenValues ); if( !outputFileName.empty() ) { graph::Graph< PixelType >::WriteMatrixToFile( L, outputFileName ); } // [ 3 ] Optional: run KMEANS++ if( outputKmeans ) { graph::Graph< PixelType >::VectorType clusters; graph::Graph< PixelType >::KMeansPP( eigenVectors, numberOfClusters, clusters ); graph::Graph< PixelType >::WriteVectorToFile( outputFileNameKmeans + "_clusters.txt", clusters ); } } else { std::cerr << "Number of input (matrix) dimensions should be 2!"<< std::endl; exit( EXIT_FAILURE ); } } }; /** * Main. */ int main( int argc, char ** argv ) { tkd::CmdParser p( argv[0], "Compute Laplacian of graph's adjacency matrix"); std::string inputFileName; std::string outputFileName; std::string outputFileNameEigen = "eigen"; int numberOfEigenVectors = 15; bool outputEigenFiles = false; bool normalize = false; std::string outputFileNameKmeans = "kmeans"; int numberOfClusters = 15; bool outputKmeans = false; bool sparse = false; p.AddArgument( inputFileName, "input" ) ->AddAlias( "i" ) ->SetInput( "filename" ) ->SetDescription( "Input image: 2D adjacency matrix" ) ->SetRequired( true ); p.AddArgument( outputFileName, "output" ) ->AddAlias( "o" ) ->SetInput( "filename" ) ->SetDescription( "Output image: 2D laplacian matrix" ) ->SetRequired( false ); p.AddArgument( outputFileNameEigen, "output-eigen-root" ) ->AddAlias( "oer" ) ->SetInput( "root filename" ) ->SetDescription( "Root eigen files (default: 'eigen')" ) ->SetRequired( false ); p.AddArgument( numberOfEigenVectors, "output-eigenvector-number" ) ->AddAlias( "oen" ) ->SetInput( "int" ) ->SetDescription( "Number of eigenvectors to output (default: 15; first (zero) eigenvector is ignored)" ) ->SetRequired( false ); p.AddArgument( outputEigenFiles, "output-eigen-files" ) ->AddAlias( "oef" ) ->SetInput( "bool" ) ->SetDescription( "Output eigenvectors and eigenvalues (default: false)" ) ->SetRequired( false ); p.AddArgument( outputFileNameKmeans, "output-kmeans-root" ) ->AddAlias( "okr" ) ->SetInput( "root filename" ) ->SetDescription( "Root kmeans files (default: 'kmeans')" ) ->SetRequired( false ); p.AddArgument( numberOfClusters, "output-kmeans-clusters" ) ->AddAlias( "okc" ) ->SetInput( "int" ) ->SetDescription( "Number of clusters to output (default: 15)" ) ->SetRequired( false ); p.AddArgument( outputKmeans, "output-kmeans-file" ) ->AddAlias( "okf" ) ->SetInput( "bool" ) ->SetDescription( "Output kmeans++ segmentation (default: false)" ) ->SetRequired( false ); p.AddArgument( normalize, "normalize" ) ->AddAlias( "n" ) ->SetInput( "bool" ) ->SetDescription( "Normalize laplacian matrix (default: false)" ) ->SetRequired( false ); p.AddArgument( sparse, "sparse" ) ->AddAlias( "s" ) ->SetInput( "bool" ) ->SetDescription( "Use Lanczos algorithm to estimate eigen-vectors (default: false)" ) ->SetRequired( false ); if ( !p.Parse( argc, argv ) ) { p.PrintUsage( std::cout ); return EXIT_FAILURE; } Laplacian laplacian; laplacian.Run( inputFileName, outputFileName, normalize, outputFileNameEigen, (unsigned) numberOfEigenVectors, outputEigenFiles, outputFileNameKmeans, (unsigned) numberOfClusters, outputKmeans, sparse ); return EXIT_SUCCESS; }
28.748663
118
0.678943
wmotte
9c4e385a8b4226636de01172b84b207f5451ceb8
4,656
cc
C++
uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc
Abhi10arora/uuv_simulator
bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc
Abhi10arora/uuv_simulator
bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
uuv_sensor_plugins/uuv_sensor_plugins/src/MagnetometerPlugin.cc
Abhi10arora/uuv_simulator
bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441
[ "Apache-2.0", "BSD-3-Clause" ]
1
2018-10-18T15:11:01.000Z
2018-10-18T15:11:01.000Z
// Copyright (c) 2016 The UUV Simulator Authors. // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This source code is derived from hector_gazebo // (https://github.com/tu-darmstadt-ros-pkg/hector_gazebo) // Copyright (c) 2012, Johannes Meyer, TU Darmstadt, // licensed under the BSD 3-Clause license, // cf. 3rd-party-licenses.txt file in the root directory of this source tree. // // The original code was modified to: // - be more consistent with other sensor plugins within uuv_simulator, // - remove its dependency on ROS. The ROS interface is instead implemented in // a derived class within the uuv_sensor_plugins_ros package, // - adhere to Gazebo's coding standards. #include <uuv_sensor_plugins/MagnetometerPlugin.hh> #include <gazebo/physics/physics.hh> #include "Common.hh" namespace gazebo { GazeboMagnetometerPlugin::GazeboMagnetometerPlugin() : GazeboSensorPlugin() { } GazeboMagnetometerPlugin::~GazeboMagnetometerPlugin() { } void GazeboMagnetometerPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { GazeboSensorPlugin::Load(_model, _sdf); // Load settings specific to this type of sensor getSdfParam<double>(_sdf, "intensity", parameters_.intensity, 1.0); getSdfParam<double>(_sdf, "referenceHeading", parameters_.heading, M_PI); getSdfParam<double>(_sdf, "declination", parameters_.declination, 0.0); getSdfParam<double>(_sdf, "inclination", parameters_.inclination, 60.*M_PI/180.); getSdfParam<double>(_sdf, "noise_xy", parameters_.noiseXY, 1.0); getSdfParam<double>(_sdf, "noise_z", parameters_.noiseZ, 1.4); getSdfParam<double>(_sdf, "turn_on_bias", parameters_.turnOnBias, 2.0); // Now Prepare derived values // Note: Gazebo uses NorthWestUp coordinate system, // heading and declination are compass headings magneticFieldWorld_.x = parameters_.intensity*cos(parameters_.inclination) * cos(parameters_.heading - parameters_.declination); magneticFieldWorld_.y = parameters_.intensity*cos(parameters_.inclination) * sin(parameters_.heading - parameters_.declination); magneticFieldWorld_.z = parameters_.intensity *(-sin(parameters_.inclination)); turnOnBias_.x = parameters_.turnOnBias * normal_(rndGen_); turnOnBias_.y = parameters_.turnOnBias * normal_(rndGen_); turnOnBias_.z = parameters_.turnOnBias * normal_(rndGen_); // Fill constant fields of sensor message already // TODO: This should better be a 3x3 matrix instead magneticGazeboMessage_.add_magnetic_field_covariance( parameters_.noiseXY*parameters_.noiseXY); magneticGazeboMessage_.add_magnetic_field_covariance( parameters_.noiseXY*parameters_.noiseXY); magneticGazeboMessage_.add_magnetic_field_covariance( parameters_.noiseZ*parameters_.noiseZ); if (this->sensorTopic_.empty()) this->sensorTopic_ = "magnetometer"; publisher_ = nodeHandle_->Advertise<sensor_msgs::msgs::Magnetic>( sensorTopic_, 10); } void GazeboMagnetometerPlugin::SimulateMeasurement( const common::UpdateInfo& info) { math::Pose pose = link_->GetWorldPose(); math::Vector3 noise(parameters_.noiseXY*normal_(rndGen_), parameters_.noiseXY*normal_(rndGen_), parameters_.noiseZ*normal_(rndGen_)); measMagneticField_ = pose.rot.RotateVectorReverse(magneticFieldWorld_) + turnOnBias_ + noise; } bool GazeboMagnetometerPlugin::OnUpdate(const common::UpdateInfo& _info) { if (!ShouldIGenerate(_info)) return false; SimulateMeasurement(_info); gazebo::msgs::Vector3d* field = new gazebo::msgs::Vector3d(); field->set_x(this->measMagneticField_.x); field->set_y(this->measMagneticField_.y); field->set_z(this->measMagneticField_.z); this->magneticGazeboMessage_.set_allocated_magnetic_field(field); publisher_->Publish(magneticGazeboMessage_); return true; } GZ_REGISTER_MODEL_PLUGIN(GazeboMagnetometerPlugin); }
36.375
78
0.717354
Abhi10arora
9c4ee80c068c69dfe9733e6e35573ed539111929
632
cpp
C++
t1m1/FOSSSim/ExplicitEuler.cpp
dailysoap/CSMM.104x
4515b30ab5f60827a9011b23ef155a3063584a9d
[ "MIT" ]
null
null
null
t1m1/FOSSSim/ExplicitEuler.cpp
dailysoap/CSMM.104x
4515b30ab5f60827a9011b23ef155a3063584a9d
[ "MIT" ]
null
null
null
t1m1/FOSSSim/ExplicitEuler.cpp
dailysoap/CSMM.104x
4515b30ab5f60827a9011b23ef155a3063584a9d
[ "MIT" ]
null
null
null
#include "ExplicitEuler.h" bool ExplicitEuler::stepScene( TwoDScene& scene, scalar dt ) { // Your code goes here! // Some tips on getting data from TwoDScene: // A vector containing all of the system's position DoFs. x0, y0, x1, y1, ... //VectorXs& x = scene.getX(); // A vector containing all of the system's velocity DoFs. v0, v0, v1, v1, ... //VectorXs& v = scene.getV(); // A vector containing the masses associated to each DoF. m0, m0, m1, m1, ... //const VectorXs& m = scene.getM(); // Determine if the ith particle is fixed // if( scene.isFixed(i) ) return true; }
31.6
81
0.620253
dailysoap
9c5062442af5a27b76ad10f56d80395f86ea7c7f
3,280
cpp
C++
tests/src/cookbook_unknown_types_and_raw_parsing2_test.cpp
friendlyanon/daw_json_link
7456a8a69a307e63e8063765a67ceba051958b10
[ "BSL-1.0" ]
null
null
null
tests/src/cookbook_unknown_types_and_raw_parsing2_test.cpp
friendlyanon/daw_json_link
7456a8a69a307e63e8063765a67ceba051958b10
[ "BSL-1.0" ]
null
null
null
tests/src/cookbook_unknown_types_and_raw_parsing2_test.cpp
friendlyanon/daw_json_link
7456a8a69a307e63e8063765a67ceba051958b10
[ "BSL-1.0" ]
1
2021-08-06T10:13:11.000Z
2021-08-06T10:13:11.000Z
// Copyright (c) Darrell Wright // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/beached/daw_json_link // #include "defines.h" #include <daw/daw_read_file.h> #include "daw/json/daw_json_link.h" #include <cstdint> #include <cstdio> #include <cstdlib> #include <iostream> #include <string> struct MyClass2 { int member0; daw::json::json_value member_later; std::string member1; std::optional<daw::json::json_value> opt_member; }; namespace daw::json { template<> struct json_data_contract<MyClass2> { static constexpr char const member0[] = "member0"; static constexpr char const member_later[] = "member_later"; static constexpr char const member1[] = "member1"; static constexpr char const opt_member[] = "opt_member"; using type = json_member_list<json_number<member0, int>, json_raw<member_later>, json_string<member1>, json_link<opt_member, std::optional<json_value>>>; static inline auto to_json_data( MyClass2 const &value ) { return std::forward_as_tuple( value.member0, value.member_later, value.member1, value.opt_member ); } }; } // namespace daw::json // This isn't necessary to parse the values as but allows for directly // constructing the object struct MyDelayedClass { int a; bool b; DAW_CONSTEXPR bool operator==( MyDelayedClass const &rhs ) const { return a == rhs.a and b == rhs.b; } }; namespace daw::json { template<> struct json_data_contract<MyDelayedClass> { #if defined( __cpp_nontype_template_parameter_class ) using type = json_member_list<json_number<"a", int>, json_bool<"b">>; #else static constexpr char const a[] = "a"; static constexpr char const b[] = "b"; using type = json_member_list<json_number<a, int>, json_bool<b>>; #endif static inline auto to_json_data( MyDelayedClass const &value ) { return std::forward_as_tuple( value.a, value.b ); } }; } // namespace daw::json bool operator==( MyClass2 const &lhs, MyClass2 const &rhs ) { if( lhs.member0 != rhs.member0 or lhs.member1 != lhs.member1 ) { return false; } using namespace daw::json; return from_json<MyDelayedClass>( rhs.member_later ) == from_json<MyDelayedClass>( rhs.member_later ); } int main( int argc, char **argv ) #ifdef DAW_USE_EXCEPTIONS try #endif { if( argc <= 1 ) { puts( "Must supply path to cookbook_unknown_types_and_delayed_parsing2.json " "file\n" ); exit( EXIT_FAILURE ); } auto data = *daw::read_file( argv[1] ); auto const val = daw::json::from_json<MyClass2>( std::string_view( data.data( ), data.size( ) ) ); auto const delayed_val = daw::json::from_json<MyDelayedClass>( val.member_later ); test_assert( delayed_val.a == 1, "Unexpected value" ); test_assert( delayed_val.b, "Unexpected value" ); std::string json_str2 = daw::json::to_json( val ); puts( json_str2.c_str( ) ); auto const val2 = daw::json::from_json<MyClass2>( json_str2 ); test_assert( val == val2, "Broken round trip" ); } catch( daw::json::json_exception const &jex ) { std::cerr << "Exception thrown by parser: " << jex.reason( ) << std::endl; exit( 1 ); }
28.77193
79
0.692378
friendlyanon
9c52156354e973d58ee13f744cf22c0fdb5f0dd2
18,521
hpp
C++
include/beap_view.hpp
degski/beap
6fffd5b536f29ed7551bdbe66ad20eb39e7024c8
[ "MIT" ]
1
2020-03-12T15:17:50.000Z
2020-03-12T15:17:50.000Z
include/beap_view.hpp
degski/beap
6fffd5b536f29ed7551bdbe66ad20eb39e7024c8
[ "MIT" ]
null
null
null
include/beap_view.hpp
degski/beap
6fffd5b536f29ed7551bdbe66ad20eb39e7024c8
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2020 degski // // 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, rhs_, 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 <cassert> #include <cstddef> #include <cstdint> #include <cstdlib> #include <compare> #include <limits> #include <optional> #include <span> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "detail/hedley.hpp" #define BEAP_PURE HEDLEY_PURE #define BEAP_UNPREDICTABLE HEDLEY_UNPREDICTABLE #define BEAP_LIKELY HEDLEY_LIKELY #define BEAP_UNLIKELY HEDLEY_UNLIKELY #include "detail/triangular.hpp" #define ever \ ; \ ; template<typename ValueType, typename SignedSizeType = int32_t, typename Compare = std::less<SignedSizeType>> class beap_view { // Current beap_height of beap_view. Note that beap_height is defined as // distance between consecutive layers, so for single - element // beap_view beap_height is 0, and for empty, we initialize it to - 1. // // An example of the lay-out: // // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 .. // { 72, 68, 63, 44, 62, 55, 33, 22, 32, 51, 13, 18, 21, 19, 22, 11, 12, 14, 17, 9, 13, 3, 2, 10, 54 } // _ _ _ _ _ _ _ _ public: using size_type = SignedSizeType; private: template<typename T, typename Comp> struct basic_value_type { T v; constexpr basic_value_type ( T value_ ) noexcept : v{ value_ } {} [[nodiscard]] constexpr size_type operator<=> ( basic_value_type const & r_ ) const noexcept { return static_cast<size_type> ( static_cast<int> ( not( Comp ( ) ( r_.v, v ) ) ) - static_cast<int> ( Comp ( ) ( v, r_.v ) ) ); }; template<typename Stream> [[maybe_unused]] friend Stream & operator<< ( Stream & out_, basic_value_type const & value_ ) noexcept { out_ << value_.v; return out_; } }; using value_type = basic_value_type<ValueType, Compare>; using container_type = std::vector<value_type>; using container_type_ptr = std::vector<value_type> *; public: using difference_type = size_type; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using pointer = typename container_type::pointer; using const_pointer = typename container_type::const_pointer; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; private: using span_type = tri::basic_span_type<size_type>; public: beap_view ( ) noexcept = delete; beap_view ( beap_view const & b_ ) = default; beap_view ( beap_view && b_ ) = delete; beap_view ( std::vector<ValueType> & data_ ) : container ( reinterpret_cast<std::vector<value_type> *> ( &data_ ) ), data ( reinterpret_cast<value_type *> ( data_.data ( ) ) ), end_span ( span_type::span ( tri::nth_triangular_root ( static_cast<size_type> ( data_.size ( ) ) ) - 1 ) ) {} [[maybe_unused]] beap_view & operator= ( beap_view const & b_ ) = default; [[maybe_unused]] beap_view & operator= ( beap_view && b_ ) = delete; // Operations (private). private: [[nodiscard]] span_type search ( value_type const & v ) const noexcept { span_type s = end_span; size_type beap_height = s.end - s.beg, i = s.beg + 1, h = beap_height, len = length ( ); for ( ever ) { switch ( value_type const & d = data[ i ]; BEAP_UNPREDICTABLE ( v <=> d ) ) { case -1: { if ( BEAP_UNLIKELY ( i == ( len - 1 ) ) ) { --s, i -= h--; continue; } if ( size_type i_ = i + h + 2; BEAP_UNLIKELY ( i_ < len ) ) { ++s, i = i_, h += 1; continue; } if ( BEAP_UNLIKELY ( i++ == ( s.end - 1 ) ) ) return { end_span.end, beap_height }; continue; } case +1: { if ( BEAP_UNLIKELY ( i == s.end ) ) return { end_span.end, beap_height }; --s, i -= h--; continue; } default: { return { i, h }; } } } } [[nodiscard]] size_type breadth_first_search ( value_type const & v_ ) noexcept { size_type siz = size ( ); for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < siz ); base_l += 1, base_i += base_l + 1 ) { for ( size_type lev = base_l + 1, l_i = base_i + 2, r_i = base_i + ( lev + 2 ) - 2; BEAP_UNLIKELY ( l_i < siz and r_i < siz ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) { if ( BEAP_UNLIKELY ( v_ == data[ l_i ] ) ) return l_i; if ( BEAP_UNLIKELY ( v_ == data[ r_i ] ) ) return r_i; } } return siz; } [[maybe_unused]] size_type bubble_up ( size_type i_, size_type h_ ) noexcept { span_type s = end_span; while ( BEAP_LIKELY ( h_ ) ) { span_type p = s.prev ( ); size_type d = i_ - s.beg; size_type l = 0, r = 0; if ( BEAP_UNLIKELY ( i_ != s.beg ) ) l = p.beg + d - 1; if ( BEAP_UNLIKELY ( i_ != s.end ) ) r = p.beg + d; if ( BEAP_UNPREDICTABLE ( ( l ) and ( refof ( i_ ) > refof ( l ) ) and ( not r or ( refof ( l ) < refof ( r ) ) ) ) ) { std::swap ( refof ( i_ ), refof ( l ) ); i_ = l; } else if ( BEAP_UNPREDICTABLE ( ( r ) and ( refof ( i_ ) > refof ( r ) ) ) ) { std::swap ( refof ( i_ ), refof ( r ) ); i_ = r; } else { return i_; } s = p; h_ -= 1; } assert ( i_ == 0 ); return i_; } [[nodiscard]] size_type bubble_down ( size_type i_, size_type h_ ) noexcept { span_type s = end_span; size_type const h_1 = s.end - s.beg - 1, len = length ( ); while ( BEAP_LIKELY ( h_ < h_1 ) ) { span_type c = s.next ( ); size_type l = c.beg + i_ - s.beg, r = 0; if ( BEAP_LIKELY ( l < len ) ) { r = l + 1; if ( BEAP_UNLIKELY ( r >= len ) ) r = 0; } else { l = 0; } if ( BEAP_UNPREDICTABLE ( l and refof ( i_ ) < refof ( l ) and ( not r or refof ( l ) > refof ( r ) ) ) ) { std::swap ( refof ( i_ ), refof ( l ) ); i_ = l; } else if ( BEAP_UNPREDICTABLE ( r and refof ( i_ ) < refof ( r ) ) ) { std::swap ( refof ( i_ ), refof ( r ) ); i_ = r; } else { return i_; } s = c; h_ += 1; } return i_; } [[maybe_unused]] void erase_impl ( size_type i_, size_type h_ ) noexcept { size_type len = length ( ); if ( BEAP_UNLIKELY ( len == end_span.beg ) ) { --end_span; shrink_to_fit ( ); // only when load is less than 50%. } assert ( i_ != ( len - 1 ) ); refof ( i_ ) = pop_data ( ); if ( size_type i = bubble_down ( i_, h_ ); BEAP_LIKELY ( i == i_ ) ) bubble_up ( i_, h_ ); } template<typename... Args> [[maybe_unused]] size_type emplace_impl ( size_type i_, Args... args_ ) noexcept { container->emplace_back ( std::forward<Args> ( args_ )... ); return bubble_up ( i_, end_span.end - end_span.beg ); } // Operations (public). public: [[maybe_unused]] size_type insert ( value_type const & v_ ) { return emplace ( value_type{ v_ } ); } template<typename ForwardIt> void insert ( ForwardIt b_, ForwardIt e_ ) noexcept { reserve ( tri::nth_triangular_ceil ( static_cast<size_type> ( container->size ( ) + std::distance ( b_, e_ ) ) ) ); size_type c = size ( ); while ( b_ != e_ ) emplace_impl ( c++, value_type{ *b_ } ); } // clang-format on template<typename... Args> [[maybe_unused]] size_type emplace ( Args... args_ ) { size_type i = length ( ); if ( BEAP_UNLIKELY ( i == end_span.end ) ) { ++end_span; reserve ( end_span.end ); } return emplace_impl ( i, std::forward<Args> ( args_ )... ); } template<typename ForwardIt> [[maybe_unused]] void emplace ( ForwardIt b_, ForwardIt e_ ) noexcept { reserve ( tri::nth_triangular_ceil ( static_cast<size_type> ( container->size ( ) + std::distance ( b_, e_ ) ) ) ); size_type c = size ( ); while ( b_ != e_ ) emplace_impl ( c++, std::move ( *b_ ) ); } void erase ( value_type const & v_ ) noexcept { auto [ i, h ] = search ( v_ ); if ( BEAP_UNLIKELY ( i == end_span.end ) ) return; erase_impl ( i, h ); } void erase_by_index ( size_type i_ ) noexcept { if ( BEAP_UNLIKELY ( i_ == end_span.end ) ) return; erase_impl ( i_, tri::nth_triangular_root ( i_ ) ); } [[nodiscard]] size_type find ( value_type const & v_ ) const noexcept { return search ( v_ ).beg; } [[nodiscard]] bool contains ( value_type const & v_ ) const noexcept { return find ( v_ ) != end_span.end; } // Sizes. [[nodiscard]] BEAP_PURE size_type size ( ) const noexcept { return static_cast<int> ( container->size ( ) ); } [[nodiscard]] BEAP_PURE size_type length ( ) const noexcept { return size ( ); } [[nodiscard]] BEAP_PURE size_type capacity ( ) const noexcept { return static_cast<int> ( container->capacity ( ) ); } void shrink_to_fit ( ) { if ( BEAP_UNLIKELY ( ( capacity ( ) >> 1 ) == size ( ) ) ) { // iff 100% over-allocated, force shrinking. container_type tmp; tmp.reserve ( end_span.end ); *container = std::move ( ( tmp = *container ) ); data = container->data ( ); } } public: [[nodiscard]] BEAP_PURE iterator begin ( ) noexcept { return container->begin ( ); } [[nodiscard]] BEAP_PURE const_iterator cbegin ( ) const noexcept { return container->begin ( ); } [[nodiscard]] BEAP_PURE iterator end ( ) noexcept { return container->end ( ); } [[nodiscard]] BEAP_PURE const_iterator cend ( ) const noexcept { return container->end ( ); } [[nodiscard]] BEAP_PURE iterator rbegin ( ) noexcept { return container->rbegin ( ); } [[nodiscard]] BEAP_PURE const_iterator crbegin ( ) const noexcept { return container->rbegin ( ); } [[nodiscard]] BEAP_PURE iterator rend ( ) noexcept { return container->rend ( ); } [[nodiscard]] BEAP_PURE const_iterator crend ( ) const noexcept { return container->rend ( ); } // Beap. static inline void make_beap ( ) noexcept { end_span = span_type::span ( 0 ); size_type c = 1; iterator b = container->begin ( ) + 1, e = container->end ( ); while ( b != e ) emplace_impl ( c++, std::move ( *b ) ); } [[nodiscard]] static inline ValueType pop_beap ( ) noexcept { after_exit_erase_top guard ( this ); return container->front ( ).v; } [[maybe_unused]] size_type push_beap ( value_type const & v_ ) { return insert ( v_ ); } [[nodiscard]] BEAP_PURE reference top ( ) noexcept { return container->front ( ); } [[nodiscard]] BEAP_PURE const_reference top ( ) const noexcept { return container->front ( ); } [[nodiscard]] BEAP_PURE const_reference bottom ( ) const noexcept { for ( size_type min = end_span.beg, i = min + 1, data_end = size ( ); BEAP_LIKELY ( i < data_end ); ++i ) if ( BEAP_UNPREDICTABLE ( data[ i ] < data[ min ] ) ) min = i; } [[nodiscard]] BEAP_PURE reference bottom ( ) noexcept { return const_cast<reference> ( std::as_const ( this )->bottom ( ) ); } template<typename ForwardIt> [[nodiscard]] static ForwardIt is_beap_untill ( ForwardIt b_, ForwardIt e_ ) noexcept { auto const data = &*b_; // 72, // 68, 63, // 44, 62, 55, // 33, 22, 32, 51, // 13, 18, 21, 19, 31, // 11, 12, 14, 17, 9, 13, // 3, 2, 10 size_type size = static_cast<size_type> ( std::distance ( b_, e_ ) ); // Searches for out-of-order element, top-down and breadth-first. for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < size ); base_l += 1, base_i += base_l + 1 ) { for ( size_type lev = base_l + 1, l_p = base_i - lev + 1, l_i = l_p + ( lev ) + 1, r_p = base_i, r_i = r_p + ( lev + 2 ) - 2; BEAP_UNLIKELY ( l_i < size and r_i < size ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) { if ( not BEAP_UNLIKELY ( Compare ( ) ( data[ l_i ], data[ l_p ] ) ) ) return b_ + l_i; if ( not BEAP_UNLIKELY ( Compare ( ) ( data[ r_i ], data[ r_p ] ) ) ) return b_ + r_i; l_p = l_i; r_p = r_i; } } return e_; } template<typename ForwardIt> [[nodiscard]] static bool is_beap ( ForwardIt b_, ForwardIt e_ ) noexcept { return is_beap_untill ( b_, e_ ) == e_; } [[nodiscard]] size_type is_beap_untill ( ) noexcept { // Searches for out-of-order element, top-down and breadth-first. size_type siz = size ( ); for ( size_type base_l = 0, base_i = tri::nth_triangular ( base_l ); BEAP_UNLIKELY ( base_i < siz ); base_l += 1, base_i += base_l + 1 ) { for ( size_type lev = base_l + 1, l_p = base_i - lev + 1, l_i = l_p + ( lev ) + 1, r_p = base_i, r_i = r_p + ( lev + 2 ) - 2; BEAP_UNLIKELY ( l_i < siz and r_i < siz ); lev += 1, l_i += ( lev + 1 ), r_i += ( ( lev + 2 ) - 2 ) ) { if ( not BEAP_UNLIKELY ( data[ l_i ] < data[ l_p ] ) ) return l_i; if ( not BEAP_UNLIKELY ( data[ r_i ] < data[ r_p ] ) ) return r_i; l_p = l_i; r_p = r_i; } } return siz; } // Miscelanious. void clear ( ) noexcept { container->clear ( ); } [[nodiscard]] constexpr size_type max_size ( ) const noexcept { return std::numeric_limits<size_type>::max ( ); } void swap ( beap_view & rhs_ ) noexcept { std::swap ( *this, rhs_ ); } [[nodiscard]] bool contains ( ValueType const & v_ ) const noexcept { return search ( v_ ).beg; } [[nodiscard]] bool empty ( ) const noexcept { return container->empty ( ); } // Output. template<typename Stream> [[maybe_unused]] friend Stream & operator<< ( Stream & out_, beap_view const & beap_ ) noexcept { std::for_each ( beap_.cbegin ( ), beap_.cend ( ), [ &out_ ] ( auto & e ) { out_ << e << sp; } ); return out_; } // Miscelanious. private: [[nodiscard]] BEAP_PURE const_reference refof ( size_type i_ ) const noexcept { return data[ i_ ]; } [[nodiscard]] BEAP_PURE reference refof ( size_type i_ ) noexcept { return data[ i_ ]; } struct after_exit_erase_top { beap_view * b; after_exit_erase_top ( beap_view * b_ ) noexcept : b ( b_ ) {} ~after_exit_erase_top ( ) noexcept { b->erase_impl ( 0, 1 ); }; }; struct after_exit_pop_back { container_type_ptr c; after_exit_pop_back ( container_type_ptr c_ ) noexcept : c ( c_ ) {} ~after_exit_pop_back ( ) noexcept { c->pop_back ( ); } }; [[nodiscard]] value_type pop_data ( ) noexcept { after_exit_pop_back guard ( container ); return container->back ( ); } void reserve ( size_type c_ ) { container->reserve ( static_cast<std::size_t> ( c_ ) ); data = container->data ( ); } // Members. container_type_ptr container = nullptr; pointer data = nullptr; span_type end_span = { 0, 0 }; }; #undef PRIVATE #undef PUBLIC #undef BEAP_PURE #undef BEAP_UNPREDICTABLE #undef BEAP_LIKELY #undef BEAP_UNLIKELY #undef ever
39.915948
132
0.528049
degski
9c53de73ff008b60db768a75560594941870e0d9
1,000
cpp
C++
src/Core/Status.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
5
2017-10-07T06:46:23.000Z
2018-12-10T07:14:47.000Z
src/Core/Status.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
8
2017-01-07T15:01:32.000Z
2017-07-16T20:18:10.000Z
src/Core/Status.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
4
2017-01-07T14:58:00.000Z
2019-10-30T09:38:53.000Z
#include "Status.hpp" #include "Memory.hpp" using namespace Core; Status Status::OK(StatusCode::OK, "OK"); Status Status::NotImplemented(StatusCode::NotImplemented, "Not implemented."); Status::Status() : code(StatusCode::OK), message("OK") { } Status::Status(const StatusCode& code, const std::string& message) : code(code), message(message) { } Status::Status(const StatusCode& code, const std::string& message, const Status& innerResult) : code(code), message(message), innerStatus(std::make_unique<Status>(innerResult)) { } Status::Status(const Status& status) : code(status.code), message(status.message) { if (status.getInnerStatus()) { innerStatus = std::make_unique<Status>(*status.getInnerStatus()); } } Status& Status::operator = (const Status& status) { if (this != &status) { code = status.code; message = status.message; if (status.getInnerStatus()) { innerStatus = std::make_unique<Status>(*status.getInnerStatus()); } } return *this; }
26.315789
95
0.693
anisimovsergey
9c53ed171322781afb9ad396e486b5d95153740e
15,909
cpp
C++
test/language/base_types/cpp/BaseTypesTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
2
2019-02-06T17:50:24.000Z
2019-11-20T16:51:34.000Z
test/language/base_types/cpp/BaseTypesTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
1
2019-11-25T16:25:51.000Z
2019-11-25T18:09:39.000Z
test/language/base_types/cpp/BaseTypesTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
null
null
null
#include <limits> #include "gtest/gtest.h" #include "base_types/BaseTypes.h" namespace base_types { class BaseTypesTest : public ::testing::Test { protected: BaseTypes m_baseTypes; }; TEST_F(BaseTypesTest, uint8Type) { const uint8_t maxUint8Type = std::numeric_limits<uint8_t>::max(); m_baseTypes.setUint8Type(maxUint8Type); const uint8_t uint8Type = m_baseTypes.getUint8Type(); ASSERT_EQ(maxUint8Type, uint8Type); } TEST_F(BaseTypesTest, uint16Type) { const uint16_t maxUint16Type = std::numeric_limits<uint16_t>::max(); m_baseTypes.setUint16Type(maxUint16Type); const uint16_t uint16Type = m_baseTypes.getUint16Type(); ASSERT_EQ(maxUint16Type, uint16Type); } TEST_F(BaseTypesTest, uint32Type) { const uint32_t maxUint32Type = std::numeric_limits<uint32_t>::max(); m_baseTypes.setUint32Type(maxUint32Type); const uint32_t uint32Type = m_baseTypes.getUint32Type(); ASSERT_EQ(maxUint32Type, uint32Type); } TEST_F(BaseTypesTest, uint64Type) { const uint64_t maxUint64Type = std::numeric_limits<uint64_t>::max(); m_baseTypes.setUint64Type(maxUint64Type); const uint64_t uint64Type = m_baseTypes.getUint64Type(); ASSERT_EQ(maxUint64Type, uint64Type); } TEST_F(BaseTypesTest, int8Type) { const int8_t maxInt8Type = std::numeric_limits<int8_t>::max(); m_baseTypes.setInt8Type(maxInt8Type); const int8_t int8Type = m_baseTypes.getInt8Type(); ASSERT_EQ(maxInt8Type, int8Type); } TEST_F(BaseTypesTest, int16Type) { const int16_t maxInt16Type = std::numeric_limits<int16_t>::max(); m_baseTypes.setInt16Type(maxInt16Type); const int16_t int16Type = m_baseTypes.getInt16Type(); ASSERT_EQ(maxInt16Type, int16Type); } TEST_F(BaseTypesTest, int32Type) { const int32_t maxInt32Type = std::numeric_limits<int32_t>::max(); m_baseTypes.setInt32Type(maxInt32Type); const int32_t int32Type = m_baseTypes.getInt32Type(); ASSERT_EQ(maxInt32Type, int32Type); } TEST_F(BaseTypesTest, int64Type) { const int64_t maxInt64Type = std::numeric_limits<int64_t>::max(); m_baseTypes.setInt64Type(maxInt64Type); const int64_t int64Type = m_baseTypes.getInt64Type(); ASSERT_EQ(maxInt64Type, int64Type); } TEST_F(BaseTypesTest, bitfield7Type) { const uint8_t maxBitfield7Type = UINT8_C(0x7F); m_baseTypes.setBitfield7Type(maxBitfield7Type); const uint8_t bitfield7Type = m_baseTypes.getBitfield7Type(); ASSERT_EQ(maxBitfield7Type, bitfield7Type); } TEST_F(BaseTypesTest, bitfield8Type) { const uint8_t maxBitfield8Type = std::numeric_limits<uint8_t>::max(); m_baseTypes.setBitfield8Type(maxBitfield8Type); const uint8_t bitfield8Type = m_baseTypes.getBitfield8Type(); ASSERT_EQ(maxBitfield8Type, bitfield8Type); } TEST_F(BaseTypesTest, bitfield15Type) { const uint16_t maxBitfield15Type = UINT16_C(0x7FFF); m_baseTypes.setBitfield15Type(maxBitfield15Type); const uint16_t bitfield15Type = m_baseTypes.getBitfield15Type(); ASSERT_EQ(maxBitfield15Type, bitfield15Type); } TEST_F(BaseTypesTest, bitfield16Type) { const uint16_t maxBitfield16Type = std::numeric_limits<uint16_t>::max(); m_baseTypes.setBitfield16Type(maxBitfield16Type); const uint16_t bitfield16Type = m_baseTypes.getBitfield16Type(); ASSERT_EQ(maxBitfield16Type, bitfield16Type); } TEST_F(BaseTypesTest, bitfield31Type) { const uint32_t maxBitfield31Type = UINT32_C(0x7FFFFFFF); m_baseTypes.setBitfield31Type(maxBitfield31Type); const uint32_t bitfield31Type = m_baseTypes.getBitfield31Type(); ASSERT_EQ(maxBitfield31Type, bitfield31Type); } TEST_F(BaseTypesTest, bitfield32Type) { const uint32_t maxBitfield32Type = std::numeric_limits<uint32_t>::max(); m_baseTypes.setBitfield32Type(maxBitfield32Type); const uint32_t bitfield32Type = m_baseTypes.getBitfield32Type(); ASSERT_EQ(maxBitfield32Type, bitfield32Type); } TEST_F(BaseTypesTest, bitfield63Type) { const uint64_t maxBitfield63Type = UINT64_C(0x7FFFFFFFFFFFFFFF); m_baseTypes.setBitfield63Type(maxBitfield63Type); const uint64_t bitfield63Type = m_baseTypes.getBitfield63Type(); ASSERT_EQ(maxBitfield63Type, bitfield63Type); } TEST_F(BaseTypesTest, variableBitfieldType) { const uint64_t maxVariableBitfieldType = std::numeric_limits<uint64_t>::max(); m_baseTypes.setVariableBitfieldType(maxVariableBitfieldType); const uint64_t variableBitfieldType = m_baseTypes.getVariableBitfieldType(); ASSERT_EQ(maxVariableBitfieldType, variableBitfieldType); } TEST_F(BaseTypesTest, variableBitfield8Type) { const uint8_t maxVariableBitfield8Type = std::numeric_limits<uint8_t>::max(); m_baseTypes.setVariableBitfield8Type(maxVariableBitfield8Type); const uint8_t variableBitfield8Type = m_baseTypes.getVariableBitfield8Type(); ASSERT_EQ(maxVariableBitfield8Type, variableBitfield8Type); } TEST_F(BaseTypesTest, intfield8Type) { const int8_t maxIntfield8Type = std::numeric_limits<int8_t>::max(); m_baseTypes.setIntfield8Type(maxIntfield8Type); const int8_t intfield8Type = m_baseTypes.getIntfield8Type(); ASSERT_EQ(maxIntfield8Type, intfield8Type); } TEST_F(BaseTypesTest, intfield16Type) { const int16_t maxIntfield16Type = std::numeric_limits<int16_t>::max(); m_baseTypes.setIntfield16Type(maxIntfield16Type); const int16_t intfield16Type = m_baseTypes.getIntfield16Type(); ASSERT_EQ(maxIntfield16Type, intfield16Type); } TEST_F(BaseTypesTest, intfield32Type) { const int32_t maxIntfield32Type = std::numeric_limits<int32_t>::max(); m_baseTypes.setIntfield32Type(maxIntfield32Type); const int32_t intfield32Type = m_baseTypes.getIntfield32Type(); ASSERT_EQ(maxIntfield32Type, intfield32Type); } TEST_F(BaseTypesTest, intfield64Type) { const int64_t maxIntfield64Type = std::numeric_limits<int64_t>::max(); m_baseTypes.setIntfield64Type(maxIntfield64Type); const int64_t intfield64Type = m_baseTypes.getIntfield64Type(); ASSERT_EQ(maxIntfield64Type, intfield64Type); } TEST_F(BaseTypesTest, variableIntfieldType) { const int16_t maxVariableIntfieldType = std::numeric_limits<int16_t>::max(); m_baseTypes.setVariableIntfieldType(maxVariableIntfieldType); const int16_t variableIntfieldType = m_baseTypes.getVariableIntfieldType(); ASSERT_EQ(maxVariableIntfieldType, variableIntfieldType); } TEST_F(BaseTypesTest, variableIntfield8Type) { const int8_t maxVariableIntfield8Type = std::numeric_limits<int8_t>::max(); m_baseTypes.setVariableIntfield8Type(maxVariableIntfield8Type); const int8_t variableIntfield8Type = m_baseTypes.getVariableIntfield8Type(); ASSERT_EQ(maxVariableIntfield8Type, variableIntfield8Type); } TEST_F(BaseTypesTest, float16Type) { const float maxFloat16Type = std::numeric_limits<float>::max(); m_baseTypes.setFloat16Type(maxFloat16Type); const float float16Type = m_baseTypes.getFloat16Type(); ASSERT_TRUE(maxFloat16Type - float16Type <= std::numeric_limits<float>::epsilon()); } TEST_F(BaseTypesTest, float32Type) { const float maxFloat32Type = std::numeric_limits<float>::max(); m_baseTypes.setFloat32Type(maxFloat32Type); const float float32Type = m_baseTypes.getFloat32Type(); ASSERT_TRUE(maxFloat32Type - float32Type <= std::numeric_limits<float>::epsilon()); } TEST_F(BaseTypesTest, float64Type) { const double maxFloat64Type = std::numeric_limits<double>::max(); m_baseTypes.setFloat64Type(maxFloat64Type); const double float64Type = m_baseTypes.getFloat64Type(); ASSERT_TRUE(maxFloat64Type - float64Type <= std::numeric_limits<double>::epsilon()); } TEST_F(BaseTypesTest, varuint16Type) { const uint16_t maxVaruint16Type = (UINT16_C(1) << 15) - 1; m_baseTypes.setVaruint16Type(maxVaruint16Type); const uint16_t varuint16Type = m_baseTypes.getVaruint16Type(); ASSERT_EQ(maxVaruint16Type, varuint16Type); } TEST_F(BaseTypesTest, varuint32Type) { const uint32_t maxVaruint32Type = (UINT32_C(1) << 29) - 1; m_baseTypes.setVaruint32Type(maxVaruint32Type); const uint32_t varuint32Type = m_baseTypes.getVaruint32Type(); ASSERT_EQ(maxVaruint32Type, varuint32Type); } TEST_F(BaseTypesTest, varuint64Type) { const uint64_t maxVaruint64Type = (UINT64_C(1) << 57) - 1; m_baseTypes.setVaruint64Type(maxVaruint64Type); const uint64_t varuint64Type = m_baseTypes.getVaruint64Type(); ASSERT_EQ(maxVaruint64Type, varuint64Type); } TEST_F(BaseTypesTest, varuintTypeMin) { const uint64_t minVaruintType = 0; m_baseTypes.setVaruintType(minVaruintType); const uint64_t readMinVaruintType = m_baseTypes.getVaruintType(); ASSERT_EQ(minVaruintType, readMinVaruintType); const uint64_t maxVaruintType = UINT64_MAX; m_baseTypes.setVaruintType(maxVaruintType); const uint64_t readMaxVaruintType = m_baseTypes.getVaruintType(); ASSERT_EQ(maxVaruintType, readMaxVaruintType); } TEST_F(BaseTypesTest, varint16Type) { const int16_t maxVarint16Type = (INT16_C(1) << 14) - 1; m_baseTypes.setVarint16Type(maxVarint16Type); const int16_t varint16Type = m_baseTypes.getVarint16Type(); ASSERT_EQ(maxVarint16Type, varint16Type); } TEST_F(BaseTypesTest, varint32Type) { const int32_t maxVarint32Type = (INT32_C(1) << 28) - 1; m_baseTypes.setVarint32Type(maxVarint32Type); const int32_t varint32Type = m_baseTypes.getVarint32Type(); ASSERT_EQ(maxVarint32Type, varint32Type); } TEST_F(BaseTypesTest, varint64Type) { const int64_t maxVarint64Type = (INT64_C(1) << 56) - 1; m_baseTypes.setVarint64Type(maxVarint64Type); const int64_t varint64Type = m_baseTypes.getVarint64Type(); ASSERT_EQ(maxVarint64Type, varint64Type); } TEST_F(BaseTypesTest, varintTypeMin) { const int64_t minVarintType = INT64_MIN; m_baseTypes.setVarintType(minVarintType); const int64_t readMinVarintType = m_baseTypes.getVarintType(); ASSERT_EQ(minVarintType, readMinVarintType); const int64_t maxVarintType = INT64_MAX; m_baseTypes.setVarintType(maxVarintType); const int64_t readMaxVarintType = m_baseTypes.getVarintType(); ASSERT_EQ(maxVarintType, readMaxVarintType); } TEST_F(BaseTypesTest, boolType) { m_baseTypes.setBoolType(true); const bool boolType = m_baseTypes.getBoolType(); ASSERT_EQ(true, boolType); } TEST_F(BaseTypesTest, stringType) { const std::string testString("TEST"); m_baseTypes.setStringType(testString); const std::string& stringType = m_baseTypes.getStringType(); ASSERT_TRUE(stringType.compare(testString) == 0); } TEST_F(BaseTypesTest, externType) { const zserio::BitBuffer testExtern(std::vector<uint8_t>({0xCD, 0x03}), 10); m_baseTypes.setExternType(testExtern); const zserio::BitBuffer& externType = m_baseTypes.getExternType(); ASSERT_EQ(testExtern, externType); } TEST_F(BaseTypesTest, bitSizeOf) { m_baseTypes.setBoolType(true); m_baseTypes.setUint8Type(1); m_baseTypes.setUint16Type(std::numeric_limits<uint16_t>::max()); m_baseTypes.setUint32Type(std::numeric_limits<uint32_t>::max()); m_baseTypes.setUint64Type(std::numeric_limits<uint64_t>::max()); m_baseTypes.setInt8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setInt16Type(std::numeric_limits<int16_t>::max()); m_baseTypes.setInt32Type(std::numeric_limits<int32_t>::max()); m_baseTypes.setInt64Type(std::numeric_limits<int64_t>::max()); m_baseTypes.setBitfield7Type(UINT8_C(0x7F)); m_baseTypes.setBitfield8Type(std::numeric_limits<uint8_t>::max()); m_baseTypes.setBitfield15Type(UINT16_C(0x7FFF)); m_baseTypes.setBitfield16Type(std::numeric_limits<uint16_t>::max()); m_baseTypes.setBitfield31Type(UINT32_C(0x7FFFFFFF)); m_baseTypes.setBitfield32Type(std::numeric_limits<uint32_t>::max()); m_baseTypes.setBitfield63Type(UINT64_C(0x7FFFFFFFFFFFFFFF)); m_baseTypes.setVariableBitfieldType(1); m_baseTypes.setVariableBitfield8Type(std::numeric_limits<uint8_t>::max()); m_baseTypes.setIntfield8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setIntfield16Type(std::numeric_limits<int16_t>::max()); m_baseTypes.setIntfield32Type(std::numeric_limits<int32_t>::max()); m_baseTypes.setIntfield64Type(std::numeric_limits<int64_t>::max()); m_baseTypes.setVariableIntfieldType(1); m_baseTypes.setVariableIntfield8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setFloat16Type(std::numeric_limits<float>::max()); m_baseTypes.setFloat32Type(std::numeric_limits<float>::max()); m_baseTypes.setFloat64Type(std::numeric_limits<double>::max()); m_baseTypes.setVaruint16Type((UINT16_C(1) << 15) - 1); m_baseTypes.setVaruint32Type((UINT32_C(1) << 29) - 1); m_baseTypes.setVaruint64Type((UINT64_C(1) << 57) - 1); m_baseTypes.setVaruintType(UINT64_MAX); m_baseTypes.setVarint16Type((INT16_C(1) << 14) - 1); m_baseTypes.setVarint32Type((INT32_C(1) << 28) - 1); m_baseTypes.setVarint64Type((INT64_C(1) << 56) - 1); m_baseTypes.setVarintType(INT64_MAX); m_baseTypes.setStringType("TEST"); m_baseTypes.setExternType(zserio::BitBuffer(std::vector<uint8_t>({0xCD, 0x03}), 10)); const size_t expectedBitSizeOf = 1102; ASSERT_EQ(expectedBitSizeOf, m_baseTypes.bitSizeOf()); } TEST_F(BaseTypesTest, readWrite) { m_baseTypes.setBoolType(true); m_baseTypes.setUint8Type(8); m_baseTypes.setUint16Type(std::numeric_limits<uint16_t>::max()); m_baseTypes.setUint32Type(std::numeric_limits<uint32_t>::max()); m_baseTypes.setUint64Type(std::numeric_limits<uint64_t>::max()); m_baseTypes.setInt8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setInt16Type(std::numeric_limits<int16_t>::max()); m_baseTypes.setInt32Type(std::numeric_limits<int32_t>::max()); m_baseTypes.setInt64Type(std::numeric_limits<int64_t>::max()); m_baseTypes.setBitfield7Type(UINT8_C(0x7F)); m_baseTypes.setBitfield8Type(std::numeric_limits<uint8_t>::max()); m_baseTypes.setBitfield15Type(UINT16_C(0x7FFF)); m_baseTypes.setBitfield16Type(std::numeric_limits<uint16_t>::max()); m_baseTypes.setBitfield31Type(UINT32_C(0x7FFFFFFF)); m_baseTypes.setBitfield32Type(std::numeric_limits<uint32_t>::max()); m_baseTypes.setBitfield63Type(UINT64_C(0x7FFFFFFFFFFFFFFF)); m_baseTypes.setVariableBitfieldType(std::numeric_limits<uint8_t>::max()); m_baseTypes.setVariableBitfield8Type(std::numeric_limits<uint8_t>::max()); m_baseTypes.setIntfield8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setIntfield16Type(std::numeric_limits<int16_t>::max()); m_baseTypes.setIntfield32Type(std::numeric_limits<int32_t>::max()); m_baseTypes.setIntfield64Type(std::numeric_limits<int64_t>::max()); m_baseTypes.setVariableIntfieldType(std::numeric_limits<int8_t>::max()); m_baseTypes.setVariableIntfield8Type(std::numeric_limits<int8_t>::max()); m_baseTypes.setFloat16Type(1.0f); m_baseTypes.setFloat32Type(std::numeric_limits<float>::max()); m_baseTypes.setFloat64Type(std::numeric_limits<double>::max()); m_baseTypes.setVaruint16Type((UINT16_C(1) << 15) - 1); m_baseTypes.setVaruint32Type((UINT32_C(1) << 29) - 1); m_baseTypes.setVaruint64Type((UINT64_C(1) << 57) - 1); m_baseTypes.setVaruintType(UINT64_MAX); m_baseTypes.setVarint16Type((INT16_C(1) << 14) - 1); m_baseTypes.setVarint32Type((INT32_C(1) << 28) - 1); m_baseTypes.setVarint64Type((INT64_C(1) << 56) - 1); m_baseTypes.setVarintType(INT64_MAX); m_baseTypes.setStringType("TEST"); m_baseTypes.setExternType(zserio::BitBuffer(std::vector<uint8_t>({0xCD, 0x03}), 10)); zserio::BitStreamWriter writer; m_baseTypes.write(writer); size_t bufferSize; const uint8_t* buffer = writer.getWriteBuffer(bufferSize); zserio::BitStreamReader reader(buffer, bufferSize); const BaseTypes readBaseTypes(reader); ASSERT_TRUE(m_baseTypes == readBaseTypes); } } // namespace base_types
38.242788
89
0.764976
Klebert-Engineering
9c5425cee3f7b340abff4705ef75e6911ccacbf4
1,487
cc
C++
net/http/http_proxy_client_socket_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
net/http/http_proxy_client_socket_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
net/http/http_proxy_client_socket_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_proxy_client_socket.h" #include "build/build_config.h" #include "net/base/address_list.h" #include "net/base/host_port_pair.h" #include "net/base/proxy_server.h" #include "net/socket/next_proto.h" #include "net/socket/socket_tag.h" #include "net/socket/socket_test_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { TEST(HttpProxyClientSocketTest, Tag) { StaticSocketDataProvider data; MockTaggingStreamSocket* tagging_sock = new MockTaggingStreamSocket(std::make_unique<MockTCPClientSocket>( AddressList(), nullptr /* net_log */, &data)); // |socket| takes ownership of |tagging_sock|, but the test keeps a non-owning // pointer to it. HttpProxyClientSocket socket(std::unique_ptr<StreamSocket>(tagging_sock), "", HostPortPair(), ProxyServer(), nullptr, false, false, NextProto(), nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ(tagging_sock->tag(), SocketTag()); #if defined(OS_ANDROID) SocketTag tag(0x12345678, 0x87654321); socket.ApplySocketTag(tag); EXPECT_EQ(tagging_sock->tag(), tag); #endif // OS_ANDROID } } // namespace } // namespace net
33.044444
80
0.709482
zealoussnow
9c56ca81ea5c09699806b48f266a19f636eb89df
9,051
hpp
C++
include/sprout/cstdlib/str_to_float.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/cstdlib/str_to_float.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/cstdlib/str_to_float.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_CSTDLIB_STR_TO_FLOAT_HPP #define SPROUT_CSTDLIB_STR_TO_FLOAT_HPP #include <cstdlib> #include <cmath> #include <type_traits> #include <sprout/config.hpp> #include <sprout/workaround/std/cstddef.hpp> #include <sprout/limits.hpp> #include <sprout/iterator/operation.hpp> #include <sprout/ctype/ascii.hpp> #include <sprout/detail/char_literal.hpp> #include <sprout/detail/char_type_of_consecutive.hpp> namespace sprout { namespace detail { template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_scale( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0, long n = 0, FloatType p10 = FloatType(10) ) { return n ? sprout::detail::str_to_float_impl_scale<FloatType>( str, negative, n & 1 ? (exponent < 0 ? number / p10 : number * p10) : number, num_digits, num_decimals, exponent, n >> 1, p10 * p10 ) : number ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_exponent_2( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0 ) { return exponent >= sprout::numeric_limits<FloatType>::min_exponent && exponent <= sprout::numeric_limits<FloatType>::max_exponent ? sprout::detail::str_to_float_impl_scale<FloatType>( str, negative, number, num_digits, num_decimals, exponent, exponent < 0 ? -exponent : exponent ) : HUGE_VAL ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_exponent_1( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0, long n = 0 ) { typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type; SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value); return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl_exponent_1<FloatType>( sprout::next(str), negative, number, num_digits, num_decimals, exponent, n * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type)) ) : sprout::detail::str_to_float_impl_exponent_2<FloatType>( str, negative, number, num_digits, num_decimals, negative ? exponent + n : exponent - n ) ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_exponent( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0 ) { typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type; return (*str == SPROUT_CHAR_LITERAL('e', char_type) || *str == SPROUT_CHAR_LITERAL('E', char_type)) ? *sprout::next(str) == SPROUT_CHAR_LITERAL('-', char_type) ? sprout::detail::str_to_float_impl_exponent_1<FloatType>( sprout::next(str, 2), true, number, num_digits, num_decimals, exponent ) : sprout::detail::str_to_float_impl_exponent_1<FloatType>( sprout::next(str, 2), false, number, num_digits, num_decimals, exponent ) : sprout::detail::str_to_float_impl_exponent_2<FloatType>( str, negative, number, num_digits, num_decimals, exponent ) ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_decimal_1( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0 ) { return num_digits == 0 ? FloatType() : sprout::detail::str_to_float_impl_exponent<FloatType>( str, negative, negative ? -number : number, num_digits, num_decimals, exponent ) ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl_decimal( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0, std::size_t num_decimals = 0, long exponent = 0 ) { typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type; SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value); return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl_decimal<FloatType>( sprout::next(str), negative, number * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type)), num_digits + 1, num_decimals + 1, exponent ) : sprout::detail::str_to_float_impl_decimal_1<FloatType>( str, negative, number, num_digits, num_decimals, exponent - num_decimals ) ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float_impl( NullTerminatedIterator const& str, bool negative, FloatType number = FloatType(), std::size_t num_digits = 0 ) { typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type; SPROUT_STATIC_ASSERT(sprout::detail::is_char_type_of_consecutive_digits<char_type>::value); return sprout::ascii::isdigit(*str) ? sprout::detail::str_to_float_impl<FloatType>( sprout::next(str), negative, number * 10 + (*str - SPROUT_CHAR_LITERAL('0', char_type)), num_digits + 1 ) : *str == SPROUT_CHAR_LITERAL('.', char_type) ? sprout::detail::str_to_float_impl_decimal<FloatType>( sprout::next(str), negative, number, num_digits ) : sprout::detail::str_to_float_impl_decimal_1<FloatType>( str, negative, number, num_digits ) ; } template<typename FloatType, typename NullTerminatedIterator> inline SPROUT_CONSTEXPR FloatType str_to_float(NullTerminatedIterator const& str) { typedef typename std::iterator_traits<NullTerminatedIterator>::value_type char_type; return sprout::ascii::isspace(*str) ? sprout::detail::str_to_float<FloatType>(sprout::next(str)) : *str == SPROUT_CHAR_LITERAL('-', char_type) ? sprout::detail::str_to_float_impl<FloatType>(sprout::next(str), true) : *str == SPROUT_CHAR_LITERAL('+', char_type) ? sprout::detail::str_to_float_impl<FloatType>(sprout::next(str), false) : sprout::detail::str_to_float_impl<FloatType>(str, false) ; } template<typename FloatType, typename NullTerminatedIterator, typename CharPtr> inline SPROUT_CONSTEXPR FloatType str_to_float(NullTerminatedIterator const& str, CharPtr* endptr) { return !endptr ? sprout::detail::str_to_float<FloatType>(str) #if defined(__MINGW32__) : std::is_same<typename std::remove_cv<FloatType>::type, float>::value ? ::strtof(&*str, endptr) : std::is_same<typename std::remove_cv<FloatType>::type, double>::value ? std::strtod(&*str, endptr) : ::strtold(&*str, endptr) #else : std::is_same<typename std::remove_cv<FloatType>::type, float>::value ? std::strtof(&*str, endptr) : std::is_same<typename std::remove_cv<FloatType>::type, double>::value ? std::strtod(&*str, endptr) : std::strtold(&*str, endptr) #endif ; } } // namespace detail // // str_to_float // template<typename FloatType, typename Char> inline SPROUT_CONSTEXPR typename std::enable_if< std::is_floating_point<FloatType>::value, FloatType >::type str_to_float(Char const* str, Char** endptr) { return sprout::detail::str_to_float<FloatType>(str, endptr); } template<typename FloatType, typename Char> inline SPROUT_CONSTEXPR typename std::enable_if< std::is_floating_point<FloatType>::value, FloatType >::type str_to_float(Char const* str, std::nullptr_t) { return sprout::detail::str_to_float<FloatType>(str); } template<typename FloatType, typename Char> inline SPROUT_CONSTEXPR typename std::enable_if< std::is_floating_point<FloatType>::value, FloatType >::type str_to_float(Char const* str) { return sprout::detail::str_to_float<FloatType>(str); } } // namespace sprout #endif // #ifndef SPROUT_CSTDLIB_STR_TO_FLOAT_HPP
30.681356
105
0.689537
thinkoid
9c578e32666ef7cd89a35e26154d369a33841d14
5,032
cpp
C++
inference-engine/src/multi_device/multi_device_async_infer_request.cpp
oxygenxo/openvino
a984e7e81bcf4a18138b57632914b5a88815282d
[ "Apache-2.0" ]
null
null
null
inference-engine/src/multi_device/multi_device_async_infer_request.cpp
oxygenxo/openvino
a984e7e81bcf4a18138b57632914b5a88815282d
[ "Apache-2.0" ]
27
2020-12-29T14:38:34.000Z
2022-02-21T13:04:03.000Z
inference-engine/src/multi_device/multi_device_async_infer_request.cpp
dorloff/openvino
1c3848a96fdd325b044babe6d5cd26db341cf85b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /////////////////////////////////////////////////////////////////////////////////////////////////// #include <string> #include <vector> #include <memory> #include <map> #include "multi_device_async_infer_request.hpp" namespace MultiDevicePlugin { using namespace InferenceEngine; MultiDeviceAsyncInferRequest::MultiDeviceAsyncInferRequest( const MultiDeviceInferRequest::Ptr& inferRequest, const bool needPerfCounters, const MultiDeviceExecutableNetwork::Ptr& multiDeviceExecutableNetwork, const ITaskExecutor::Ptr& callbackExecutor) : AsyncInferRequestThreadSafeDefault(inferRequest, nullptr, callbackExecutor), _multiDeviceExecutableNetwork{multiDeviceExecutableNetwork}, _inferRequest{inferRequest}, _needPerfCounters{needPerfCounters} { // this executor starts the inference while the task (checking the result) is passed to the next stage struct ThisRequestExecutor : public ITaskExecutor { explicit ThisRequestExecutor(MultiDeviceAsyncInferRequest* _this_) : _this{_this_} {} void run(Task task) override { auto workerInferRequest = _this->_workerInferRequest; workerInferRequest->_task = std::move(task); workerInferRequest->_inferRequest.StartAsync(); }; MultiDeviceAsyncInferRequest* _this = nullptr; }; _pipeline = { // if the request is coming with device-specific remote blobs make sure it is scheduled to the specific device only: { /*TaskExecutor*/ std::make_shared<ImmediateExecutor>(), /*task*/ [this] { // by default, no preferred device: _multiDeviceExecutableNetwork->_thisPreferredDeviceName = ""; // if any input is remote (e.g. was set with SetBlob), let' use the corresponding device for (const auto &it : _multiDeviceExecutableNetwork->GetInputsInfo()) { Blob::Ptr b; _inferRequest->GetBlob(it.first.c_str(), b); auto r = b->as<RemoteBlob>(); if (r) { const auto name = r->getDeviceName(); const auto res = std::find_if( _multiDeviceExecutableNetwork->_devicePrioritiesInitial.cbegin(), _multiDeviceExecutableNetwork->_devicePrioritiesInitial.cend(), [&name](const MultiDevicePlugin::DeviceInformation& d){ return d.deviceName == name; }); if (_multiDeviceExecutableNetwork->_devicePrioritiesInitial.cend() == res) { THROW_IE_EXCEPTION << "None of the devices (for which current MULTI-device configuration was " "initialized) supports a remote blob created on the device named " << name; } else { // it is ok to take the c_str() here (as pointed in the multi_device_exec_network.hpp we need to use const char*) // as the original strings are from the "persistent" vector (with the right lifetime) _multiDeviceExecutableNetwork->_thisPreferredDeviceName = res->deviceName.c_str(); break; } } } }}, // as the scheduling algo may select any device, this stage accepts the scheduling decision (actual workerRequest) // then sets the device-agnostic blobs to the actual (device-specific) request { /*TaskExecutor*/ _multiDeviceExecutableNetwork, /*task*/ [this] { _workerInferRequest = MultiDeviceExecutableNetwork::_thisWorkerInferRequest; _inferRequest->SetBlobsToAnotherRequest(_workerInferRequest->_inferRequest); }}, // final task in the pipeline: { /*TaskExecutor*/std::make_shared<ThisRequestExecutor>(this), /*task*/ [this] { auto status = _workerInferRequest->_status; if (InferenceEngine::StatusCode::OK != status) { if (nullptr != InferenceEngine::CurrentException()) std::rethrow_exception(InferenceEngine::CurrentException()); else THROW_IE_EXCEPTION << InferenceEngine::details::as_status << status; } if (_needPerfCounters) _perfMap = _workerInferRequest->_inferRequest.GetPerformanceCounts(); }} }; } void MultiDeviceAsyncInferRequest::Infer_ThreadUnsafe() { InferUsingAsync(); } void MultiDeviceAsyncInferRequest::GetPerformanceCounts_ThreadUnsafe(std::map<std::string, InferenceEngineProfileInfo> &perfMap) const { perfMap = std::move(_perfMap); } MultiDeviceAsyncInferRequest::~MultiDeviceAsyncInferRequest() { StopAndWait(); } } // namespace MultiDevicePlugin
50.828283
141
0.614269
oxygenxo
9c59b39adaec4554bc712f329391175a5ffd0c10
3,695
cpp
C++
src/Bme280Spi.cpp
karol57/Bme280SpiTest
ecbd64a71396f63be1e4595b2562f6feaa6690ae
[ "MIT" ]
null
null
null
src/Bme280Spi.cpp
karol57/Bme280SpiTest
ecbd64a71396f63be1e4595b2562f6feaa6690ae
[ "MIT" ]
null
null
null
src/Bme280Spi.cpp
karol57/Bme280SpiTest
ecbd64a71396f63be1e4595b2562f6feaa6690ae
[ "MIT" ]
null
null
null
#include "Bme280Spi.hpp" #include <cstring> #include <iostream> #include <thread> #include <chrono> namespace { void ensureValidSpiSpeed(SpiDevice& spi) { constexpr uint32_t Mhz20 = 20'000'000; if (const uint32_t spiSpeed = spi.getMaxSpeedHz(); spiSpeed > Mhz20) { spi.setMaxSpeedHz(Mhz20); std::cout << "Reduced SPI speed from " << spiSpeed << " Hz to " << Mhz20 << " Hz" << std::endl; } } void delayUs(uint32_t period, void */*intf_ptr*/) { std::this_thread::sleep_for(std::chrono::microseconds(period)); } int8_t spiRead(uint8_t reg_addr, uint8_t * const reg_data, uint32_t len, void * const intf_ptr) { if (not reg_data or not intf_ptr) return BME280_E_NULL_PTR; SpiDevice& bme280 = *reinterpret_cast<SpiDevice*>(intf_ptr); spi_ioc_transfer xfer[2] = {}; xfer[0].tx_buf = reinterpret_cast<uintptr_t>(&reg_addr); xfer[0].len = 1; xfer[1].rx_buf = reinterpret_cast<uintptr_t>(reg_data); xfer[1].len = len; bme280.transfer(xfer); return BME280_OK; } int8_t spiWrite(uint8_t reg_addr, const uint8_t * const reg_data, uint32_t len, void * const intf_ptr) { if (not reg_data or not intf_ptr) return BME280_E_NULL_PTR; SpiDevice& bme280 = *reinterpret_cast<SpiDevice*>(intf_ptr); spi_ioc_transfer xfer[2] = {}; xfer[0].tx_buf = reinterpret_cast<uintptr_t>(&reg_addr); xfer[0].len = 1; xfer[1].tx_buf = reinterpret_cast<uintptr_t>(reg_data); xfer[1].len = len; bme280.transfer(xfer); return BME280_OK; } [[gnu::cold, noreturn]] static void throwBME280Error(int8_t error) { switch (error) { case BME280_E_NULL_PTR: throw std::runtime_error("BME280: Null pointer"); case BME280_E_DEV_NOT_FOUND: throw std::runtime_error("BME280: Device not found"); case BME280_E_INVALID_LEN: throw std::runtime_error("BME280: Invalid length"); case BME280_E_COMM_FAIL: throw std::runtime_error("BME280: Communication failure"); case BME280_E_SLEEP_MODE_FAIL: throw std::runtime_error("BME280: Sleep mode failure"); case BME280_E_NVM_COPY_FAILED: throw std::runtime_error("BME280: NVM copy failed"); default: throw std::runtime_error("BME280: Unknown error " + std::to_string(error)); } } static void verifyBme280Result(int8_t result) { if (result < 0) throwBME280Error(result); switch (result) { case BME280_OK: return; case BME280_W_INVALID_OSR_MACRO: std::cerr << "BME280: Invalid osr macro"; break; default: std::cerr << "BME280: Unknown warning " << result; } } } Bme280Spi::Bme280Spi(const char* path) : m_spi(path) { ensureValidSpiSpeed(m_spi); m_dev.intf_ptr = &m_spi; m_dev.intf = BME280_SPI_INTF; m_dev.read = spiRead; m_dev.write = spiWrite; m_dev.delay_us = delayUs; verifyBme280Result(bme280_init(&m_dev)); // Temporary default initialization m_dev.settings.osr_h = BME280_OVERSAMPLING_1X; m_dev.settings.osr_p = BME280_OVERSAMPLING_16X; m_dev.settings.osr_t = BME280_OVERSAMPLING_2X; m_dev.settings.filter = BME280_FILTER_COEFF_16; uint8_t settings_sel = BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL | BME280_OSR_HUM_SEL | BME280_FILTER_SEL; verifyBme280Result(bme280_set_sensor_settings(settings_sel, &m_dev)); verifyBme280Result(bme280_set_sensor_mode(BME280_NORMAL_MODE, &m_dev)); std::this_thread::sleep_for(std::chrono::milliseconds(bme280_cal_meas_delay(&m_dev.settings))); } bme280_data Bme280Spi::getData() { bme280_data result; verifyBme280Result(bme280_get_sensor_data(BME280_ALL, &result, &m_dev)); return result; }
32.699115
111
0.69364
karol57
9c5a54d102180c96470f77c1515c8b5ea4243363
3,115
cpp
C++
trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-08-02-ZOJ-Monthly-2015-July/F.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <cstdio> #include <iostream> using namespace std; const int N = 10000010; int n, m; int num[N], a[111111]; bool U_prime[N]; int cnt = 0; struct Node { int l, r, Max, sum; } tree[400444]; void update(int root) { tree[root].Max = max(tree[root << 1].Max, tree[root << 1 | 1].Max); tree[root].sum = tree[root << 1].sum + tree[root << 1 | 1].sum; return; } void build(int root, int x, int y) { tree[root].l = x, tree[root].r = y; if (x == y) { tree[root].Max = a[x]; tree[root].sum = num[a[x]]; return; } int mid = x + y >> 1; build(root << 1, x, mid); build(root << 1 | 1, mid + 1, y); update(root); } void update(int root, int x, int y) { if (tree[root].l == tree[root].r) { tree[root].Max = y; tree[root].sum = num[y]; return; } int mid = tree[root].l + tree[root].r >> 1; if (x <= mid) { update(root << 1, x, y); } else { update(root << 1 | 1, x, y); } update(root); } int Query(int root, int x, int y) { if (tree[root].l == x && tree[root].r == y) { return tree[root].sum; } int mid = tree[root].l + tree[root].r >> 1; if (y <= mid) { return Query(root << 1, x, y); } else if (x > mid) { return Query(root << 1 | 1, x, y); } else { return Query(root << 1, x, mid) + Query(root << 1 | 1, mid + 1, y); } } void update(int root, int x, int y, int key) { if (tree[root].l == x && tree[root].r == y && tree[root].Max < key) { return; } if (tree[root].l == tree[root].r) { tree[root].Max %= key; tree[root].sum = num[tree[root].Max]; return; } int mid = tree[root].l + tree[root].r >> 1; if (y <= mid) { update(root << 1, x, y, key); } else if (x > mid) { update(root << 1 | 1, x, y, key); } else { update(root << 1, x, mid, key), update(root << 1 | 1, mid + 1, y, key); } update(root); } int main() { for (int i = 2; i <= N - 5; i++) { if (!U_prime[i]) { num[i] = 1; } else { continue; } for (int j = 2 * i; j <= N - 5; j += i) { U_prime[j] = true; } } int now = 2; for (; now <= N - 5; now *= 2) { num[now] = 1; } num[6] = num[0] = num[1] = 1; while (scanf("%d", &n) == 1) { for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } build(1, 1, n); int m; scanf("%d", &m); for (int i = 1; i <= m; i++) { int type; scanf("%d", &type); if (type == 1) { int x, y; scanf("%d%d", &x, &y); printf("%d\n", Query(1, x, y)); } if (type == 2) { int x, y, r; scanf("%d%d%d", &x, &y, &r); update(1, x, y, r); } if (type == 3) { int x, r; scanf("%d%d", &x, &r); update(1, x, r); } } } return 0; }
23.961538
79
0.402247
HcPlu
9c5aea0a6ffeba117367b70a8617ce4bca0ed544
4,936
cpp
C++
ame/src/v20190916/model/TRTCJoinRoomInput.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
ame/src/v20190916/model/TRTCJoinRoomInput.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
ame/src/v20190916/model/TRTCJoinRoomInput.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ame/v20190916/model/TRTCJoinRoomInput.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ame::V20190916::Model; using namespace std; TRTCJoinRoomInput::TRTCJoinRoomInput() : m_signHasBeenSet(false), m_roomIdHasBeenSet(false), m_sdkAppIdHasBeenSet(false), m_userIdHasBeenSet(false) { } CoreInternalOutcome TRTCJoinRoomInput::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Sign") && !value["Sign"].IsNull()) { if (!value["Sign"].IsString()) { return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.Sign` IsString=false incorrectly").SetRequestId(requestId)); } m_sign = string(value["Sign"].GetString()); m_signHasBeenSet = true; } if (value.HasMember("RoomId") && !value["RoomId"].IsNull()) { if (!value["RoomId"].IsString()) { return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.RoomId` IsString=false incorrectly").SetRequestId(requestId)); } m_roomId = string(value["RoomId"].GetString()); m_roomIdHasBeenSet = true; } if (value.HasMember("SdkAppId") && !value["SdkAppId"].IsNull()) { if (!value["SdkAppId"].IsString()) { return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.SdkAppId` IsString=false incorrectly").SetRequestId(requestId)); } m_sdkAppId = string(value["SdkAppId"].GetString()); m_sdkAppIdHasBeenSet = true; } if (value.HasMember("UserId") && !value["UserId"].IsNull()) { if (!value["UserId"].IsString()) { return CoreInternalOutcome(Core::Error("response `TRTCJoinRoomInput.UserId` IsString=false incorrectly").SetRequestId(requestId)); } m_userId = string(value["UserId"].GetString()); m_userIdHasBeenSet = true; } return CoreInternalOutcome(true); } void TRTCJoinRoomInput::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_signHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Sign"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_sign.c_str(), allocator).Move(), allocator); } if (m_roomIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RoomId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_roomId.c_str(), allocator).Move(), allocator); } if (m_sdkAppIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SdkAppId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_sdkAppId.c_str(), allocator).Move(), allocator); } if (m_userIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UserId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_userId.c_str(), allocator).Move(), allocator); } } string TRTCJoinRoomInput::GetSign() const { return m_sign; } void TRTCJoinRoomInput::SetSign(const string& _sign) { m_sign = _sign; m_signHasBeenSet = true; } bool TRTCJoinRoomInput::SignHasBeenSet() const { return m_signHasBeenSet; } string TRTCJoinRoomInput::GetRoomId() const { return m_roomId; } void TRTCJoinRoomInput::SetRoomId(const string& _roomId) { m_roomId = _roomId; m_roomIdHasBeenSet = true; } bool TRTCJoinRoomInput::RoomIdHasBeenSet() const { return m_roomIdHasBeenSet; } string TRTCJoinRoomInput::GetSdkAppId() const { return m_sdkAppId; } void TRTCJoinRoomInput::SetSdkAppId(const string& _sdkAppId) { m_sdkAppId = _sdkAppId; m_sdkAppIdHasBeenSet = true; } bool TRTCJoinRoomInput::SdkAppIdHasBeenSet() const { return m_sdkAppIdHasBeenSet; } string TRTCJoinRoomInput::GetUserId() const { return m_userId; } void TRTCJoinRoomInput::SetUserId(const string& _userId) { m_userId = _userId; m_userIdHasBeenSet = true; } bool TRTCJoinRoomInput::UserIdHasBeenSet() const { return m_userIdHasBeenSet; }
27.120879
144
0.680308
suluner
9c615b3d65c782c7ad7496bbf2b3e12ed4f1684a
12,903
cpp
C++
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Game/CarlaGameModeBase.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
1
2021-04-07T11:45:18.000Z
2021-04-07T11:45:18.000Z
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Game/CarlaGameModeBase.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
2
2021-03-31T19:58:35.000Z
2021-12-13T20:47:16.000Z
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Game/CarlaGameModeBase.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
1
2021-03-28T07:13:12.000Z
2021-03-28T07:13:12.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "Carla.h" #include "Carla/Game/CarlaGameModeBase.h" #include "Carla/Game/CarlaHUD.h" #include "Engine/DecalActor.h" #include <compiler/disable-ue4-macros.h> #include <carla/rpc/WeatherParameters.h> #include "carla/opendrive/OpenDriveParser.h" #include "carla/road/element/RoadInfoSignal.h" #include <compiler/enable-ue4-macros.h> #include "Async/ParallelFor.h" #include "DynamicRHI.h" #include "DrawDebugHelpers.h" #include "Kismet/KismetSystemLibrary.h" namespace cr = carla::road; namespace cre = carla::road::element; ACarlaGameModeBase::ACarlaGameModeBase(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.TickGroup = TG_PrePhysics; bAllowTickBeforeBeginPlay = false; Episode = CreateDefaultSubobject<UCarlaEpisode>(TEXT("Episode")); Recorder = CreateDefaultSubobject<ACarlaRecorder>(TEXT("Recorder")); // HUD HUDClass = ACarlaHUD::StaticClass(); TaggerDelegate = CreateDefaultSubobject<UTaggerDelegate>(TEXT("TaggerDelegate")); CarlaSettingsDelegate = CreateDefaultSubobject<UCarlaSettingsDelegate>(TEXT("CarlaSettingsDelegate")); } void ACarlaGameModeBase::AddSceneCaptureSensor(ASceneCaptureSensor* SceneCaptureSensor) { uint32 ImageWidth = SceneCaptureSensor->ImageWidth; uint32 ImageHeight = SceneCaptureSensor->ImageHeight; if(AtlasTextureWidth < ImageWidth) { IsAtlasTextureValid = false; AtlasTextureWidth = ImageWidth; } if(AtlasTextureHeight < (CurrentAtlasTextureHeight + ImageHeight) ) { IsAtlasTextureValid = false; AtlasTextureHeight = CurrentAtlasTextureHeight + ImageHeight; } SceneCaptureSensor->PositionInAtlas = FIntVector(0, CurrentAtlasTextureHeight, 0); CurrentAtlasTextureHeight += ImageHeight; SceneCaptureSensors.Add(SceneCaptureSensor); UE_LOG(LogCarla, Warning, TEXT("ACarlaGameModeBase::AddSceneCaptureSensor %d %dx%d"), SceneCaptureSensors.Num(), AtlasTextureWidth, AtlasTextureHeight); } void ACarlaGameModeBase::RemoveSceneCaptureSensor(ASceneCaptureSensor* SceneCaptureSensor) { FlushRenderingCommands(); // Remove camera SceneCaptureSensors.Remove(SceneCaptureSensor); // Recalculate PositionInAtlas for each camera AtlasTextureWidth = 0u; CurrentAtlasTextureHeight = 0u; for(ASceneCaptureSensor* Camera : SceneCaptureSensors) { Camera->PositionInAtlas = FIntVector(0, CurrentAtlasTextureHeight, 0); CurrentAtlasTextureHeight += Camera->ImageHeight; if(AtlasTextureWidth < Camera->ImageWidth) { AtlasTextureWidth = Camera->ImageWidth; } } AtlasTextureHeight = CurrentAtlasTextureHeight; IsAtlasTextureValid = false; } void ACarlaGameModeBase::InitGame( const FString &MapName, const FString &Options, FString &ErrorMessage) { Super::InitGame(MapName, Options, ErrorMessage); checkf( Episode != nullptr, TEXT("Missing episode, can't continue without an episode!")); #if WITH_EDITOR { // When playing in editor the map name gets an extra prefix, here we // remove it. FString CorrectedMapName = MapName; constexpr auto PIEPrefix = TEXT("UEDPIE_0_"); CorrectedMapName.RemoveFromStart(PIEPrefix); UE_LOG(LogCarla, Log, TEXT("Corrected map name from %s to %s"), *MapName, *CorrectedMapName); Episode->MapName = CorrectedMapName; } #else Episode->MapName = MapName; #endif // WITH_EDITOR auto World = GetWorld(); check(World != nullptr); GameInstance = Cast<UCarlaGameInstance>(GetGameInstance()); checkf( GameInstance != nullptr, TEXT("GameInstance is not a UCarlaGameInstance, did you forget to set " "it in the project settings?")); if (TaggerDelegate != nullptr) { TaggerDelegate->RegisterSpawnHandler(World); } else { UE_LOG(LogCarla, Error, TEXT("Missing TaggerDelegate!")); } if(CarlaSettingsDelegate != nullptr) { CarlaSettingsDelegate->ApplyQualityLevelPostRestart(); CarlaSettingsDelegate->RegisterSpawnHandler(World); } else { UE_LOG(LogCarla, Error, TEXT("Missing CarlaSettingsDelegate!")); } if (WeatherClass != nullptr) { Episode->Weather = World->SpawnActor<AWeather>(WeatherClass); } else { UE_LOG(LogCarla, Error, TEXT("Missing weather class!")); } GameInstance->NotifyInitGame(); SpawnActorFactories(); // make connection between Episode and Recorder Recorder->SetEpisode(Episode); Episode->SetRecorder(Recorder); ParseOpenDrive(MapName); } void ACarlaGameModeBase::RestartPlayer(AController *NewPlayer) { if (CarlaSettingsDelegate != nullptr) { CarlaSettingsDelegate->ApplyQualityLevelPreRestart(); } Super::RestartPlayer(NewPlayer); } void ACarlaGameModeBase::BeginPlay() { Super::BeginPlay(); if (true) { /// @todo If semantic segmentation enabled. check(GetWorld() != nullptr); ATagger::TagActorsInLevel(*GetWorld(), true); TaggerDelegate->SetSemanticSegmentationEnabled(); } // HACK: fix transparency see-through issues // The problem: transparent objects are visible through walls. // This is due to a weird interaction between the SkyAtmosphere component, // the shadows of a directional light (the sun) // and the custom depth set to 3 used for semantic segmentation // The solution: Spawn a Decal. // It just works! GetWorld()->SpawnActor<ADecalActor>( FVector(0,0,-1000000), FRotator(0,0,0), FActorSpawnParameters()); ATrafficLightManager* Manager = GetTrafficLightManager(); Manager->InitializeTrafficLights(); Episode->InitializeAtBeginPlay(); GameInstance->NotifyBeginEpisode(*Episode); if (Episode->Weather != nullptr) { Episode->Weather->ApplyWeather(carla::rpc::WeatherParameters::Default); } /// @todo Recorder should not tick here, FCarlaEngine should do it. // check if replayer is waiting to autostart if (Recorder) { Recorder->GetReplayer()->CheckPlayAfterMapLoaded(); } CaptureAtlasDelegate = FCoreDelegates::OnEndFrame.AddUObject(this, &ACarlaGameModeBase::CaptureAtlas); } void ACarlaGameModeBase::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); /// @todo Recorder should not tick here, FCarlaEngine should do it. if (Recorder) { Recorder->Tick(DeltaSeconds); } SendAtlas(); } void ACarlaGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason) { Episode->EndPlay(); GameInstance->NotifyEndEpisode(); Super::EndPlay(EndPlayReason); if ((CarlaSettingsDelegate != nullptr) && (EndPlayReason != EEndPlayReason::EndPlayInEditor)) { CarlaSettingsDelegate->Reset(); } FCoreDelegates::OnEndFrame.Remove(CaptureAtlasDelegate); } void ACarlaGameModeBase::SpawnActorFactories() { auto *World = GetWorld(); check(World != nullptr); for (auto &FactoryClass : ActorFactories) { if (FactoryClass != nullptr) { auto *Factory = World->SpawnActor<ACarlaActorFactory>(FactoryClass); if (Factory != nullptr) { Episode->RegisterActorFactory(*Factory); ActorFactoryInstances.Add(Factory); } else { UE_LOG(LogCarla, Error, TEXT("Failed to spawn actor spawner")); } } } } void ACarlaGameModeBase::ParseOpenDrive(const FString &MapName) { std::string opendrive_xml = carla::rpc::FromLongFString(UOpenDrive::LoadXODR(MapName)); Map = carla::opendrive::OpenDriveParser::Load(opendrive_xml); if (!Map.has_value()) { UE_LOG(LogCarla, Error, TEXT("Invalid Map")); } else { Episode->MapGeoReference = Map->GetGeoReference(); } } ATrafficLightManager* ACarlaGameModeBase::GetTrafficLightManager() { if (!TrafficLightManager) { AActor* TrafficLightManagerActor = UGameplayStatics::GetActorOfClass(GetWorld(), ATrafficLightManager::StaticClass()); if(TrafficLightManagerActor == nullptr) { TrafficLightManager = GetWorld()->SpawnActor<ATrafficLightManager>(); } else { TrafficLightManager = Cast<ATrafficLightManager>(TrafficLightManagerActor); } } return TrafficLightManager; } void ACarlaGameModeBase::DebugShowSignals(bool enable) { auto World = GetWorld(); check(World != nullptr); if(!Map) { return; } if(!enable) { UKismetSystemLibrary::FlushDebugStrings(World); UKismetSystemLibrary::FlushPersistentDebugLines(World); return; } //const std::unordered_map<carla::road::SignId, std::unique_ptr<carla::road::Signal>> const auto& Signals = Map->GetSignals(); const auto& Controllers = Map->GetControllers(); for(const auto& Signal : Signals) { const auto& ODSignal = Signal.second; const FTransform Transform = ODSignal->GetTransform(); const FVector Location = Transform.GetLocation(); const FQuat Rotation = Transform.GetRotation(); const FVector Up = Rotation.GetUpVector(); DrawDebugSphere( World, Location, 50.0f, 10, FColor(0, 255, 0), true ); } TArray<const cre::RoadInfoSignal*> References; auto waypoints = Map->GenerateWaypointsOnRoadEntries(); std::unordered_set<cr::RoadId> ExploredRoads; for (auto & waypoint : waypoints) { // Check if we already explored this road if (ExploredRoads.count(waypoint.road_id) > 0) { continue; } ExploredRoads.insert(waypoint.road_id); // Multiple times for same road (performance impact, not in behavior) auto SignalReferences = Map->GetLane(waypoint). GetRoad()->GetInfos<cre::RoadInfoSignal>(); for (auto *SignalReference : SignalReferences) { References.Add(SignalReference); } } for (auto& Reference : References) { auto RoadId = Reference->GetRoadId(); const auto* SignalReference = Reference; const FTransform SignalTransform = SignalReference->GetSignal()->GetTransform(); for(auto &validity : SignalReference->GetValidities()) { for(auto lane : carla::geom::Math::GenerateRange(validity._from_lane, validity._to_lane)) { if(lane == 0) continue; auto signal_waypoint = Map->GetWaypoint( RoadId, lane, SignalReference->GetS()).get(); if(Map->GetLane(signal_waypoint).GetType() != cr::Lane::LaneType::Driving) continue; FTransform ReferenceTransform = Map->ComputeTransform(signal_waypoint); DrawDebugSphere( World, ReferenceTransform.GetLocation(), 50.0f, 10, FColor(0, 0, 255), true ); DrawDebugLine( World, ReferenceTransform.GetLocation(), SignalTransform.GetLocation(), FColor(0, 0, 255), true ); } } } } void ACarlaGameModeBase::CreateAtlasTextures() { if(AtlasTextureWidth > 0 && AtlasTextureHeight > 0) { FRHIResourceCreateInfo CreateInfo; CamerasAtlasTexture = RHICreateTexture2D(AtlasTextureWidth, AtlasTextureHeight, PF_B8G8R8A8, 1, 1, TexCreate_CPUReadback, CreateInfo); AtlasImage.Init(FColor(), AtlasTextureWidth * AtlasTextureHeight); IsAtlasTextureValid = true; } } void ACarlaGameModeBase::CaptureAtlas() { ACarlaGameModeBase* This = this; if(!SceneCaptureSensors.Num()) return; // Be sure that the atlas texture is ready if(!IsAtlasTextureValid) { CreateAtlasTextures(); return; } // Enqueue the commands to copy the captures to the atlas for(ASceneCaptureSensor* Sensor : SceneCaptureSensors) { Sensor->CopyTextureToAtlas(); } // Download Atlas texture ENQUEUE_RENDER_COMMAND(ACarlaGameModeBase_CaptureAtlas) ( [This](FRHICommandListImmediate& RHICmdList) mutable { FTexture2DRHIRef AtlasTexture = This->CamerasAtlasTexture; if (!AtlasTexture) { UE_LOG(LogCarla, Error, TEXT("ACarlaGameModeBase::CaptureAtlas: Missing atlas texture")); return; } FIntRect Rect = FIntRect(0, 0, This->AtlasTextureWidth, This->AtlasTextureHeight); #if !UE_BUILD_SHIPPING if(This->ReadSurfaceMode == 2) Rect = FIntRect(0, 0, This->SurfaceW, This->SurfaceH); #endif #if !UE_BUILD_SHIPPING if (This->ReadSurfaceMode == 0) return; #endif SCOPE_CYCLE_COUNTER(STAT_CarlaSensorReadRT); RHICmdList.ReadSurfaceData( AtlasTexture, Rect, This->AtlasImage, FReadSurfaceDataFlags(RCM_UNorm, CubeFace_MAX)); } ); } void ACarlaGameModeBase::SendAtlas() { #if !UE_BUILD_SHIPPING if(!AtlasCopyToCamera) { return; } #endif for(int32 Index = 0; Index < SceneCaptureSensors.Num(); Index++) { ASceneCaptureSensor* Sensor = SceneCaptureSensors[Index]; Sensor->SendPixels(AtlasImage, AtlasTextureWidth); } }
26.993724
154
0.705572
adelbennaceur
9c61e043bfa520b9152f20cc36caaadc809beb29
1,594
cpp
C++
Number theory/C++/Mahasena.cpp
mahitha2001/DSA-Questions
f8970f3489fff9c79a67c58ac26e5923436ec652
[ "MIT" ]
96
2021-09-28T19:11:37.000Z
2022-03-06T05:13:34.000Z
Number theory/C++/Mahasena.cpp
mahitha2001/DSA-Questions
f8970f3489fff9c79a67c58ac26e5923436ec652
[ "MIT" ]
448
2021-09-29T06:54:58.000Z
2022-03-30T15:35:05.000Z
Number theory/C++/Mahasena.cpp
mahitha2001/DSA-Questions
f8970f3489fff9c79a67c58ac26e5923436ec652
[ "MIT" ]
243
2021-09-29T06:28:00.000Z
2022-03-06T21:23:07.000Z
/* Question Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had never lost a battle under him (as army-chief), and the reason for that was their really powerful army, also called as Mahasena. Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky" if the soldier is holding an even number of weapons, and "unlucky" otherwise. He considered the army as "READY FOR BATTLE" if the count of "lucky" soldiers is strictly greater than the count of "unlucky" soldiers, and "NOT READY" otherwise. Given the number of weapons each soldier is holding, your task is to determine whether the army formed by all these soldiers is "READY FOR BATTLE" or "NOT READY". https://www.codechef.com/problems/AMR15A */ /* Input The first line of input consists of a single integer N denoting the number of soldiers. The second line of input consists of N space separated integers A1, A2, ..., AN, where Ai denotes the number of weapons that the ith soldier is holding. */ /* Output Generate one line output saying "READY FOR BATTLE", if the army satisfies the conditions that Kattapa requires or "NOT READY" otherwise (quotes for clarity). */ #include <iostream> using namespace std; int main() { int t; int lucky=0,unlucky=0; cin>>t; for(int i=0;i<t;i++) { int m; cin>>m; if(m%2==0) lucky++; else unlucky++; } if(lucky>unlucky) cout<<"READY FOR BATTLE"; else cout<<"NOT READY"; return 0; }
37.952381
175
0.685696
mahitha2001
9c62c70f747d78ce976c8b75b284d2e70a231f8f
2,199
hh
C++
src/Distributed/MortonOrderRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Distributed/MortonOrderRedistributeNodes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Distributed/MortonOrderRedistributeNodes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // MortonOrderRedistributeNodes // // Attempt to redistribute nodes such that they are laid out in memory // in a Morton ordering. Note that this involves renumbering the nodes of // each NodeList, not just redistributing them between processors. // // Warren & Salmon (1995), Computer Physics Communications, 87, 266-290. // // Created by JMO, Tue Mar 25 14:19:18 PDT 2008 //----------------------------------------------------------------------------// #ifndef MortonOrderRedistributeNodes_HH #define MortonOrderRedistributeNodes_HH #include "SpaceFillingCurveRedistributeNodes.hh" namespace Spheral { template<typename Dimension> class DataBase; } namespace Spheral { template<typename Dimension> class MortonOrderRedistributeNodes: public SpaceFillingCurveRedistributeNodes<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef KeyTraits::Key Key; // Constructors MortonOrderRedistributeNodes(const double dummy, const double minNodesPerDomainFraction = 0.5, const double maxNodesPerDomainFraction = 1.5, const bool workBalance = true, const bool localReorderOnly = false); // Destructor virtual ~MortonOrderRedistributeNodes(); // Hash the positions. virtual FieldList<Dimension, Key> computeHashedIndices(const DataBase<Dimension>& dataBase) const override; private: //--------------------------- Private Interface ---------------------------// // No copy or assignment operations. MortonOrderRedistributeNodes(const MortonOrderRedistributeNodes& nodes); MortonOrderRedistributeNodes& operator=(const MortonOrderRedistributeNodes& rhs); }; } #else // Forward declare the MortonOrderRedistributeNodes class. namespace Spheral { template<typename Dimension> class MortonOrderRedistributeNodes; } #endif
32.820896
90
0.653024
jmikeowen
9c6814c86593cf07a915dfd43aeeec9f8624c39f
1,674
cc
C++
src/data_pack/table_pack.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
src/data_pack/table_pack.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
src/data_pack/table_pack.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
/* * pfs_pack.cc * * Created on: 2015. 5. 7. * Author: windfree */ #include "data_pack/table_pack.h" #include "data_pack/pack_constants.h" #include "value/map_value.h" #include "value/list_value.h" #include "util/util.h" #include "util/obj_name_util.h" #include "io/data_output.h" #include "io/data_input.h" namespace scouter { table_pack::table_pack() { map_val = new map_value(); time = util::get_current_time(); obj_type ="mariaplugin"; obj_hash = obj_name_util::get_instance()->object_hash(); } table_pack::~table_pack() { delete map_val; map_val = 0; } int16_t table_pack::get_pack_type() { return pack_constants::TABLE; } table_pack* table_pack::new_list_value(std::string key, list_value* value) { this->map_val->insert(key,value); return this; } void table_pack::write(data_output* out) { out->write_decimal(time); out->write_string(obj_type.c_str()); out->write_decimal(obj_hash); out->write_string(key.c_str()); out->write_value(map_val); } pack* table_pack::read(data_input* in) { this->time = in->read_decimal(); this->obj_type=in->read_string(); this->obj_hash = in->read_decimal(); this->key=in->read_string(); this->map_val = (map_value*)in->read_value(); return this; } table_pack* table_pack::set_time(uint64_t val) { time = val; return this; } table_pack* table_pack::set_obj_type(std::string val) { obj_type = val; return this; } table_pack* table_pack::set_obj_hash(int32_t val) { obj_hash = val; return this; } table_pack* table_pack::set_key(std::string val) { key = val; return this; } } /* namespace scouter */
20.168675
77
0.673238
scouter-project
9c697b6e0764a0944673453b6b221ca376f1b109
6,923
cpp
C++
src/singletons/settingsmanager.cpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
1
2018-03-24T18:40:00.000Z
2018-03-24T18:40:00.000Z
src/singletons/settingsmanager.cpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
null
null
null
src/singletons/settingsmanager.cpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
null
null
null
#include "singletons/settingsmanager.hpp" #include "debug/log.hpp" #include "singletons/pathmanager.hpp" #include "singletons/resourcemanager.hpp" #include "singletons/windowmanager.hpp" using namespace chatterino::messages; namespace chatterino { namespace singletons { std::vector<std::weak_ptr<pajlada::Settings::ISettingData>> _settings; void _registerSetting(std::weak_ptr<pajlada::Settings::ISettingData> setting) { _settings.push_back(setting); } SettingManager::SettingManager() : snapshot(nullptr) , _ignoredKeywords(new std::vector<QString>) { this->wordFlagsListener.addSetting(this->showTimestamps); this->wordFlagsListener.addSetting(this->showBadges); this->wordFlagsListener.addSetting(this->enableBttvEmotes); this->wordFlagsListener.addSetting(this->enableEmojis); this->wordFlagsListener.addSetting(this->enableFfzEmotes); this->wordFlagsListener.addSetting(this->enableTwitchEmotes); this->wordFlagsListener.cb = [this](auto) { this->updateWordTypeMask(); // }; this->moderationActions.connect([this](auto, auto) { this->updateModerationActions(); }); this->ignoredKeywords.connect([this](auto, auto) { this->updateIgnoredKeywords(); }); this->timestampFormat.connect( [](auto, auto) { singletons::WindowManager::getInstance().layoutVisibleChatWidgets(); }); } MessageElement::Flags SettingManager::getWordFlags() { return this->wordFlags; } bool SettingManager::isIgnoredEmote(const QString &) { return false; } void SettingManager::init() { QString settingsPath = PathManager::getInstance().settingsFolderPath + "/settings.json"; pajlada::Settings::SettingManager::load(qPrintable(settingsPath)); } void SettingManager::updateWordTypeMask() { uint32_t newMaskUint = MessageElement::Text; if (this->showTimestamps) { newMaskUint |= MessageElement::Timestamp; } newMaskUint |= enableTwitchEmotes ? MessageElement::TwitchEmoteImage : MessageElement::TwitchEmoteText; newMaskUint |= enableFfzEmotes ? MessageElement::FfzEmoteImage : MessageElement::FfzEmoteText; newMaskUint |= enableBttvEmotes ? MessageElement::BttvEmoteImage : MessageElement::BttvEmoteText; newMaskUint |= enableEmojis ? MessageElement::EmojiImage : MessageElement::EmojiText; newMaskUint |= MessageElement::BitsAmount; newMaskUint |= enableGifAnimations ? MessageElement::BitsAnimated : MessageElement::BitsStatic; if (this->showBadges) { newMaskUint |= MessageElement::Badges; } newMaskUint |= MessageElement::Username; newMaskUint |= MessageElement::AlwaysShow; MessageElement::Flags newMask = static_cast<MessageElement::Flags>(newMaskUint); if (newMask != this->wordFlags) { this->wordFlags = newMask; emit wordFlagsChanged(); } } void SettingManager::saveSnapshot() { rapidjson::Document *d = new rapidjson::Document(rapidjson::kObjectType); rapidjson::Document::AllocatorType &a = d->GetAllocator(); for (const auto &weakSetting : _settings) { auto setting = weakSetting.lock(); if (!setting) { continue; } rapidjson::Value key(setting->getPath().c_str(), a); rapidjson::Value val = setting->marshalInto(*d); d->AddMember(key.Move(), val.Move(), a); } this->snapshot.reset(d); debug::Log("hehe: {}", pajlada::Settings::SettingManager::stringify(*d)); } void SettingManager::recallSnapshot() { if (!this->snapshot) { return; } const auto &snapshotObject = this->snapshot->GetObject(); for (const auto &weakSetting : _settings) { auto setting = weakSetting.lock(); if (!setting) { debug::Log("Error stage 1 of loading"); continue; } const char *path = setting->getPath().c_str(); if (!snapshotObject.HasMember(path)) { debug::Log("Error stage 2 of loading"); continue; } setting->unmarshalValue(snapshotObject[path]); } } std::vector<ModerationAction> SettingManager::getModerationActions() const { return this->_moderationActions; } const std::shared_ptr<std::vector<QString>> SettingManager::getIgnoredKeywords() const { return this->_ignoredKeywords; } void SettingManager::updateModerationActions() { auto &resources = singletons::ResourceManager::getInstance(); this->_moderationActions.clear(); static QRegularExpression newLineRegex("(\r\n?|\n)+"); static QRegularExpression replaceRegex("[!/.]"); static QRegularExpression timeoutRegex("^[./]timeout.* (\\d+)"); QStringList list = this->moderationActions.getValue().split(newLineRegex); int multipleTimeouts = 0; for (QString &str : list) { if (timeoutRegex.match(str).hasMatch()) { multipleTimeouts++; if (multipleTimeouts > 1) { break; } } } for (int i = 0; i < list.size(); i++) { QString &str = list[i]; if (str.isEmpty()) { continue; } auto timeoutMatch = timeoutRegex.match(str); if (timeoutMatch.hasMatch()) { if (multipleTimeouts > 1) { QString line1; QString line2; int amount = timeoutMatch.captured(1).toInt(); if (amount < 60) { line1 = QString::number(amount); line2 = "s"; } else if (amount < 60 * 60) { line1 = QString::number(amount / 60); line2 = "m"; } else if (amount < 60 * 60 * 24) { line1 = QString::number(amount / 60 / 60); line2 = "h"; } else { line1 = QString::number(amount / 60 / 60 / 24); line2 = "d"; } this->_moderationActions.emplace_back(line1, line2, str); } else { this->_moderationActions.emplace_back(resources.buttonTimeout, str); } } else if (str.startsWith("/ban ")) { this->_moderationActions.emplace_back(resources.buttonBan, str); } else { QString xD = str; xD.replace(replaceRegex, ""); this->_moderationActions.emplace_back(xD.mid(0, 2), xD.mid(2, 2), str); } } } void SettingManager::updateIgnoredKeywords() { static QRegularExpression newLineRegex("(\r\n?|\n)+"); auto items = new std::vector<QString>(); for (const QString &line : this->ignoredKeywords.getValue().split(newLineRegex)) { QString line2 = line.trimmed(); if (!line2.isEmpty()) { items->push_back(line2); } } this->_ignoredKeywords = std::shared_ptr<std::vector<QString>>(items); } } // namespace singletons } // namespace chatterino
29.459574
99
0.628485
alexandera3
9c69ecbd219423e42f9903a99d2eed0b92b9fb10
1,773
cxx
C++
main/editeng/source/items/svdfield.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/editeng/source/items/svdfield.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/editeng/source/items/svdfield.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_editeng.hxx" #include <editeng/measfld.hxx> SV_IMPL_PERSIST1(SdrMeasureField,SvxFieldData); __EXPORT SdrMeasureField::~SdrMeasureField() { } SvxFieldData* __EXPORT SdrMeasureField::Clone() const { return new SdrMeasureField(*this); } int __EXPORT SdrMeasureField::operator==(const SvxFieldData& rSrc) const { return eMeasureFieldKind==((SdrMeasureField&)rSrc).GetMeasureFieldKind(); } void __EXPORT SdrMeasureField::Load(SvPersistStream& rIn) { sal_uInt16 nFieldKind; rIn>>nFieldKind; eMeasureFieldKind=(SdrMeasureFieldKind)nFieldKind; } void __EXPORT SdrMeasureField::Save(SvPersistStream& rOut) { rOut<<(sal_uInt16)eMeasureFieldKind; } ////////////////////////////////////////////////////////////////////////////// // eof
30.050847
78
0.678511
Grosskopf
9c6a7e723996e5e54041d88ec331b20845a226db
2,255
cpp
C++
ir/node.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
ir/node.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
ir/node.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013-present Barefoot Networks, 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 "ir.h" void IR::Node::traceVisit(const char* visitor) const { LOG3("Visiting " << visitor << " " << id << ":" << node_type_name()); } void IR::Node::traceCreation() const { LOG5("Created node " << id); } int IR::Node::currentId = 0; void IR::Node::toJSON(JSONGenerator &json) const { json << json.indent << "\"Node_ID\" : " << id << ", " << std::endl << json.indent << "\"Node_Type\" : " << node_type_name(); } IR::Node::Node(JSONLoader &json) : id(-1) { json.load("Node_ID", id); if (id < 0) id = currentId++; else if (id >= currentId) currentId = id+1; } cstring IR::dbp(const IR::INode* node) { std::stringstream str; if (node == nullptr) { str << "<nullptr>"; } else { if (node->is<IR::IDeclaration>()) { node->getNode()->Node::dbprint(str); str << " " << node->to<IR::IDeclaration>()->getName(); } else if (node->is<IR::Type_MethodBase>()) { str << node; } else if (node->is<IR::Member>()) { node->getNode()->Node::dbprint(str); str << " ." << node->to<IR::Member>()->member; } else if (node->is<IR::PathExpression>() || node->is<IR::Path>() || node->is<IR::TypeNameExpression>() || node->is<IR::Constant>() || node->is<IR::Type_Name>() || node->is<IR::Type_Base>()) { node->getNode()->Node::dbprint(str); str << " " << node->toString(); } else { node->getNode()->Node::dbprint(str); } } return str.str(); } IRNODE_DEFINE_APPLY_OVERLOAD(Node, , )
33.161765
73
0.566741
pierce-m
9c6c851005d2820e0fd445c7303b3a33171bb969
3,062
cpp
C++
third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2003, 2007, 2010 Apple Inc. All rights reserved. * * 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 "core/html/HTMLMarqueeElement.h" #include "bindings/core/v8/PrivateScriptRunner.h" #include "bindings/core/v8/V8HTMLMarqueeElement.h" #include "core/HTMLNames.h" #include "core/dom/Document.h" #include "core/frame/UseCounter.h" namespace blink { inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document) : HTMLElement(HTMLNames::marqueeTag, document) { if (document.contextDocument()) { v8::Local<v8::Value> classObject = PrivateScriptRunner::installClassIfNeeded(&document, "HTMLMarqueeElement"); RELEASE_ASSERT(!classObject.IsEmpty()); } UseCounter::count(document, UseCounter::HTMLMarqueeElement); } HTMLMarqueeElement* HTMLMarqueeElement::create(Document& document) { HTMLMarqueeElement* marqueeElement = new HTMLMarqueeElement(document); V8HTMLMarqueeElement::PrivateScript::createdCallbackMethod(document.frame(), marqueeElement); return marqueeElement; } void HTMLMarqueeElement::attributeChanged(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason reason) { HTMLElement::attributeChanged(name, oldValue, newValue, reason); V8HTMLMarqueeElement::PrivateScript::attributeChangedCallbackMethod(document().frame(), this, name.toString(), oldValue, newValue); } Node::InsertionNotificationRequest HTMLMarqueeElement::insertedInto(ContainerNode* insertionPoint) { HTMLElement::insertedInto(insertionPoint); if (inShadowIncludingDocument()) { V8HTMLMarqueeElement::PrivateScript::attachedCallbackMethod(document().frame(), this); } return InsertionDone; } void HTMLMarqueeElement::removedFrom(ContainerNode* insertionPoint) { HTMLElement::removedFrom(insertionPoint); if (insertionPoint->inShadowIncludingDocument()) { V8HTMLMarqueeElement::PrivateScript::detachedCallbackMethod(insertionPoint->document().frame(), this); } } bool HTMLMarqueeElement::isHorizontal() const { AtomicString direction = getAttribute(HTMLNames::directionAttr); return direction != "down" && direction != "up"; } } // namespace blink
38.275
164
0.758328
Wzzzx
9c6cc0772cd6f8a3fc597daf84a19aec3613854c
782
cpp
C++
GPTP/src/graphics/draw_hook.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
8
2015-04-03T16:50:59.000Z
2021-01-06T17:12:29.000Z
GPTP/src/graphics/draw_hook.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-03T18:10:56.000Z
2016-02-18T05:04:21.000Z
GPTP/src/graphics/draw_hook.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-04T04:37:33.000Z
2018-04-09T09:03:50.000Z
#include "draw_hook.h" #include "../SCBW/api.h" #include "../hook_tools.h" #include "graphics_misc.h" namespace { //-------- Draw hook taken from BWAPI --------// bool wantRefresh = false; void __stdcall DrawHook(graphics::Bitmap *surface, Bounds *bounds) { if (wantRefresh) { wantRefresh = false; scbw::refreshScreen(); } oldDrawGameProc(surface, bounds); //if ( BW::BWDATA::GameScreenBuffer->isValid() ) //{ // unsigned int numShapes = BWAPI::BroodwarImpl.drawShapes(); // // if ( numShapes ) // wantRefresh = true; //} if (graphics::drawAllShapes() > 0) wantRefresh = true; } } //unnamed namespace namespace hooks { void injectDrawHook() { memoryPatch(0x004BD68D, &DrawHook); } } //hooks
20.578947
70
0.609974
idmontie
9c6d67781ca99a80ade56220086f7c21eccd5458
1,173
cpp
C++
Modules/PlanarFigure/src/IO/mitkPlanarFigureIOFactory.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/PlanarFigure/src/IO/mitkPlanarFigureIOFactory.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/PlanarFigure/src/IO/mitkPlanarFigureIOFactory.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPlanarFigureIOFactory.h" #include "mitkIOAdapter.h" #include "mitkPlanarFigureReader.h" #include "itkVersion.h" namespace mitk { PlanarFigureIOFactory::PlanarFigureIOFactory() { this->RegisterOverride("mitkIOAdapter", "mitkPlanarFigureReader", "mitk PlanarFigure IO", true, itk::CreateObjectFunction<IOAdapter<PlanarFigureReader>>::New()); } PlanarFigureIOFactory::~PlanarFigureIOFactory() {} const char *PlanarFigureIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } const char *PlanarFigureIOFactory::GetDescription() const { return "PlanarFigure IO Factory, allows the loading of .pf files"; } } // end namespace mitk
30.868421
95
0.595908
SVRTK
9c6ed76ef27548e2e5c0749e65eabc697226bcae
2,798
cpp
C++
src/Formats/ProtobufSchemas.cpp
lizhichao/ClickHouse
3f5dc37095ccca18de490fab162d6e3cb99756aa
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Formats/ProtobufSchemas.cpp
lizhichao/ClickHouse
3f5dc37095ccca18de490fab162d6e3cb99756aa
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Formats/ProtobufSchemas.cpp
lizhichao/ClickHouse
3f5dc37095ccca18de490fab162d6e3cb99756aa
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#if !defined(ARCADIA_BUILD) # include "config_formats.h" #endif #if USE_PROTOBUF # include <Formats/FormatSchemaInfo.h> # include <Formats/ProtobufSchemas.h> # include <google/protobuf/compiler/importer.h> # include <Common/Exception.h> namespace DB { namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int CANNOT_PARSE_PROTOBUF_SCHEMA; } ProtobufSchemas & ProtobufSchemas::instance() { static ProtobufSchemas instance; return instance; } class ProtobufSchemas::ImporterWithSourceTree : public google::protobuf::compiler::MultiFileErrorCollector { public: explicit ImporterWithSourceTree(const String & schema_directory) : importer(&disk_source_tree, this) { disk_source_tree.MapPath("", schema_directory); } ~ImporterWithSourceTree() override = default; const google::protobuf::Descriptor * import(const String & schema_path, const String & message_name) { // Search the message type among already imported ones. const auto * descriptor = importer.pool()->FindMessageTypeByName(message_name); if (descriptor) return descriptor; const auto * file_descriptor = importer.Import(schema_path); // If there are parsing errors AddError() throws an exception and in this case the following line // isn't executed. assert(file_descriptor); descriptor = file_descriptor->FindMessageTypeByName(message_name); if (!descriptor) throw Exception( "Not found a message named '" + message_name + "' in the schema file '" + schema_path + "'", ErrorCodes::BAD_ARGUMENTS); return descriptor; } private: // Overrides google::protobuf::compiler::MultiFileErrorCollector: void AddError(const String & filename, int line, int column, const String & message) override { throw Exception( "Cannot parse '" + filename + "' file, found an error at line " + std::to_string(line) + ", column " + std::to_string(column) + ", " + message, ErrorCodes::CANNOT_PARSE_PROTOBUF_SCHEMA); } google::protobuf::compiler::DiskSourceTree disk_source_tree; google::protobuf::compiler::Importer importer; }; ProtobufSchemas::ProtobufSchemas() = default; ProtobufSchemas::~ProtobufSchemas() = default; const google::protobuf::Descriptor * ProtobufSchemas::getMessageTypeForFormatSchema(const FormatSchemaInfo & info) { auto it = importers.find(info.schemaDirectory()); if (it == importers.end()) it = importers.emplace(info.schemaDirectory(), std::make_unique<ImporterWithSourceTree>(info.schemaDirectory())).first; auto * importer = it->second.get(); return importer->import(info.schemaPath(), info.messageName()); } } #endif
32.534884
137
0.695497
lizhichao
9c6ef314c1bc19517b00f75bb594d36395203b8e
18,170
cpp
C++
src/hook.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
2
2020-10-23T02:42:18.000Z
2021-12-08T14:01:46.000Z
src/hook.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
null
null
null
src/hook.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
null
null
null
/* hook */ /* Version 1.1 (with Win32 GUI) by Juce. */ #include <windows.h> #include <windef.h> #include <string.h> #include <stdio.h> #include "mydll.h" #include "shared.h" #include "win32gui.h" #include "config.h" #include "hook.h" FILE* log = NULL; // Program Configuration static TAXI_CONFIG config = { DEFAULT_DEBUG, DEFAULT_CAPTURE_DIR, DEFAULT_TARGET_FRAME_RATE, DEFAULT_VKEY_INDICATOR, DEFAULT_VKEY_HOOK_MODE, DEFAULT_VKEY_SMALL_SCREENSHOT, DEFAULT_VKEY_SCREENSHOT, DEFAULT_VKEY_VIDEO_CAPTURE, DEFAULT_USE_DIRECT_INPUT, DEFAULT_STARTUP_MODE_SYSTEM_WIDE, DEFAULT_FULL_SIZE_VIDEO, DEFAULT_CUSTOM_LIST }; BOOL dropDownSelecting = false; TAXI_CUSTOM_CONFIG* g_curCfg = NULL; // function prototypes void ApplySettings(void); void ForceReconf(void); void RestoreSettings(void); void InitializeCustomConfigs(void); BOOL GetDevice8Methods(HWND hWnd, DWORD* present, DWORD* reset); BOOL GetDevice9Methods(HWND hWnd, DWORD* present, DWORD* reset); /** * Increase the reconf-counter thus telling all the mapped DLLs that * they need to reconfigure themselves. */ void ForceReconf(void) { ZeroMemory(config.captureDir, BUFLEN); SendMessage(g_captureDirectoryControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)config.captureDir); // make sure it ends with backslash. if (config.captureDir[lstrlen(config.captureDir)-1] != '\\') { lstrcat(config.captureDir, "\\"); SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir); } int frate = 0; char buf[BUFLEN]; ZeroMemory(buf, BUFLEN); SendMessage(g_frameRateControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf); if (sscanf(buf, "%d", &frate) == 1 && frate > 0) { config.targetFrameRate = frate; } else { config.targetFrameRate = GetTargetFrameRate(); sprintf(buf, "%d", config.targetFrameRate); SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf); } // Apply new settings ApplySettings(); // Save if (WriteConfig(&config)) { SetReconfCounter(GetReconfCounter() + 1); } } /** * Apply settings from config */ void ApplySettings(void) { char buf[BUFLEN]; // apply general settings SetDebug(config.debug); if (lstrlen(config.captureDir)==0) { // If capture directory is still unknown at this point // set it to the current directory then. ZeroMemory(config.captureDir, BUFLEN); GetModuleFileName(NULL, config.captureDir, BUFLEN); // strip off file name char* p = config.captureDir + lstrlen(config.captureDir); while (p > config.captureDir && *p != '\\') p--; p[1] = '\0'; } SetCaptureDir(config.captureDir); SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir); SetTargetFrameRate(config.targetFrameRate); ZeroMemory(buf, BUFLEN); sprintf(buf,"%d",config.targetFrameRate); SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf); // apply keys SetKey(VKEY_INDICATOR_TOGGLE, config.vKeyIndicator); VKEY_TEXT(VKEY_INDICATOR_TOGGLE, buf, BUFLEN); SendMessage(g_keyIndicatorControl, WM_SETTEXT, 0, (LPARAM)buf); SetKey(VKEY_HOOK_MODE_TOGGLE, config.vKeyHookMode); VKEY_TEXT(VKEY_HOOK_MODE_TOGGLE, buf, BUFLEN); SendMessage(g_keyModeToggleControl, WM_SETTEXT, 0, (LPARAM)buf); SetKey(VKEY_SMALL_SCREENSHOT, config.vKeySmallScreenShot); VKEY_TEXT(VKEY_SMALL_SCREENSHOT, buf, BUFLEN); SendMessage(g_keySmallScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf); SetKey(VKEY_SCREENSHOT, config.vKeyScreenShot); VKEY_TEXT(VKEY_SCREENSHOT, buf, BUFLEN); SendMessage(g_keyScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf); SetKey(VKEY_VIDEO_CAPTURE, config.vKeyVideoCapture); VKEY_TEXT(VKEY_VIDEO_CAPTURE, buf, BUFLEN); SendMessage(g_keyVideoToggleControl, WM_SETTEXT, 0, (LPARAM)buf); // apply useDirectInput SetUseDirectInput(config.useDirectInput); // apply startupModeSystemWide SetStartupModeSystemWide(config.startupModeSystemWide); // apply fullSizeVideo SetFullSizeVideo(config.fullSizeVideo); // apply custom configs SendMessage(g_customSettingsListControl, CB_RESETCONTENT, 0, 0); SendMessage(g_customPatternControl, WM_SETTEXT, 0, (LPARAM)""); SendMessage(g_customFrameRateControl, WM_SETTEXT, 0, (LPARAM)""); SendMessage(g_customFrameWeightControl, WM_SETTEXT, 0, (LPARAM)""); InitializeCustomConfigs(); } /** * Restores last saved settings. */ void RestoreSettings(void) { g_curCfg = NULL; FreeCustomConfigs(&config); // read optional configuration file ReadConfig(&config); // check for "silent" mode if (config.debug == 0) { if (log != NULL) fclose(log); DeleteFile(MAINLOGFILE); log = NULL; } ApplySettings(); } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { int home, away, timecode; char buf[BUFLEN]; switch(uMsg) { case WM_DESTROY: // Set flag, so that mydll knows to unhook device methods SetUnhookFlag(true); SetExiting(true); // Free memory taken by custom configs FreeCustomConfigs(&config); // close LOG file if (log != NULL) fclose(log); // Uninstall the hook UninstallTheHook(); // Exit the application when the window closes PostQuitMessage(1); return true; case WM_APP_REHOOK: // Re-install system-wide hook LOG(log, (log, "Received message to re-hook GetMsgProc\n")); if (InstallTheHook()) { LOG(log, (log, "GetMsgProc successfully re-hooked.\n")); } break; case WM_COMMAND: if (HIWORD(wParam) == BN_CLICKED) { if ((HWND)lParam == g_saveButtonControl) { // update current custom config if (g_curCfg != NULL) { SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern); int value = 0; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value; float dvalue = 0.0f; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue; } ForceReconf(); // modify status text SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"SAVED"); } else if ((HWND)lParam == g_restoreButtonControl) { RestoreSettings(); // modify status text SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"RESTORED"); } else if ((HWND)lParam == g_customAddButtonControl) { // update current custom config if (g_curCfg != NULL) { SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern); int value = 0; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value; float dvalue = 0.0f; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue; } g_curCfg = NULL; // clear out controls SendMessage(g_customSettingsListControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); // set focus on appId comboBox SendMessage(g_customSettingsListControl,WM_SETFOCUS, 0, 0); } else if ((HWND)lParam == g_customDropButtonControl) { // remove current custom config if (g_curCfg != NULL) { int idx = (int)SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId); //ZeroMemory(buf, BUFLEN); //sprintf(buf,"idx = %d", idx); //SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf); if (idx != -1) { SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0); DeleteCustomConfig(&config, g_curCfg->appId); } SendMessage(g_customSettingsListControl, CB_SETCURSEL, 0, 0); ZeroMemory(buf, BUFLEN); SendMessage(g_customSettingsListControl, CB_GETLBTEXT, 0, (LPARAM)buf); g_curCfg = LookupExistingCustomConfig(&config, buf); if (g_curCfg != NULL) { // update custom controls SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)g_curCfg->pattern); ZeroMemory(buf, BUFLEN); sprintf(buf, "%d", g_curCfg->frameRate); SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); ZeroMemory(buf, BUFLEN); sprintf(buf, "%1.4f", g_curCfg->frameWeight); SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); } else { // clear out controls SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)""); } } } } else if (HIWORD(wParam) == CBN_KILLFOCUS) { ZeroMemory(buf, BUFLEN); SendMessage(g_customSettingsListControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf); if (lstrlen(buf)>0) { if (lstrcmp(buf, g_curCfg->appId)!=0) { if (g_curCfg != NULL) { // find list item with old appId int idx = SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId); // delete this item, if found if (idx != -1) SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0); // change appId strncpy(g_curCfg->appId, buf, BUFLEN-1); // add a new list item SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId); } else { // we have a new custom config g_curCfg = LookupCustomConfig(&config, buf); // add a new list item SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId); } } } else { // cannot use empty string. Restore the old one, if known. if (g_curCfg != NULL) { // restore previous text SendMessage(g_customSettingsListControl, WM_SETTEXT, 0, (LPARAM)g_curCfg->appId); } } } else if (HIWORD(wParam) == CBN_SELCHANGE) { // update previously selected custom config if (g_curCfg != NULL) { SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern); int value = 0; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value; float dvalue = 0.0f; ZeroMemory(buf, BUFLEN); SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf); if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue; } // user selected different custom setting in drop-down int idx = (int)SendMessage(g_customSettingsListControl, CB_GETCURSEL, 0, 0); ZeroMemory(buf, BUFLEN); SendMessage(g_customSettingsListControl, CB_GETLBTEXT, idx, (LPARAM)buf); TAXI_CUSTOM_CONFIG* cfg = LookupExistingCustomConfig(&config, buf); if (cfg == NULL) break; // update custom controls dropDownSelecting = true; SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern); ZeroMemory(buf, BUFLEN); sprintf(buf, "%d", cfg->frameRate); SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); ZeroMemory(buf, BUFLEN); sprintf(buf, "%1.4f", cfg->frameWeight); SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); dropDownSelecting = false; // remember new current config g_curCfg = cfg; } else if (HIWORD(wParam) == EN_CHANGE) { HWND control = (HWND)lParam; if (!dropDownSelecting) { // modify status text SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE"); } } else if (HIWORD(wParam) == CBN_EDITCHANGE) { HWND control = (HWND)lParam; // modify status text SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE"); } break; case WM_APP_KEYDEF: HWND target = (HWND)lParam; ZeroMemory(buf, BUFLEN); GetKeyNameText(MapVirtualKey(wParam, 0) << 16, buf, BUFLEN); SendMessage(target, WM_SETTEXT, 0, (LPARAM)buf); SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE"); // update config if (target == g_keyIndicatorControl) config.vKeyIndicator = (WORD)wParam; else if (target == g_keyModeToggleControl) config.vKeyHookMode = (WORD)wParam; else if (target == g_keySmallScreenshotControl) config.vKeySmallScreenShot = (WORD)wParam; else if (target == g_keyScreenshotControl) config.vKeyScreenShot = (WORD)wParam; else if (target == g_keyVideoToggleControl) config.vKeyVideoCapture = (WORD)wParam; break; } return DefWindowProc(hwnd,uMsg,wParam,lParam); } bool InitApp(HINSTANCE hInstance, LPSTR lpCmdLine) { WNDCLASSEX wcx; // cbSize - the size of the structure. wcx.cbSize = sizeof(WNDCLASSEX); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.lpfnWndProc = (WNDPROC)WindowProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.hInstance = hInstance; wcx.hIcon = LoadIcon(NULL,IDI_APPLICATION); wcx.hCursor = LoadCursor(NULL,IDC_ARROW); wcx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wcx.lpszMenuName = NULL; wcx.lpszClassName = "TAXICLS"; wcx.hIconSm = NULL; // Register the class with Windows if(!RegisterClassEx(&wcx)) return false; // open log log = fopen(MAINLOGFILE, "wt"); // read optional configuration file ReadConfig(&config); // check for "silent" mode if (config.debug == 0) { if (log != NULL) fclose(log); DeleteFile(MAINLOGFILE); log = NULL; } // clear exiting flag SetExiting(false); return true; } HWND BuildWindow(int nCmdShow) { DWORD style, xstyle; HWND retval; style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; xstyle = WS_EX_LEFT; retval = CreateWindowEx(xstyle, "TAXICLS", // class name TAXI_WINDOW_TITLE, // title for our window (appears in the titlebar) style, CW_USEDEFAULT, // initial x coordinate CW_USEDEFAULT, // initial y coordinate WIN_WIDTH, WIN_HEIGHT, // width and height of the window NULL, // no parent window. NULL, // no menu NULL, // no creator NULL); // no extra data if (retval == NULL) return NULL; // BAD. ShowWindow(retval,nCmdShow); // Show the window return retval; // return its handle for future use. } void InitializeCustomConfigs(void) { TAXI_CUSTOM_CONFIG* cfg = config.customList; while (cfg != NULL) { SendMessage(g_customSettingsListControl,CB_INSERTSTRING,(WPARAM)0, (LPARAM)cfg->appId); if (cfg->next == NULL) { // Pre-select iteam SendMessage(g_customSettingsListControl,CB_SETCURSEL,(WPARAM)0,(LPARAM)0); SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern); char buf[BUFLEN]; ZeroMemory(buf, BUFLEN); sprintf(buf, "%d", cfg->frameRate); SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); ZeroMemory(buf, BUFLEN); sprintf(buf, "%1.4f", cfg->frameWeight); SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf); // remember current config g_curCfg = cfg; } cfg = cfg->next; } // clear status text SendMessage(g_statusTextControl, WM_SETTEXT, (WPARAM)0, (LPARAM)""); } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; int retval; if(InitApp(hInstance, lpCmdLine) == false) return 0; HWND hWnd = BuildWindow(nCmdShow); if(hWnd == NULL) return 0; // build GUI if (!BuildControls(hWnd)) return 0; // Initialize all controls ApplySettings(); // show credits char buf[BUFLEN]; ZeroMemory(buf, BUFLEN); strncpy(buf, CREDITS, BUFLEN-1); SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf); // Get method pointers of IDirect3DDevice8 vtable DWORD present8_addr = 0, reset8_addr = 0; if (GetDevice8Methods(hWnd, &present8_addr, &reset8_addr)) { SetPresent8(present8_addr); SetReset8(reset8_addr); } // Get method pointers of IDirect3DDevice9 vtable DWORD present9_addr = 0, reset9_addr = 0; if (GetDevice9Methods(hWnd, &present9_addr, &reset9_addr)) { SetPresent9(present9_addr); SetReset9(reset9_addr); } // Clear the flag, so that mydll hooks on device methods SetUnhookFlag(false); // Set HWND for later use SetServerWnd(hWnd); // Install the hook InstallTheHook(); while((retval = GetMessage(&msg,NULL,0,0)) != 0) { // capture key-def events if ((msg.hwnd == g_keyIndicatorControl || msg.hwnd == g_keyModeToggleControl || msg.hwnd == g_keySmallScreenshotControl || msg.hwnd == g_keyScreenshotControl || msg.hwnd == g_keyVideoToggleControl) && (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN)) { PostMessage(hWnd, WM_APP_KEYDEF, msg.wParam, (LPARAM)msg.hwnd); continue; } if(retval == -1) return 0; // an error occured while getting a message if (!IsDialogMessage(hWnd, &msg)) // need to call this to make WS_TABSTOP work { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; }
31.273666
111
0.671987
juce
9c73217befc2182c35b35cbea31af5574495ab55
17,520
cpp
C++
libraries/entities/src/EntityDynamicInterface.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
14
2020-02-23T12:51:54.000Z
2021-11-14T17:09:34.000Z
libraries/entities/src/EntityDynamicInterface.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
2
2018-11-01T02:16:43.000Z
2018-11-16T00:45:44.000Z
libraries/entities/src/EntityDynamicInterface.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
5
2020-04-02T09:42:00.000Z
2021-03-15T00:54:07.000Z
// // EntityDynamicInterface.cpp // libraries/entities/src // // Created by Seth Alves on 2015-6-4 // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // /* +-------------------------+ +--------------------------------+ | | | | | EntityDynamicsInterface | | EntityDynamicsFactoryInterface | | (entities) | | (entities) | +-------------------------+ +--------------------------------+ | | | | +----+ +--+ | | | | | | +---------------------+ +----------------+ +--------------------------+ +---------------------------+ | | | | | | | | | AssignmentDynamics | | ObjectDynamics | | InterfaceDynamicsFactory | | AssignmentDynamicsFactory | |(assignment client) | | (physics) | | (interface) | | (assignment client) | +---------------------+ +----------------+ +--------------------------+ +---------------------------+ | | | | +---------------------+ | | | | | | | btActionInterface | | | | (bullet) | | | +---------------------+ | | | | | +--------------+ +------------------+ +-------------------+ | | | | | | | ObjectAction | | ObjectConstraint | | btTypedConstraint | | (physics) | | (physics) --|--->| (bullet) | +--------------+ +------------------+ +-------------------+ | | | | +--------------------+ +-----------------------+ | | | | | ObjectActionTractor| | ObjectConstraintHinge | | (physics) | | (physics) | +--------------------+ +-----------------------+ A dynamic is a callback which is registered with bullet. A dynamic is called-back every physics simulation step and can do whatever it wants with the various datastructures it has available. A dynamic, for example, can pull an EntityItem toward a point as if that EntityItem were connected to that point by a spring. In this system, a dynamic is a property of an EntityItem (rather, an EntityItem has a property which encodes a list of dynamics). Each dynamic has a type and some arguments. Dynamics can be created by a script or when receiving information via an EntityTree data-stream (either over the network or from an svo file). In the interface, if an EntityItem has dynamics, this EntityItem will have pointers to ObjectDynamic subclass (like ObjectDynamicTractor) instantiations. Code in the entities library affects a dynamic-object via the EntityDynamicInterface (which knows nothing about bullet). When the ObjectDynamic subclass instance is created, it is registered as a dynamic with bullet. Bullet will call into code in this instance with the btDynamicInterface every physics-simulation step. Because the dynamic can exist next to the interface's EntityTree or the entity-server's EntityTree, parallel versions of the factories and dynamics are needed. In an entity-server, any type of dynamic is instantiated as an AssignmentDynamic. This dynamic isn't called by bullet (which isn't part of an assignment-client). It does nothing but remember its type and its arguments. This may change as we try to make the entity-server's simple physics simulation better, but right now the AssignmentDynamic class is a place-holder. The dynamic-objects are instantiated by singleton (dependecy) subclasses of EntityDynamicFactoryInterface. In the interface, the subclass is an InterfaceDynamicFactory and it will produce things like ObjectDynamicTractor. In an entity-server the subclass is an AssignmentDynamicFactory and it always produces AssignmentDynamics. Depending on the dynamic's type, it will have various arguments. When a script changes an argument of an dynamic, the argument-holding member-variables of ObjectDynamicTractor (in this example) are updated and also serialized into _dynamicData in the EntityItem. Each subclass of ObjectDynamic knows how to serialize and deserialize its own arguments. _dynamicData is what gets sent over the wire or saved in an svo file. When a packet-reader receives data for _dynamicData, it will save it in the EntityItem; this causes the deserializer in the ObjectDynamic subclass to be called with the new data, thereby updating its argument variables. These argument variables are used by the code which is run when bullet does a callback. */ #include "EntityDynamicInterface.h" #include "EntityItem.h" /**jsdoc * <p>An entity action may be one of the following types:</p> * <table> * <thead> * <tr><th>Value</th><th>Type</th><th>Description</th><th>Arguments</th></tr> * </thead> * <tbody> * <tr><td><code>"far-grab"</code></td><td>Avatar action</td> * <td>Moves and rotates an entity to a target position and orientation, optionally relative to another entity. Collisions * between the entity and the user's avatar are disabled during the far-grab.</td> * <td>{@link Entities.ActionArguments-FarGrab}</td></tr> * <tr><td><code>"hold"</code></td><td>Avatar action</td> * <td>Positions and rotates an entity relative to an avatar's hand. Collisions between the entity and the user's avatar * are disabled during the hold.</td> * <td>{@link Entities.ActionArguments-Hold}</td></tr> * <tr><td><code>"offset"</code></td><td>Object action</td> * <td>Moves an entity so that it is a defined distance away from a target point.</td> * <td>{@link Entities.ActionArguments-Offset}</td></tr> * <tr><td><code>"tractor"</code></td><td>Object action</td> * <td>Moves and rotates an entity to a target position and orientation, optionally relative to another entity.</td> * <td>{@link Entities.ActionArguments-Tractor}</td></tr> * <tr><td><code>"travel-oriented"</code></td><td>Object action</td> * <td>Orients an entity to align with its direction of travel.</td> * <td>{@link Entities.ActionArguments-TravelOriented}</td></tr> * <tr><td><code>"hinge"</code></td><td>Object constraint</td> * <td>Lets an entity pivot about an axis or connects two entities with a hinge joint.</td> * <td>{@link Entities.ActionArguments-Hinge}</td></tr> * <tr><td><code>"slider"</code></td><td>Object constraint</td> * <td>Lets an entity slide and rotate along an axis, or connects two entities that slide and rotate along a shared * axis.</td> * <td>{@link Entities.ActionArguments-Slider|ActionArguments-Slider}</td></tr> * <tr><td><code>"cone-twist"</code></td><td>Object constraint</td> * <td>Connects two entities with a joint that can move through a cone and can twist.</td> * <td>{@link Entities.ActionArguments-ConeTwist}</td></tr> * <tr><td><code>"ball-socket"</code></td><td>Object constraint</td> * <td>Connects two entities with a ball and socket joint.</td> * <td>{@link Entities.ActionArguments-BallSocket}</td></tr> * <tr><td><code>"spring"</code></td><td>&nbsp;</td><td>Synonym for <code>"tractor"</code>. * <p class="important">Deprecated.</p></td><td>&nbsp;</td></tr> * </tbody> * </table> * @typedef {string} Entities.ActionType */ // Note: The "none" action type is not listed because it's an internal "uninitialized" value and not useful for scripts. EntityDynamicType EntityDynamicInterface::dynamicTypeFromString(QString dynamicTypeString) { QString normalizedDynamicTypeString = dynamicTypeString.toLower().remove('-').remove('_'); if (normalizedDynamicTypeString == "none") { return DYNAMIC_TYPE_NONE; } if (normalizedDynamicTypeString == "offset") { return DYNAMIC_TYPE_OFFSET; } if (normalizedDynamicTypeString == "spring") { return DYNAMIC_TYPE_TRACTOR; } if (normalizedDynamicTypeString == "tractor") { return DYNAMIC_TYPE_TRACTOR; } if (normalizedDynamicTypeString == "hold") { return DYNAMIC_TYPE_HOLD; } if (normalizedDynamicTypeString == "traveloriented") { return DYNAMIC_TYPE_TRAVEL_ORIENTED; } if (normalizedDynamicTypeString == "hinge") { return DYNAMIC_TYPE_HINGE; } if (normalizedDynamicTypeString == "fargrab") { return DYNAMIC_TYPE_FAR_GRAB; } if (normalizedDynamicTypeString == "slider") { return DYNAMIC_TYPE_SLIDER; } if (normalizedDynamicTypeString == "ballsocket") { return DYNAMIC_TYPE_BALL_SOCKET; } if (normalizedDynamicTypeString == "conetwist") { return DYNAMIC_TYPE_CONE_TWIST; } qCDebug(entities) << "Warning -- EntityDynamicInterface::dynamicTypeFromString got unknown dynamic-type name" << dynamicTypeString; return DYNAMIC_TYPE_NONE; } QString EntityDynamicInterface::dynamicTypeToString(EntityDynamicType dynamicType) { switch(dynamicType) { case DYNAMIC_TYPE_NONE: return "none"; case DYNAMIC_TYPE_OFFSET: return "offset"; case DYNAMIC_TYPE_SPRING: case DYNAMIC_TYPE_TRACTOR: return "tractor"; case DYNAMIC_TYPE_HOLD: return "hold"; case DYNAMIC_TYPE_TRAVEL_ORIENTED: return "travel-oriented"; case DYNAMIC_TYPE_HINGE: return "hinge"; case DYNAMIC_TYPE_FAR_GRAB: return "far-grab"; case DYNAMIC_TYPE_SLIDER: return "slider"; case DYNAMIC_TYPE_BALL_SOCKET: return "ball-socket"; case DYNAMIC_TYPE_CONE_TWIST: return "cone-twist"; } assert(false); return "none"; } glm::vec3 EntityDynamicInterface::extractVec3Argument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return glm::vec3(0.0f); } QVariant resultV = arguments[argumentName]; if (resultV.type() != (QVariant::Type) QMetaType::QVariantMap) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map"; ok = false; return glm::vec3(0.0f); } QVariantMap resultVM = resultV.toMap(); if (!resultVM.contains("x") || !resultVM.contains("y") || !resultVM.contains("z")) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, z"; ok = false; return glm::vec3(0.0f); } QVariant xV = resultVM["x"]; QVariant yV = resultVM["y"]; QVariant zV = resultVM["z"]; bool xOk = true; bool yOk = true; bool zOk = true; float x = xV.toFloat(&xOk); float y = yV.toFloat(&yOk); float z = zV.toFloat(&zOk); if (!xOk || !yOk || !zOk) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, and z of type float."; ok = false; return glm::vec3(0.0f); } if (x != x || y != y || z != z) { // at least one of the values is NaN ok = false; return glm::vec3(0.0f); } return glm::vec3(x, y, z); } glm::quat EntityDynamicInterface::extractQuatArgument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return glm::quat(); } QVariant resultV = arguments[argumentName]; if (resultV.type() != (QVariant::Type) QMetaType::QVariantMap) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map, not" << resultV.typeName(); ok = false; return glm::quat(); } QVariantMap resultVM = resultV.toMap(); if (!resultVM.contains("x") || !resultVM.contains("y") || !resultVM.contains("z") || !resultVM.contains("w")) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, z, and w"; ok = false; return glm::quat(); } QVariant xV = resultVM["x"]; QVariant yV = resultVM["y"]; QVariant zV = resultVM["z"]; QVariant wV = resultVM["w"]; bool xOk = true; bool yOk = true; bool zOk = true; bool wOk = true; float x = xV.toFloat(&xOk); float y = yV.toFloat(&yOk); float z = zV.toFloat(&zOk); float w = wV.toFloat(&wOk); if (!xOk || !yOk || !zOk || !wOk) { qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, z, and w of type float."; ok = false; return glm::quat(); } if (x != x || y != y || z != z || w != w) { // at least one of the components is NaN! ok = false; return glm::quat(); } return glm::normalize(glm::quat(w, x, y, z)); } float EntityDynamicInterface::extractFloatArgument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return 0.0f; } QVariant variant = arguments[argumentName]; bool variantOk = true; float value = variant.toFloat(&variantOk); if (!variantOk || std::isnan(value)) { ok = false; return 0.0f; } return value; } int EntityDynamicInterface::extractIntegerArgument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return 0.0f; } QVariant variant = arguments[argumentName]; bool variantOk = true; int value = variant.toInt(&variantOk); if (!variantOk) { ok = false; return 0; } return value; } QString EntityDynamicInterface::extractStringArgument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return ""; } return arguments[argumentName].toString(); } bool EntityDynamicInterface::extractBooleanArgument(QString objectName, QVariantMap arguments, QString argumentName, bool& ok, bool required) { if (!arguments.contains(argumentName)) { if (required) { qCDebug(entities) << objectName << "requires argument:" << argumentName; } ok = false; return false; } return arguments[argumentName].toBool(); } QDataStream& operator<<(QDataStream& stream, const EntityDynamicType& entityDynamicType) { return stream << (quint16)entityDynamicType; } QDataStream& operator>>(QDataStream& stream, EntityDynamicType& entityDynamicType) { quint16 dynamicTypeAsInt; stream >> dynamicTypeAsInt; entityDynamicType = (EntityDynamicType)dynamicTypeAsInt; return stream; } QString serializedDynamicsToDebugString(QByteArray data) { if (data.size() == 0) { return QString(); } QVector<QByteArray> serializedDynamics; QDataStream serializedDynamicsStream(data); serializedDynamicsStream >> serializedDynamics; QString result; foreach(QByteArray serializedDynamic, serializedDynamics) { QDataStream serializedDynamicStream(serializedDynamic); EntityDynamicType dynamicType; QUuid dynamicID; serializedDynamicStream >> dynamicType; serializedDynamicStream >> dynamicID; result += EntityDynamicInterface::dynamicTypeToString(dynamicType) + "-" + dynamicID.toString() + " "; } return result; }
42.731707
129
0.575742
Darlingnotin
9c7349434259d3d42f01b7ed9e66f64d09e76ef2
7,923
cpp
C++
src/rx/core/memory/buddy_allocator.cpp
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
2
2020-06-13T11:39:46.000Z
2021-03-10T01:03:03.000Z
src/rx/core/memory/buddy_allocator.cpp
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
null
null
null
src/rx/core/memory/buddy_allocator.cpp
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
1
2021-01-06T03:47:08.000Z
2021-01-06T03:47:08.000Z
#include <string.h> // memcpy #include "rx/core/memory/buddy_allocator.h" #include "rx/core/concurrency/scope_lock.h" #include "rx/core/hints/unlikely.h" #include "rx/core/hints/likely.h" #include "rx/core/assert.h" namespace Rx::Memory { // Each allocation in the heap is prefixed with this header. struct alignas(Allocator::ALIGNMENT) Block { Size size; bool free; }; // Returns the next block in the intrusive, flat linked-list structure. static inline Block* next(Block* _block) { return reinterpret_cast<Block*>(reinterpret_cast<Byte*>(_block) + _block->size); } // Returns size that is needed for |_size|. static inline Size needed(Size _size) { Size result = Allocator::ALIGNMENT; // Smallest allocation // Storage for the block. _size += sizeof(Block); // Continually double result until |_size| fits. while (_size > result) { result <<= 1; } return result; } // Continually divides the block |block_| until it's the optimal size for // an allocation of size |_size|. static Block* divide(Block* block_, Size _size) { while (block_->size > _size) { // Split block into two halves, half-size each. const auto size = block_->size >> 1; block_->size = size; block_ = next(block_); block_->size = size; block_->free = true; } return block_->size >= _size ? block_ : nullptr; } // Searches for a free block that matches the given size |_size| in the list // defined by |_head| and |_tail|. When a block cannot be found which satisifies // the size |_size| but there is a larger free block, this divides the free // block into two halves of the same size until the block optimally fits the // size |_size| in it. If there is no larger free block available, this returns // nullptr. // // This function also merges adjacent free blocks as it searches to make larger, // free blocks available during the search. static Block* find_available(Block* _head, Block* _tail, Size _size) { Block* region = _head; Block* buddy = next(region); Block* closest = nullptr; // When at the end of the heap and the region is free. if (buddy == _tail && region->free) { // Split it into a block to satisfy the request leaving what is left over // for any future allocations. This is the one edge case the general // algorithm cannot cover. return divide(region, _size); } // Find the closest minimum sized match within the heap. Size closest_size = 0; while (region < _tail && buddy < _tail) { // When both the region and the buddy are free, merge those adjacent // free blocks. if (region->free && buddy->free && region->size == buddy->size) { region->size <<= 1; const Size region_size = region->size; if (_size <= region_size && (!closest || region_size <= closest->size)) { closest = region; } if ((region = next(buddy)) < _tail) { buddy = next(region); } } else { if (closest) { closest_size = closest->size; } // Check the region block. const Size region_size = region->size; if (region->free && _size <= region_size && (!closest || region_size <= closest->size)) { closest = region; closest_size = region_size; } // Check the buddy block. const Size buddy_size = buddy->size; if (buddy->free && _size <= buddy_size && (!closest || buddy_size <= closest->size)) { closest = buddy; closest_size = buddy_size; } // The buddy has been split up into smaller blocks. if (region_size > buddy_size) { region = buddy; buddy = next(buddy); } else if ((region = next(buddy)) < _tail) { // Skip the base and buddy region for the next iteration. buddy = next(region); } } } if (closest) { // Perfect match. if (closest_size == _size) { return closest; } // Split |current| in halves continually until it optimally fits |_size|. return divide(closest, _size); } // Potentially out of memory. return nullptr; } // Performs a single level merge of adjacent free blocks in the list given // by |_head| and |_tail|. static bool merge_free(Block* _head, Block* _tail) { Block* region = _head; Block* buddy = next(region); bool modified = false; while (region < _tail && buddy < _tail) { // Both the region and buddy are free. if (region->free && buddy->free && region->size == buddy->size) { // Merge the blocks back into one, larger one. region->size <<= 1; if ((region = next(region)) < _tail) { buddy = next(region); } modified = true; } else if (region->size > buddy->size) { // The buddy block has been split into smaller blocks. region = buddy; buddy = next(buddy); } else if ((region = next(buddy)) < _tail) { // Skip the base and buddy region for the next iteration. buddy = next(region); } } return modified; } BuddyAllocator::BuddyAllocator(Byte* _data, Size _size) { // Ensure |_data| and |_size| are multiples of |ALIGNMENT|. RX_ASSERT(reinterpret_cast<UintPtr>(_data) % ALIGNMENT == 0, "_data not aligned on %zu-byte boundary", ALIGNMENT); RX_ASSERT(_size % ALIGNMENT == 0, "_size not a multiple of %zu", ALIGNMENT); // Ensure |_size| is a power of two. RX_ASSERT((_size & (_size - 1)) == 0, "_size not a power of two"); // Create the root block structure. Block* head = reinterpret_cast<Block*>(_data); head->size = _size; head->free = true; m_head = reinterpret_cast<void*>(head); m_tail = reinterpret_cast<void*>(next(head)); } Byte* BuddyAllocator::allocate(Size _size) { Concurrency::ScopeLock lock{m_lock}; return allocate_unlocked(_size); } Byte* BuddyAllocator::reallocate(void* _data, Size _size) { Concurrency::ScopeLock lock{m_lock}; return reallocate_unlocked(_data, _size); } void BuddyAllocator::deallocate(void* _data) { Concurrency::ScopeLock lock{m_lock}; deallocate_unlocked(_data); } Byte* BuddyAllocator::allocate_unlocked(Size _size) { const auto size = needed(_size); const auto head = reinterpret_cast<Block*>(m_head); const auto tail = reinterpret_cast<Block*>(m_tail); auto find = find_available(head, tail, size); if (RX_HINT_LIKELY(find)) { find->free = false; return reinterpret_cast<Byte*>(find + 1); } // Merge free blocks until they're all merged. while (merge_free(head, tail)) { ; } // Search again for a free block. if ((find = find_available(head, tail, size))) { find->free = false; return reinterpret_cast<Byte*>(find + 1); } // Out of memory. return nullptr; } Byte* BuddyAllocator::reallocate_unlocked(void* _data, Size _size) { if (RX_HINT_LIKELY(_data)) { const auto region = reinterpret_cast<Block*>(_data) - 1; const auto head = reinterpret_cast<Block*>(m_head); const auto tail = reinterpret_cast<Block*>(m_tail); RX_ASSERT(region >= head, "out of heap"); RX_ASSERT(region <= tail - 1, "out of heap"); // No need to resize. if (region->size >= needed(_size)) { return reinterpret_cast<Byte*>(_data); } // Create a new allocation. auto resize = allocate_unlocked(_size); if (RX_HINT_LIKELY(resize)) { memcpy(resize, _data, region->size - sizeof *region); deallocate_unlocked(_data); return resize; } // Out of memory. return nullptr; } return allocate_unlocked(_size); } void BuddyAllocator::deallocate_unlocked(void* _data) { if (RX_HINT_LIKELY(_data)) { const auto region = reinterpret_cast<Block*>(_data) - 1; const auto head = reinterpret_cast<Block*>(m_head); const auto tail = reinterpret_cast<Block*>(m_tail); RX_ASSERT(region >= head, "out of heap"); RX_ASSERT(region <= tail - 1, "out of heap"); region->free = true; } } } // namespace rx::memory
28.397849
82
0.649628
DethRaid
9c753066d459755141cd3223d7174009bedff3ca
2,172
cpp
C++
rmw_connext_dynamic_cpp/src/publish_take.cpp
ross-desmond/rmw_connext
6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9
[ "Apache-2.0" ]
24
2017-11-15T09:16:24.000Z
2022-03-30T07:32:15.000Z
rmw_connext_dynamic_cpp/src/publish_take.cpp
ross-desmond/rmw_connext
6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9
[ "Apache-2.0" ]
394
2015-03-07T01:00:13.000Z
2022-02-03T15:40:52.000Z
rmw_connext_dynamic_cpp/src/publish_take.cpp
ross-desmond/rmw_connext
6c22e0a4a76c7ca6ffe2340e0009eaeca40789e9
[ "Apache-2.0" ]
41
2015-08-13T02:07:08.000Z
2021-07-07T03:41:44.000Z
// Copyright 2014-2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "./publish_take.hpp" #include "./templates.hpp" bool using_introspection_c_typesupport(const char * typesupport_identifier) { return typesupport_identifier == rosidl_typesupport_introspection_c__identifier; } bool using_introspection_cpp_typesupport(const char * typesupport_identifier) { return typesupport_identifier == rosidl_typesupport_introspection_cpp::typesupport_identifier; } bool _publish(DDS_DynamicData * dynamic_data, const void * ros_message, const void * untyped_members, const char * typesupport) { if (using_introspection_c_typesupport(typesupport)) { return publish<rosidl_typesupport_introspection_c__MessageMembers>( dynamic_data, ros_message, untyped_members); } else if (using_introspection_cpp_typesupport(typesupport)) { return publish<rosidl_typesupport_introspection_cpp::MessageMembers>( dynamic_data, ros_message, untyped_members); } RMW_SET_ERROR_MSG("Unknown typesupport identifier") return false; } bool _take(DDS_DynamicData * dynamic_data, void * ros_message, const void * untyped_members, const char * typesupport) { if (using_introspection_c_typesupport(typesupport)) { return take<rosidl_typesupport_introspection_c__MessageMembers>( dynamic_data, ros_message, untyped_members); } else if (using_introspection_cpp_typesupport(typesupport)) { return take<rosidl_typesupport_introspection_cpp::MessageMembers>( dynamic_data, ros_message, untyped_members); } RMW_SET_ERROR_MSG("Unknown typesupport identifier") return false; }
38.105263
82
0.785912
ross-desmond
9c7732f6fd84f13a63693fd3c95cd5fd8badee67
21,660
cpp
C++
src/xma/src/xmaapi/xmaxclbin.cpp
cucapra/XRT
60f98c50f5c69fd35468309df3d8c85324b813ba
[ "Apache-2.0" ]
null
null
null
src/xma/src/xmaapi/xmaxclbin.cpp
cucapra/XRT
60f98c50f5c69fd35468309df3d8c85324b813ba
[ "Apache-2.0" ]
null
null
null
src/xma/src/xmaapi/xmaxclbin.cpp
cucapra/XRT
60f98c50f5c69fd35468309df3d8c85324b813ba
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018, Xilinx Inc - All rights reserved * Xilinx SDAccel Media Accelerator API * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://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 <fstream> #include <stdexcept> #include "xclbin.h" #include "app/xmaerror.h" #include "app/xmalogger.h" #include "lib/xmaxclbin.h" #include "core/common/config_reader.h" #include "core/common/xclbin_parser.h" #include "app/xma_utils.hpp" #include "lib/xma_utils.hpp" #define XMAAPI_MOD "xmaxclbin" /* Private function */ static int get_xclbin_iplayout(const char *buffer, XmaXclbinInfo *xclbin_info); static int get_xclbin_mem_topology(const char *buffer, XmaXclbinInfo *xclbin_info); static int get_xclbin_connectivity(const char *buffer, XmaXclbinInfo *xclbin_info); std::vector<char> xma_xclbin_file_open(const std::string& xclbin_name) { xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "Loading %s ", xclbin_name.c_str()); std::ifstream infile(xclbin_name, std::ios::binary | std::ios::ate); if (!infile) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Failed to open xclbin file"); throw std::runtime_error("Failed to open xclbin file"); } std::streamsize xclbin_size = infile.tellg(); infile.seekg(0, std::ios::beg); std::vector<char> xclbin_buffer; try { xclbin_buffer.reserve(xclbin_size); } catch (const std::bad_alloc& ex) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not allocate buffer for file %s ", xclbin_name.c_str()); xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Buffer allocation error: %s ", ex.what()); throw; } catch (...) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not allocate buffer for xclbin file %s ", xclbin_name.c_str()); throw; } infile.read(xclbin_buffer.data(), xclbin_size); if (infile.gcount() != xclbin_size) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Unable to read full xclbin file %s ", xclbin_name.c_str()); throw std::runtime_error("Unable to read full xclbin file"); } return xclbin_buffer; } static int32_t kernel_max_channel_id(const ip_data* ip, std::string kernel_channels) { if (kernel_channels.empty()) return -1; std::string knm = std::string(reinterpret_cast<const char*>(ip->m_name)); knm = knm.substr(0,knm.find(":")); auto pos1 = kernel_channels.find("{"+knm+":"); if (pos1 == std::string::npos) return -1; auto pos2 = kernel_channels.find("}",pos1); if (pos2 == std::string::npos || pos2 < pos1+knm.size()+2) return -2; auto ctxid_str = kernel_channels.substr(pos1+knm.size()+2,pos2); auto ctxid = std::stoi(ctxid_str); if (ctxid < 0 || ctxid > 31) return -3; return ctxid; } static int get_xclbin_iplayout(const char *buffer, XmaXclbinInfo *xclbin_info) { const axlf *xclbin = reinterpret_cast<const axlf *>(buffer); const axlf_section_header *ip_hdr = xclbin::get_axlf_section(xclbin, IP_LAYOUT); if (ip_hdr) { const char *data = &buffer[ip_hdr->m_sectionOffset]; const ip_layout *ipl = reinterpret_cast<const ip_layout *>(data); xclbin_info->number_of_kernels = 0; xclbin_info->number_of_hardware_kernels = 0; std::string kernel_channels_info = xrt_core::config::get_kernel_channel_info(); xclbin_info->cu_addrs_sorted = xrt_core::xclbin::get_cus(ipl, false); bool has_cuisr = xrt_core::xclbin::get_cuisr(xclbin); if (!has_cuisr) { xma_logmsg(XMA_WARNING_LOG, XMAAPI_MOD, "One or more CUs do not support interrupt. Use RTL Wizard or Vitis for xclbin creation "); } auto& xma_ip_layout = xclbin_info->ip_layout; for (int i = 0; i < ipl->m_count; i++) { if (ipl->m_ip_data[i].m_type != IP_KERNEL) continue; if (xma_ip_layout.size() == MAX_XILINX_KERNELS) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d kernels per device ", MAX_XILINX_KERNELS); throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_XILINX_KERNELS) + " kernels per device"); } XmaIpLayout temp_ip_layout; temp_ip_layout.base_addr = ipl->m_ip_data[i].m_base_address; temp_ip_layout.kernel_name = std::string((char*)ipl->m_ip_data[i].m_name); using xarg = xrt_core::xclbin::kernel_argument; static constexpr size_t no_index = xarg::no_index; auto args = xrt_core::xclbin::get_kernel_arguments(xclbin, temp_ip_layout.kernel_name); //Note: args are sorted by index; Assuming that offset will increase with arg index //This is fair assumption; v++ or HLS decides on these offset values std::vector<xarg> args2; std::copy_if(args.begin(), args.end(), std::back_inserter(args2), [](const xarg& y){return y.index != no_index;}); temp_ip_layout.arg_start = -1; temp_ip_layout.regmap_size = -1; if (args2.size() > 0) { temp_ip_layout.arg_start = args2[0].offset; auto& last = args2.back(); temp_ip_layout.regmap_size = last.offset + last.size; if (temp_ip_layout.arg_start < 0x10) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s doesn't meet argument register map spec of HLS/RTL Wizard kernels ", temp_ip_layout.kernel_name.c_str()); throw std::runtime_error("kernel doesn't meet argument register map spec of HLS/RTL Wizard kernels"); } } else { std::string knm = temp_ip_layout.kernel_name.substr(0,temp_ip_layout.kernel_name.find(":")); args = xrt_core::xclbin::get_kernel_arguments(xclbin, knm); std::vector<xarg> args3; std::copy_if(args.begin(), args.end(), std::back_inserter(args3), [](const xarg& y){return y.index != no_index;}); if (args3.size() > 0) { temp_ip_layout.arg_start = args3[0].offset; auto& last = args3.back(); temp_ip_layout.regmap_size = last.offset + last.size; if (temp_ip_layout.arg_start < 0x10) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s doesn't meet argument register map spec of HLS/RTL Wizard kernels ", temp_ip_layout.kernel_name.c_str()); throw std::runtime_error("kernel doesn't meet argument register map spec of HLS/RTL Wizard kernels"); } } } temp_ip_layout.kernel_channels = false; xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %lu, kernel name = %s, base_addr = %lx ", xma_ip_layout.size(), temp_ip_layout.kernel_name.c_str(), temp_ip_layout.base_addr); if (temp_ip_layout.regmap_size > MAX_KERNEL_REGMAP_SIZE) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s register map size exceeds max limit. regmap_size: %d, max regmap_size: %d . Will use only max regmap_size", temp_ip_layout.kernel_name.c_str(), temp_ip_layout.regmap_size, MAX_KERNEL_REGMAP_SIZE); //DRM IPs have registers at high offset temp_ip_layout.regmap_size = MAX_KERNEL_REGMAP_SIZE; //throw std::runtime_error("kernel regmap exceed's max size"); } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s:- arg_start: 0x%x, regmap_size: 0x%x", temp_ip_layout.kernel_name.c_str(), temp_ip_layout.arg_start, temp_ip_layout.regmap_size); auto cu_data = xrt_core::xclbin::get_cus(ipl, temp_ip_layout.kernel_name); if (cu_data.size() > 0) { if (((cu_data[0]->properties & IP_CONTROL_MASK) >> IP_CONTROL_SHIFT) == AP_CTRL_CHAIN) { int32_t max_channel_id = kernel_max_channel_id(cu_data[0], kernel_channels_info); if (max_channel_id >= 0) { xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. channel_id will be handled by XMA. host app and plugins should not use reserved channle_id registers. Max channel_id is: %d ", temp_ip_layout.kernel_name.c_str(), max_channel_id); temp_ip_layout.kernel_channels = true; temp_ip_layout.max_channel_id = (uint32_t)max_channel_id; } else { if (max_channel_id == -1) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. Use kernel_channels xrt.ini setting to enable handling of channel_id by XMA. Treatng it as legacy dataflow kernel and channels to be managed by host app and plugins ", temp_ip_layout.kernel_name.c_str()); } else if (max_channel_id == -2) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. xrt.ini kernel_channels setting has incorrect format. setting found is: %s ", temp_ip_layout.kernel_name.c_str(), kernel_channels_info.c_str()); throw std::runtime_error("Incorrect dataflow kernel ini setting"); } else if (max_channel_id == -3) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. xrt.ini kernel_channels setting only supports channel_ids from 0 to 31. setting found is: %s ", temp_ip_layout.kernel_name.c_str(), kernel_channels_info.c_str()); throw std::runtime_error("Incorrect dataflow kernel ini setting"); } } } else { xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "kernel \"%s\" is a legacy kernel. Channels to be managed by host app and plugins ", temp_ip_layout.kernel_name.c_str()); } } else { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "No CU for kernel %s in xclbin", temp_ip_layout.kernel_name.c_str()); throw std::runtime_error("Unexpected error. CU not found in xclbin"); } temp_ip_layout.soft_kernel = false; xma_ip_layout.emplace_back(std::move(temp_ip_layout)); } xclbin_info->number_of_hardware_kernels = xma_ip_layout.size(); if (xclbin_info->number_of_hardware_kernels != xclbin_info->cu_addrs_sorted.size()) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Num of hardware kernels on this device = %ud. But num of sorted kernels = %lu", xclbin_info->number_of_hardware_kernels, xclbin_info->cu_addrs_sorted.size()); throw std::runtime_error("Unable to get sorted kernel list"); } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of hardware kernels on this device = %ud ", xclbin_info->number_of_hardware_kernels); uint32_t num_soft_kernels = 0; //Handle soft kernels just like another hardware IP_Layout kernel //soft kernels to follow hardware kernels. so soft kenrel index will start after hardware kernels auto soft_kernels = xrt_core::xclbin::get_softkernels(xclbin); for (auto& sk: soft_kernels) { if (num_soft_kernels + sk.ninst > MAX_XILINX_SOFT_KERNELS) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d soft kernels per device ", MAX_XILINX_SOFT_KERNELS); throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_XILINX_SOFT_KERNELS) + " soft kernels per device"); } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "soft kernel name = %s, version = %s, symbol name = %s, num of instances = %d ", sk.mpo_name.c_str(), sk.mpo_version.c_str(), sk.symbol_name.c_str(), sk.ninst); XmaIpLayout temp_ip_layout; std::string str_tmp1; for (uint32_t i = 0; i < sk.ninst; i++) { str_tmp1 = std::string(sk.mpo_name); str_tmp1 += "_"; str_tmp1 += std::to_string(i); temp_ip_layout.kernel_name = str_tmp1; temp_ip_layout.soft_kernel = true; temp_ip_layout.base_addr = 0; temp_ip_layout.arg_start = -1; temp_ip_layout.regmap_size = -1; xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %lu, soft kernel name = %s ", xma_ip_layout.size(), temp_ip_layout.kernel_name.c_str()); xma_ip_layout.emplace_back(std::move(temp_ip_layout)); num_soft_kernels++; } } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of soft kernels on this device = %ud ", num_soft_kernels); xclbin_info->number_of_kernels = xma_ip_layout.size(); xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of total kernels on this device = %ud ", xclbin_info->number_of_kernels); xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " "); const axlf_section_header *xml_hdr = xclbin::get_axlf_section(xclbin, EMBEDDED_METADATA); if (xml_hdr) { char *xml_data = const_cast<char*>(&buffer[xml_hdr->m_sectionOffset]); uint64_t xml_size = xml_hdr->m_sectionSize; if (xml_size > 0 && xml_size < 500000) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "XML MetaData is:"); xma_core::utils::streambuf xml_streambuf(xml_data, xml_size); std::istream xml_stream(&xml_streambuf); std::string line; while(std::getline(xml_stream, line)) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s", line.c_str()); } } } else { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "XML MetaData is missing"); } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " "); const axlf_section_header *kv_hdr = xclbin::get_axlf_section(xclbin, KEYVALUE_METADATA); if (kv_hdr) { char *kv_data = const_cast<char*>(&buffer[kv_hdr->m_sectionOffset]); uint64_t kv_size = kv_hdr->m_sectionSize; if (kv_size > 0 && kv_size < 200000) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Key-Value MetaData is:"); xma_core::utils::streambuf kv_streambuf(kv_data, kv_size); std::istream kv_stream(&kv_streambuf); std::string line; while(std::getline(kv_stream, line)) { uint32_t lsize = line.size(); uint32_t pos = 0; while (pos < lsize) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s", line.substr(pos, MAX_KERNEL_NAME).c_str()); pos += MAX_KERNEL_NAME; } } } } else { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Key-Value Data is not present in xclbin"); } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " "); } else { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find IP_LAYOUT in xclbin ip_hdr=%p ", ip_hdr); throw std::runtime_error("Could not find IP_LAYOUT in xclbin"); } uuid_copy(xclbin_info->uuid, xclbin->m_header.uuid); return XMA_SUCCESS; } static int get_xclbin_mem_topology(const char *buffer, XmaXclbinInfo *xclbin_info) { const axlf *xclbin = reinterpret_cast<const axlf *>(buffer); const axlf_section_header *mem_hdr = xrt_core::xclbin::get_axlf_section(xclbin, MEM_TOPOLOGY); if (!mem_hdr) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find MEM TOPOLOGY in xclbin "); throw std::runtime_error("Could not find MEM TOPOLOGY in xclbin file"); } const char *data3 = &buffer[mem_hdr->m_sectionOffset]; auto mem_topo1 = reinterpret_cast<const mem_topology *>(data3); auto mem_topo2 = const_cast<mem_topology*>(mem_topo1); xclbin_info->has_mem_groups = false; const axlf_section_header *mem_grp_hdr = xrt_core::xclbin::get_axlf_section(xclbin, ASK_GROUP_TOPOLOGY); if (mem_grp_hdr) { const char *data2 = &buffer[mem_grp_hdr->m_sectionOffset]; auto mem_grp_topo = reinterpret_cast<const mem_topology *>(data2); if (mem_grp_topo->m_count > mem_topo1->m_count) { xclbin_info->has_mem_groups = true; mem_topo2 = const_cast<mem_topology*>(mem_grp_topo); } } auto mem_topo = reinterpret_cast<const mem_topology *>(mem_topo2); auto& xma_mem_topology = xclbin_info->mem_topology; xclbin_info->number_of_mem_banks = mem_topo->m_count; xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "MEM TOPOLOGY - %ud banks ",xclbin_info->number_of_mem_banks); if (xclbin_info->number_of_mem_banks > MAX_DDR_MAP) { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d mem banks ", MAX_DDR_MAP); throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_DDR_MAP) + " mem banks"); } for (int i = 0; i < mem_topo->m_count; i++) { XmaMemTopology temp_mem_topology; temp_mem_topology.m_type = mem_topo->m_mem_data[i].m_type; temp_mem_topology.m_used = mem_topo->m_mem_data[i].m_used; temp_mem_topology.m_size = mem_topo->m_mem_data[i].m_size; temp_mem_topology.m_base_address = mem_topo->m_mem_data[i].m_base_address; //m_tag is 16 chars auto tmp_ptr = mem_topo->m_mem_data[i].m_tag; temp_mem_topology.m_tag = {tmp_ptr, std::find(tmp_ptr, tmp_ptr+16, '\0')};//magic 16 from xclbin.h xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index=%d, tag=%s, type = %ud, used = %ud, size = %lx, base = %lx ", i,temp_mem_topology.m_tag.c_str(), temp_mem_topology.m_type, temp_mem_topology.m_used, temp_mem_topology.m_size, temp_mem_topology.m_base_address); xma_mem_topology.emplace_back(std::move(temp_mem_topology)); } return XMA_SUCCESS; } static int get_xclbin_connectivity(const char *buffer, XmaXclbinInfo *xclbin_info) { const axlf *xclbin = reinterpret_cast<const axlf *>(buffer); const axlf_section_header *ip_hdr = xrt_core::xclbin::get_axlf_section(xclbin, ASK_GROUP_CONNECTIVITY); if (ip_hdr) { const char *data = &buffer[ip_hdr->m_sectionOffset]; const connectivity *axlf_conn = reinterpret_cast<const connectivity *>(data); auto& xma_connectivity = xclbin_info->connectivity; xclbin_info->number_of_connections = axlf_conn->m_count; xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "CONNECTIVITY - %d connections ",xclbin_info->number_of_connections); for (int i = 0; i < axlf_conn->m_count; i++) { XmaAXLFConnectivity temp_conn; temp_conn.arg_index = axlf_conn->m_connection[i].arg_index; temp_conn.m_ip_layout_index = axlf_conn->m_connection[i].m_ip_layout_index; temp_conn.mem_data_index = axlf_conn->m_connection[i].mem_data_index; xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %d, arg_idx = %d, ip_idx = %d, mem_idx = %d ", i, temp_conn.arg_index, temp_conn.m_ip_layout_index, temp_conn.mem_data_index); xma_connectivity.emplace_back(std::move(temp_conn)); } } else { xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find CONNECTIVITY in xclbin ip_hdr=%p ", ip_hdr); throw std::runtime_error("Could not find CONNECTIVITY in xclbin file"); } return XMA_SUCCESS; } int xma_xclbin_info_get(const char *buffer, XmaXclbinInfo *info) { get_xclbin_mem_topology(buffer, info); get_xclbin_connectivity(buffer, info); get_xclbin_iplayout(buffer, info); memset(info->ip_ddr_mapping, 0, sizeof(info->ip_ddr_mapping)); uint64_t tmp_ddr_map = 0; for(uint32_t c = 0; c < info->number_of_connections; c++) { auto& xma_conn = info->connectivity[c]; tmp_ddr_map = 1; tmp_ddr_map = tmp_ddr_map << (xma_conn.mem_data_index); info->ip_ddr_mapping[xma_conn.m_ip_layout_index] |= tmp_ddr_map; } xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "CU DDR connections bitmap:"); for(uint32_t i = 0; i < info->number_of_hardware_kernels; i++) { xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "\t%s - 0x%016llx ",info->ip_layout[i].kernel_name.c_str(), (unsigned long long)info->ip_ddr_mapping[i]); } return XMA_SUCCESS; } int xma_xclbin_map2ddr(uint64_t bit_map, int32_t* ddr_bank, bool has_mem_grps) { //64 bits based on MAX_DDR_MAP = 64 int ddr_bank_idx = 0; if (!has_mem_grps) { while (bit_map != 0) { if (bit_map & 1) { *ddr_bank = ddr_bank_idx; return XMA_SUCCESS; } ddr_bank_idx++; bit_map = bit_map >> 1; } } else {//For Memory Groups use last group as default memory group; For HBM groups ddr_bank_idx = 63; uint64_t tmp_int = 1ULL << 63; while (bit_map != 0) { if (bit_map & tmp_int) { *ddr_bank = ddr_bank_idx; return XMA_SUCCESS; } ddr_bank_idx--; bit_map = bit_map << 1; } } *ddr_bank = -1; return XMA_ERROR; }
50.964706
307
0.638873
cucapra
9c78efe1b9442070067cb4dc4d1db31a28ea8a09
6,801
cpp
C++
repeat_masker_src/seeder.cpp
yatisht/SegAlign
d5c2816cfb11890c31bb68dc202cf16346660d42
[ "MIT" ]
28
2020-08-03T14:23:40.000Z
2022-03-21T10:04:04.000Z
repeat_masker_src/seeder.cpp
yatisht/SegAlign
d5c2816cfb11890c31bb68dc202cf16346660d42
[ "MIT" ]
17
2020-06-25T23:20:20.000Z
2022-02-21T21:52:08.000Z
repeat_masker_src/seeder.cpp
yatisht/SegAlign
d5c2816cfb11890c31bb68dc202cf16346660d42
[ "MIT" ]
6
2020-07-22T03:20:04.000Z
2022-01-17T23:26:36.000Z
#include "graph.h" #include <algorithm> #include <assert.h> #include "store.h" #include "ntcoding.h" #include "seed_filter.h" #include "tbb/scalable_allocator.h" std::atomic<uint64_t> seeder_body::num_seed_hits(0); std::atomic<uint64_t> seeder_body::num_seeds(0); std::atomic<uint64_t> seeder_body::num_hsps(0); std::atomic<uint32_t> seeder_body::total_xdrop(0); std::atomic<uint32_t> seeder_body::num_seeded_regions(0); bool sort_hsp(segmentPair x, segmentPair y){ if(x.query_start < y.query_start) return true; else if(x.query_start == y.query_start){ if(x.len < y.len) return true; else return false; } return false; } printer_input seeder_body::operator()(seeder_input input) { auto &payload = get<0>(input); size_t token = get<1>(input); auto &block_data = get<0>(payload); auto &interval_data = get<1>(payload); size_t block_start = block_data.start; uint32_t block_len = block_data.len; int block_index = block_data.index; uint32_t start_pos = interval_data.start; uint32_t end_pos = interval_data.end; uint32_t ref_start = interval_data.ref_start; uint32_t ref_end = interval_data.ref_end; uint32_t num_invoked = interval_data.num_invoked; uint32_t num_intervals = interval_data.num_intervals; uint32_t start_pos_rc = block_len - 1 - end_pos; uint32_t end_pos_rc = block_len - 1 - start_pos; size_t rc_block_start = cfg.seq_len - 1 - block_start - (block_len - 1); uint64_t kmer_index; uint64_t transition_index; uint64_t seed_offset; std::vector<segmentPair> total_hsps; total_hsps.clear(); uint8_t* int_count; int_count = (uint8_t*) scalable_calloc(block_len, sizeof(uint8_t)); std::vector<Segment> total_intervals; total_intervals.clear(); int32_t start; int32_t end; uint32_t old_num_hsps = 0; uint32_t new_num_hsps = 0; fprintf (stderr, "Chromosome block %u interval %u/%u (%lu:%lu) with ref (%u:%u) rc (%lu:%lu)\n", block_index, num_invoked, num_intervals, block_start+start_pos, block_start+end_pos, ref_start, ref_end, rc_block_start+start_pos_rc, rc_block_start+end_pos_rc); for (uint32_t i = start_pos; i < end_pos; i += cfg.wga_chunk_size) { //chunk limit positions start = i; end = std::min(start + cfg.wga_chunk_size, end_pos); if(cfg.strand == "plus" || cfg.strand == "both"){ std::vector<uint64_t> seed_offset_vector; seed_offset_vector.clear(); //start to end position in the chunk for (uint32_t j = start; j < end; j++) { kmer_index = GetKmerIndexAtPos(seq_DRAM->buffer, block_start+j, cfg.seed.size); if (kmer_index != ((uint32_t) 1 << 31)) { seed_offset = (kmer_index << 32) + j; seed_offset_vector.push_back(seed_offset); if (cfg.seed.transition) { for (int t=0; t < cfg.seed.kmer_size; t++) { if (IsTransitionAtPos(t) == 1) { transition_index = (kmer_index ^ (TRANSITION_MASK << (2*t))); seed_offset = (transition_index << 32) + j; seed_offset_vector.push_back(seed_offset); } } } } } if(seed_offset_vector.size() > 0){ seeder_body::num_seeds += seed_offset_vector.size(); std::vector<segmentPair> anchors = g_SeedAndFilter(seed_offset_vector, false, ref_start, ref_end); seeder_body::num_seed_hits += anchors[0].score; if(anchors.size() > 1){ total_hsps.insert(total_hsps.end(), anchors.begin()+1, anchors.end()); seeder_body::num_hsps += anchors.size()-1; } } } if(cfg.strand == "minus" || cfg.strand == "both"){ //chunk limit positions start = block_len - 1 - end; end = std::min(start + cfg.wga_chunk_size, end_pos_rc); std::vector<uint64_t> seed_offset_vector; seed_offset_vector.clear(); for (uint32_t j = start; j < end; j++) { kmer_index = GetKmerIndexAtPos(seq_rc_DRAM->buffer, (rc_block_start+j), cfg.seed.size); if (kmer_index != ((uint32_t) 1 << 31)) { seed_offset = (kmer_index << 32) + j; seed_offset_vector.push_back(seed_offset); if (cfg.seed.transition) { for (int t=0; t < cfg.seed.kmer_size; t++) { if (IsTransitionAtPos(t) == 1) { transition_index = (kmer_index ^ (TRANSITION_MASK << (2*t))); seed_offset = (transition_index << 32) + j; seed_offset_vector.push_back(seed_offset); } } } } } if(seed_offset_vector.size() > 0){ seeder_body::num_seeds += seed_offset_vector.size(); std::vector<segmentPair> anchors = g_SeedAndFilter(seed_offset_vector, true, ref_start, ref_end); seeder_body::num_seed_hits += anchors[0].score; if(anchors.size() > 1){ total_hsps.insert(total_hsps.end(), anchors.rbegin(), anchors.rend()-1); seeder_body::num_hsps += anchors.size()-1; } } } if(total_hsps.size() > 0){ std::sort(total_hsps.begin(), total_hsps.end(), sort_hsp); for (auto hsp: total_hsps) { for(int j = hsp.query_start; j < (hsp.query_start + hsp.len); j++){ int_count[j]++; } } total_hsps.clear(); } } int run = 0; int query_start = 0; int len = 0; for(int i = 0; i < block_len; i++){ if(int_count[i] >= cfg.M){ if(run == 0){ run = 1; query_start = i; } len++; } else{ if(run == 1){ run = 0; Segment s; s.query_start = query_start; s.len = len; total_intervals.push_back(s); } query_start = 0; len = 0; } } scalable_free(int_count); seeder_body::num_seeded_regions += 1; seeder_body::total_xdrop += 1; return printer_input(printer_payload(block_data, num_invoked, total_intervals), token); }
34.876923
262
0.541832
yatisht
9c79c270a168e07c7d4af0cacba0bf2a13d3971c
2,895
cpp
C++
ngraph/core/src/op/reduce_logical_and.cpp
maksimvlasov/openvino
be8600af38dd6ab39422b3db496c0fb73c156938
[ "Apache-2.0" ]
1
2021-12-30T05:47:43.000Z
2021-12-30T05:47:43.000Z
ngraph/core/src/op/reduce_logical_and.cpp
maksimvlasov/openvino
be8600af38dd6ab39422b3db496c0fb73c156938
[ "Apache-2.0" ]
34
2020-11-19T14:29:56.000Z
2022-02-21T13:13:22.000Z
ngraph/core/src/op/reduce_logical_and.cpp
likholat/openvino
322c87411399f83ab9c9b99c941c1ba2ed623214
[ "Apache-2.0" ]
1
2021-01-21T12:09:13.000Z
2021-01-21T12:09:13.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/reduce_logical_and.hpp" #include <ngraph/validation_util.hpp> #include "itt.hpp" #include "ngraph/log.hpp" #include "ngraph/op/util/evaluate_helpers.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/runtime/reference/logical_reduction.hpp" using namespace ngraph; using namespace std; OPENVINO_RTTI_DEFINITION(op::v1::ReduceLogicalAnd, "ReduceLogicalAnd", 1, util::LogicalReductionKeepDims); op::v1::ReduceLogicalAnd::ReduceLogicalAnd(const Output<Node>& data, const Output<Node>& reduction_axes, const bool keep_dims) : LogicalReductionKeepDims(data, reduction_axes, keep_dims) { constructor_validate_and_infer_types(); } shared_ptr<Node> op::v1::ReduceLogicalAnd::clone_with_new_inputs(const OutputVector& new_args) const { NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_clone_with_new_inputs); check_new_args_count(this, new_args); return make_shared<op::v1::ReduceLogicalAnd>(new_args.at(0), new_args.at(1), get_keep_dims()); } namespace reduce_and { bool evaluate_reduce_logical_and(const HostTensorPtr& data, const HostTensorPtr& out, const AxisSet& reduction_axes, bool keep_dims) { out->set_shape(reduce(data->get_shape(), reduction_axes, keep_dims)); try { runtime::reference::reduce_logical_and(data->get_data_ptr<char>(), out->get_data_ptr<char>(), data->get_shape(), reduction_axes); return true; } catch (const ngraph_error& e) { NGRAPH_WARN << e.what(); return false; } } } // namespace reduce_and bool op::v1::ReduceLogicalAnd::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const { NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_evaluate); NGRAPH_CHECK(validate_host_tensor_vector(inputs, 2)); NGRAPH_CHECK(validate_host_tensor_vector(outputs, 1)); const auto& data = inputs[0]; const auto& axes = inputs[1]; const auto& out = outputs[0]; if (data->get_element_type() != element::boolean || !axes->get_element_type().is_integral_number()) { return false; } const auto reduction_axes = get_normalized_axes_from_tensor(axes, data->get_partial_shape().rank(), get_friendly_name()); return reduce_and::evaluate_reduce_logical_and(data, out, reduction_axes, get_keep_dims()); } bool op::v1::ReduceLogicalAnd::has_evaluate() const { NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_has_evaluate); return get_input_element_type(0) == element::boolean && get_input_element_type(1).is_integral_number(); }
40.774648
112
0.667703
maksimvlasov
9c7bb56013c79a1f386e8d97d0786a977e22fb38
1,967
cpp
C++
601-700/647-Palindromic_Substrings-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
601-700/647-Palindromic_Substrings-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
601-700/647-Palindromic_Substrings-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given a string, your task is to count how many palindromic substrings in // this string. // The substrings with different start indexes or end indexes are counted as // different substrings even they consist of same characters. // Example 1: // Input: "abc" // Output: 3 // Explanation: Three palindromic strings: "a", "b", "c". // Example 2: // Input: "aaa" // Output: 6 // Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". // Note: // The input string length won't exceed 1000. // Manacher’s Algorithm // https://articles.leetcode.com/longest-palindromic-substring-part-ii/ // https://www.felix021.com/blog/read.php?2040 class Solution { string prepare(const string &s) { stringstream Ts("^"); for (auto &&c : s) Ts << '#' << c; if (!s.empty()) Ts << '#'; Ts << '$'; return Ts.str(); } public: int countSubstrings(string s) { string T = prepare(s); // transformed string vector<int> P(T.size()); // longest palindrome int C = 0, R = 0; // center, right for (int i = 1; i < T.size() - 1; ++i) { P[i] = R > i ? min(R - i, P[2 * C - i]) : 0; while (T[i + P[i] + 1] == T[i - P[i] - 1]) ++P[i]; if (i + P[i] > R) { C = i; R = i + P[i]; } } int ret = 0; for (auto &&pl : P) ret += (pl + 1) / 2; return ret; } }; // method 2, extend center class Solution { public: int countSubstrings(string S) { int n = S.size(); int ret = 0, l, r; for (int i = 0; i < n; ++i) { l = r = i; while (l >= 0 && r < n && S[l--] == S[r++]) ++ret; l = i, r = i + 1; while (l >= 0 && r < n && S[l--] == S[r++]) ++ret; } return ret; } }; // method 3, dp, TODO
23.141176
76
0.457041
ysmiles